id
int64
1
2k
content
stringlengths
272
88.9k
title
stringlengths
3
77
title_slug
stringlengths
3
79
question_content
stringlengths
230
5k
question_hints
stringclasses
695 values
tag
stringclasses
618 values
level
stringclasses
3 values
similar_question_ids
stringclasses
822 values
1,295
hello municipal i am aayushi roy jo welcome to my channel twisted tours to introduce solution box open list code problem numbers with number of this movement and subscribe like every time subscribe problem se give me the number 90 vihar two example give me value of 5a 5216 From these and without this to fix well and from Z2 winters which have even thaw in are 500 600 800 in this case will return top number 90 12512 feature skin or input are name specified 019 allotment of labs 2051 name no elementary middle he will return Of Account 2009 Subscribe 2019 Elements For Converting Into Four Wheel Buddha Account Navratri Nanga Khol Do Ki And Developed By Submitting Distract You Can Find All The Code Deposit Link Description Box Mein Ho To Please Like Subscribe Interest In Learning Video Positive A Solution Bathroom Please subscribe comment box strongly recommend you to join telegram channel subscribe and develop portion help improve it connect with another place in the survey description box give with more videos from this loot
Find Numbers with Even Number of Digits
minimum-garden-perimeter-to-collect-enough-apples
Given an array `nums` of integers, return how many of them contain an **even number** of digits. **Example 1:** **Input:** nums = \[12,345,2,6,7896\] **Output:** 2 **Explanation:** 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digit (odd number of digits). 6 contains 1 digit (odd number of digits). 7896 contains 4 digits (even number of digits). Therefore only 12 and 7896 contain an even number of digits. **Example 2:** **Input:** nums = \[555,901,482,1771\] **Output:** 1 **Explanation:** Only 1771 contains an even number of digits. **Constraints:** * `1 <= nums.length <= 500` * `1 <= nums[i] <= 105`
Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected.
Math,Binary Search
Medium
null
875
Hello everyone, today we discuss the problem number of the list, this is 25o setting making in this and we have suppose it is okay to make for laying, making from paragraph Vivek and in every subject something or the other has to be made and what is it that you are given a proverb. Time has been given, okay, and you have to tell me what should I show on this page, we have to put it in this video, okay, what am I missing in print, that the whole family is going to be made in this way, which they don't do within it, the division air. The condition given in it is that if it is accepted that its speed is the speed of Manjhi Khana, then it is okay and the owner has given this to you as per the first answer of 6 dry ginger. If this thing is at its speed, it means that it will arrive in 1 hour, till then what will he have given you. Madhuri, this eight thing is given to you by its mother, okay, if it eats it, how much time will it take? First of all, it has the condition, but as it eats the food, it is okay if the mother eats it first, before that, there is no one from that air like it is that 1 The alarm can go off in an hour, this person will start standing for a few minutes, suffer or make any movement, he will eat quickly, but at that time, he will not eat anything left, we will leave him like this, okay, then it is the hour that this person feels. In eating food, even in this piece of food, even in one hour, what will happen in it, in the first hour, I will eat tiffin today instead of getting it for free, now what is there in this, if you want it may take a year, then what is it like for you that this would have been given to you and it will reach. Will give you the minimum to tell you, it is clear that it is okay to become literate, you see that your speed matches yours, meaning in the meantime, anyone can take this restriction and ask from the turning point, when you have to make such a first choice, that in this rally Any value and all so you first of all family is the truth that your mind has then decide on this Facebook it in the middle of this okay so we wrote the function editing spread ball you and oil and egg this time is okay so what we all Want for entries and feel the sacred festival of administrative person that between the two try like this means from one to the tax department thinking of starting find it should keep us running till it is small okay so we collected Chinese daily point The first thing I asked was that what would be its speed, let's have a table in front of the office and here I tweeted on time that if its speed would be a mile then how much time would it take to eat, it is functional by going and clicking on it. What did you see, it was written like this with a pass and we keep the information about what is the media 19, then it will take time, the path, it gives all kinds of stress, proverb, Mario, then flower city, it is falling short, it is like this, it is okay, Ma Chandrika Haar meaning that which gives. There is a benefit, where are we going before that, so you try to make it smaller and take the skin smaller because it is like this, suspend use win, this is what you had, okay boss, I can handle more speed, so how many records do you have? Garbage of and so at least it's okay if mother Nancy I do n't give office yet a little more planets means you are going to have different pimples Babu what to do and make it smaller with the cream method of yours if when did this happen It gets bigger ok means the owner wanted me for Asaf Khan's food and came to know that it has been given because deposit is a food what does it mean I should increase the speed because there is a lot of express on this saree this modern of tennis From the chart above and this is a number interruption in between, okay, now it is the turn, whether these points get any number under any condition or not, so what will happen when I come to you and like this, how many quintals have to be done - 28 - Everyone has this problem of becoming cancer - 28 - Everyone has this problem of becoming cancer - 28 - Everyone has this problem of becoming cancer and in the end the blood has to be returned. Let's have a look at the party wear look of these remedies. How to turn on the White House? According to Tigmanshu, you also have the option of heating from Jio Tower and you can attend festivals etc. This is fit and if you want to make Akbar total, then you have been giving this hole in the last weeks, as if every province of the society or acid is there, the owner is our spoon, if it is ok, then how much request will it take, the whole village will take this appointment, if it was appointed on 19th 752, then it would have been done. So it will go, when we will take it, then what will we do by turning on the setting, then it arrests, divides and is located on many occasions. If you remind, then what is the explanation added in the last, how many houses have all lost this but Is this question clear to you? If you have any doubt, please do so in the comment box so that all the garbage can get the commission at the right time.
Koko Eating Bananas
longest-mountain-in-array
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_. **Example 1:** **Input:** piles = \[3,6,7,11\], h = 8 **Output:** 4 **Example 2:** **Input:** piles = \[30,11,23,4,20\], h = 5 **Output:** 30 **Example 3:** **Input:** piles = \[30,11,23,4,20\], h = 6 **Output:** 23 **Constraints:** * `1 <= piles.length <= 104` * `piles.length <= h <= 109` * `1 <= piles[i] <= 109`
null
Array,Two Pointers,Dynamic Programming,Enumeration
Medium
1766,2205
309
hey folks welcome back to another video today we'll be looking at question 309 best time to buy and sell stocks with cooldown so the way we'll be solving this problem is by using dynamic programming and the basis of this entire solution is that we'll be storing states uh of the maximum profit that you can earn at every single uh price that you encounter throughout the area by looking at what's the maximum profit that you can earn if you have bought at that particular value or sold at that particular value or use that value to just use that as a cooldown period and the way we'll be representing those states is with these variables so b naught is uh b naught will keep a track of what is the profit that you've earned so far uh with the assumption that you're buying at this particular time b1 is what is the maximum profit that you have earned with the assumption that you bought the stock just previously and these three states right here represents the still the selling maximum profits so s naught represents oh hey uh this i was sold at this particular moment so what is the maximum profit that i've had by selling right now s1 is keeping a track of oh uh these are the uh this is the maximum profit of profit that i can earn by selling previously and then um s2 represents what is the maximum profit that i can earn when i've sold many of when i've sold that particular stock two iterations previously the solution becomes uh more intuitive as we start coding so let's jump right in so uh first let's cover the base cases if uh prices uh if the area is null r if the length is less than or equal to one you would just rip down zero because you need at least two size two to buy and sell at least ones so let's initialize all of our variables so b naught would say hey we have actually bought at index zero so we would say price of zero which means that uh i'm buying at the first index itself and since i'm buying i would pay that price out of my pocket so it would be negative and b1 since we don't really have anything before that we would just initialize to b not and then let's initialize all of the selling prices so since we haven't really sold it will be zero s one will also be zero and s two will also be zero all right and in the for loop we will start our iterations with one because we have already assumed that hey listen we are buying at uh at the first iteration so um i is less than prices dot length and incremented so for b not currently you need to get the maximum profit so what you would do is you are saying hey we either hold the price that we have already seen previously or you would buy it after a cooldown period so there are two buys that you can possibly do you can either buy it previously uh and sell uh immediately but you got since we're keeping on track of just what's the maximum you're just buying it so we're not really doing any action we're just keeping it as is or you can buy it afresh with s2 minus prices of the current and the reason why that is because you're looking to buy at the current iteration itself but you can only buy that with the cooldown period when you have sold at s2 and s2 is keeping a track of what exactly with s2 is keeping a track of what is the maximum profit that you have earned not this particular iteration by the previous uh with the previous two iterations that means you have sold it you have one day of holding period a cooldown period and now you're buying it so this is what it represents so these are the two states that you can possibly do with buying you can either keep the previous by itself or you can buy it after a cooldown period and s naught is what exactly so let's look at that so you're keeping a max of um s naught by either keeping the previous sold that means you have sold it and you're currently keeping your key currently cooling down so you're keeping it as is or you are selling a fresh that means you've just bought the stock previously so that would be uh b1 plus prices of i so let me just go over that again so it's super clear so you're telling so s not again has two states you can either sell it immediately that means you bought at the previous iteration and you're selling it right now thereby this is the profit that you're getting or you sold it at the previous iteration and you're keeping and you're not doing any new action you're just holding that particular stock as sold because you want to use that as a cooldown period so that's the max so these two lines what they're doing is that they're telling hey this is the best thing that you can do from a buying perspective and this is the best thing that you can do from a selling perspective with the condition that you need to have a cooldown period so these things right here like this right here says that hey we're we are waiting for a cool-down period we are waiting for a cool-down period we are waiting for a cool-down period before we actually buy it and after we have done the calculations we renew the states so um b uh b1 becomes b naught s2 becomes s1 um and s1 becomes s naught and in the end the thing that you're returning is s naught and the reason why we're returning s naught is because the it after you have iterated through the entire array it has to end with a cell you cannot buy it and keep it as is so there's a reason why you're returning it with s not uh let's just run this code and see if everything is okay oh price is all not change the edge okay cool let's just run this again let's see if everything is okay again um why oh as well right this one so that should be good hopefully perfect it compiles the first test case works and then uh all the other test cases work as well all right so this question is a little tricky but once you wrap your head um around how the states work and how they interact with each other the distribution is pretty simple the time complexity for this entire solution is of n because you're iterating through the entire area just once um and the space complexity is of one since we're using just a fixed amount of variables and not um using more space than necessary so that's the solution you guys let me know if there are any questions that you want to solve in the comments below uh please don't forget to like share and subscribe and i'll see you guys in the next video see ya
Best Time to Buy and Sell Stock with Cooldown
best-time-to-buy-and-sell-stock-with-cooldown
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[1,2,3,0,2\] **Output:** 3 **Explanation:** transactions = \[buy, sell, cooldown, buy, sell\] **Example 2:** **Input:** prices = \[1\] **Output:** 0 **Constraints:** * `1 <= prices.length <= 5000` * `0 <= prices[i] <= 1000`
null
Array,Dynamic Programming
Medium
121,122
68
text justification in JavaScript this is a hard problem it's very tedious and messy with little edge cases and things to watch out for given an array of strings words and a word and a width Max width format the text such that each line is exactly maxed with characters and is fully left and right Justified you should pack your words in a greedy approach pack as many words as you can in each line add Extra Spaces when necessary so that each line has exactly Max width characters extra spaces between words should be distributed as evenly as possible if the number of spaces on the line does not divide evenly between words the empty slots on the left will be assigned more spaces than the slots on the right see what I mean by being annoying the last for the last line of text it should be left Justified and no extra space is inserted between words another Edge case the word is defined as a character sequence consisting of non-empty space sequence consisting of non-empty space sequence consisting of non-empty space jars each word's length is guaranteed to be greater than zero and not exceed Max width the input array words contains at least one word so if the max width is 16 we can put 4 and then we can put five six seven eight our next word would be example 9 10 11 12 13 14 15. and we'd have to have these spaces so this is four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sorry 12 13 14 15 16 yeah so we don't have enough spaces on this one four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen we would have we would need two extra spaces for that word so that way we can only get this is n on the first line and the next line we can start out with example that is seven letters uh the space or the comma is eight nine ten eleven plus 4 is 15 and that'll fit on there and then the last word justification and a period followed by a number of spaces here now we look here example has two spaces and then of has one and that one's how that's how that one's padded and all that's taken care of in a separate function called format line what the way I divided it up is to create lines where we can have each line will fit the number of words okay so now we've got each line format we've got each line with a correct number of words on it so that it will fit those number of words with the spaces between each word and then we're going to have to go through and format the line in a second approach and I found this divide and conquer strategy for formatting the lines would work better for me so we could see if the line can accommodate another word and if it does then we can add it onto there so here's our function if we have no words return an empty string well I don't think that's ever the case uh one is so we have to have at least one word so that's never going to be the case so we can just get rid of that right now lines is words dot shift takes an element from the front of the array and modifies the input array that it's called on so now words has one fewer line in the beginning so we're not going to start our loop on the first word this we're going to start on is Loop through I zero I is less than words dot length I plus W equals words I which is because we shifted one off the front of the array current line is lines zero curl line is zero and we're going to increment that later line Min length is this is the fastest way to do this oddly modify keeping track of the number of characters and each line was a lot slower than actually converting it to a string and getting the length property off it so what we do is we convert that line array into a string and get the length of that string now that line array formatted as a string is going to contain commas those commas will have the same length as a space character and we can see that to be the case if we go something like if we go string and when then we pass it an array High by we pass it a string array and we call that we're going to have a comma in between hi and by that's the way JavaScript has been standardized and can be expected to format an array it will format it with that comma there and this happened to be the fastest way to do this oddly it was much faster than counting and keeping track of a number you wouldn't think it would be but it was and we get we're in the Upper 90 percentiles like 96 to 99 performance on this so This beats all has a room that's a Boolean you always name your booleans with has or is usually sometimes you want to use can but has or is so as room is the max width that's what we passed in this case it's 16. uh line Min length minus lineman length which is calculated to the current Line's length being greater than the word length now word is the next word so right now we're on this we have this in our array our current word that we're testing is do we have room to put it in there so yes we do obviously we know that this is four Max width is 16 minus 4 is 12. uh and well so then is that's going to be greater than the words length that we're checking we're trying to put is in there right so it has to be greater than not equal to greater than because we need that extra space in there if we have room then we push that word onto the current line and we keep doing that so we push is on there so now we're going to crew we're going to increment I is going to be one uh this is one because remember we slice this off the front we shifted this off the front so this is zero this is one uh so now we're going to convert this to a string one two three four five six seven eight do we have room for two more characters what's 16 minus eight obviously we have room for this word in here okay so now we have two more characters in there so now we have uh ten and we increment I line is this is n now we're going to try to add example we've incremented i w here words I is example has seven characters in there so do we have room to add to the current line so we have four five six seven eight nine ten eleven 16 minus 11. is that right four five six seven eight nine ten eleven uh our 10 sorry is 10. minus 7 is uh 10 16 minus 10 16 is Max width minus lineman length which is 10. uh greater than uh w dot length no 16 minus 10 is 6. the word's length is seven so it has to be eight so we would have to have instead of six we would have to have eight characters remaining to get that word on this we can't have we don't have room so now we have to see if the next line if it'll fit on the next line when we do that we're going to format the current line and then we're going to check the next line and then when we're done we're going to format the last line we're going to basically join it together on the empty string and then Pat it Max width with the empty string and these string dot repeat and Pad end really came in handy the um the current line is then formatted we pass in line and the line Min length and the lineman length is just the lines length plus the word gaps the Extra Spaces is the max width minus the line Min length plus the word gaps so how many spaces do we have to divvy up between those word gaps uh the line Max width is 16 the line Min length is we say 10 and the word gaps is going to be let's see was it 10 one two three four five six seven eight nine ten so we have six uh plus the word gaps so 16 minus 10 is 6 plus the word gaps is 2. so because remember we have line mid length already includes those commas as if they were spaces so now we can get the pad size the extra space is divided by the word gaps but we don't want a decimal point in there so we're going to have to floor that and then Extra Spaces are going to be the extra ones so Extra Spaces are the word gaps plus the pad size floored Extra Spaces uh at minus Extra Spaces are the number of Extra Spaces minus the word gaps times the pad size floored word gaps if we have in this case we have two word gaps and the pad size floored was what did we say it was four so we don't have any extra spaces on the first line is evenly divided with four on each one and if the line length is one then we do this it's not one so in this case we Loop through I is 0 I is less than Extra Spaces we don't have any so that's zero and we just skip right over that and then we join those on um because we're going to go greedy if we have a case where we have Extra Spaces we're going to go greedy and left prefer those extra spaces and then and we're going to add each one to the each word and then we're done with that because we skipped over that on this iteration we're going to join that line on the empty string repeated by the pad size floored okay so we joined that by the repeated by the pad size four so we repeat the empty string and how many times did we say the pad size floored was did we say it was uh it was going to be four right because Extra Spaces a pad size floored is the Extra Spaces divided by the word gaps two word gaps eight Extra Spaces floored is the same thing it's still four and then we're going to repeat that we're gonna have four spaces in between each one and we can see that if we log that out to the console and we're going to continue this algorithm in the same manner until we get to the last line and on the last line we're going to have to reformat it the curl line is the last lines we'd actually reformat we just increment it here and then we don't we terminate the loop current line is format last line curl line and we can see the input to that way when we go down here by just console.logging see down here by just console.logging see down here by just console.logging see what that gets and we'll show you the line before we format it and then we'll just add those Extra Spaces so if that's the last line that we have now we have to add those Extra Spaces on there and the way we do that is with the string.prototype.pad end Max width and string.prototype.pad end Max width and string.prototype.pad end Max width and then the empty string then the and then the empty string and the pad end takes care of that formatting for us so there's how to solve it and here's the performance that I was getting out of this which is like I said in the top percentile range as for memory not so bad either there you go there's another lead code hard problem a very annoying one solved creatively with Advanced knowledge of JavaScript I didn't look at any of the other Solutions I just Dove right in and solved it by using my knowledge of JavaScript and I hope this helps and take some of these lessons from this JavaScript example and apply them to your own code particularly those string prototype methods and the technique of converting an array to a string that can come in handy
Text Justification
text-justification
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. **Note:** * A word is defined as a character sequence consisting of non-space characters only. * Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`. * The input array `words` contains at least one word. **Example 1:** **Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16 **Output:** \[ "This is an ", "example of text ", "justification. " \] **Example 2:** **Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16 **Output:** \[ "What must be ", "acknowledgment ", "shall be " \] **Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified because it contains only one word. **Example 3:** **Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20 **Output:** \[ "Science is what we ", "understand well ", "enough to explain to ", "a computer. Art is ", "everything else we ", "do " \] **Constraints:** * `1 <= words.length <= 300` * `1 <= words[i].length <= 20` * `words[i]` consists of only English letters and symbols. * `1 <= maxWidth <= 100` * `words[i].length <= maxWidth`
null
Array,String,Simulation
Hard
1714,2260
61
hi friends welcome back today we are going to solve lead code problem 61 rotate list so given the head of a linked list rotate the list to the right by k places so let's just consider this first example which i have it here so this is the list that we have been given one two three four five and we have to rotate it by distance k ah so rotation means that like the first rotation is basically we are taking the last node 5 and we are bringing it to the front so as you can see the five came to the front and then one two three four then the second rotation means again we go and take the last element and bring it to the front so four we took it and again we bring it to the front and then we attached it to the five so four five one two three so this is what the rotation means so we are uh given a number k and we have to rotate the list by that uh k uh times repetition so um uh how we can solve this problem is by using uh two pointers like we can like as you can see the head is pointing here to this node 1 so what we can do is we can take two pointers one is a first pointer so let me just it is pointing here so this is a first pointer and we will have another pointer which is called as second pointer it is also pointing to the same node in the beginning so this is the second pointer and what we will do is we will move the second pointer by distance k which is 2 here in this case uh so first we will start and we will move the second pointer by 2 so it will go to 2 and then it will go to 3 so we will move we moved it by distance two so it the second pointer reached here and at that time the first pointer is still pointing to one so after uh so simultaneously i'll also discuss the code so uh here first thing we will uh check is if the head is null or head dot next is null means only one element is there in the list or the it's empty list then we are just going to return head because we cannot do much uh like a rotation here right because it's a empty list or only one element so we'll just return the head otherwise we have taken three list nodes current first and second all are pointing to head here and then as we were discussing i am going to like move the second pointer here by the distance k so i will just while i is less than k i am going to move the second pointer to second dot next and there are some uh there are certain boundary conditions we have to handle here where the you know sometimes the k is bigger than the length of the list so it will go out of bound right if we travel here if the k is more than 5 then it will go out of bound so what we have to do in that case is we have to after it reach the last uh node 5 then we have to again take it back to the first node you know so it will not go out of bounds if the this happens if the k is more than length of the linked list so that's what we have to handle here so that's what we are handling so we are just in case if it is a more than length of the list then we are again uh once it reaches the end we will set it back to the head again uh so that's what we are doing so the next step is that now the second pointer is pointing to node three and first pointer is still pointing to node one now we will start moving both pointers simultaneously so second pointer will go at four and first pointer will go at two at that time the second pointer will now go at five and first pointer will go at three now at that time right so we will keep checking and we know that now the second pointer has already reached the end of the list right so at that time we are actually uh what we are going to do is uh we are going to put the head of the list to this node 4 so we will point the head here of the list uh which is like how we will do it we will just say head is equal to first dot next so here the head will point right first dot next will be the new head now which will point to the node 4 and after that we will go to 5 and 5 next will be the previous head element here so here we are doing the same thing we are iterating first and second uh pointer simultaneously until second dot next is not equal to null means second is second dot next means until it reaches the last element so we will iterate it and we will say that second next is equal to head so this is the second next right so second is here at this time so second next we are pointing to head which is here right 1 and head is equal to first dot next so as i said the first is here right at 0.3 so i said the first is here right at 0.3 so i said the first is here right at 0.3 so head will be first dot next which is 4 so now as you can see the new list will start with node 4 so it will start with 4 and then we'll go 5 and after 5 we are going to go like uh as you know like uh second.next is equal you know like uh second.next is equal you know like uh second.next is equal to head we are doing so second dot next means five dot next is equal to head means one because that's where the head was pointing uh previously right before in the starting so that's how it will go and then 1 goes to 2 and 2 goes to 3 so once we reach this node 3 where first is pointing we have to make sure that we will terminate the uh link here right so it should end so that's what we are doing here so we will just say first dot next is equal to null so the list is ending here so that's how we will get four five one two three and this is what the result is right four five one two three uh so i took a couple of i tried couple of test cases so let's just try this one here and the second is already here so here the k is equal to 2 so let's try to run it and make sure that this works correctly yeah so we are getting the correct result right four five one two three so we can submit this solution oh little let's yeah actually let me retry this solution yeah so the solution works and it got accepted uh so i think there was some problem with lead code so the solution got accepted so if you like the video please consider subscribing to my channel and hit the like button so this is a simple way of rotating list using two pointers so i hope this is clear explanation thanks for watching the video
Rotate List
rotate-list
Given the `head` of a linked list, rotate the list to the right by `k` places. **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[4,5,1,2,3\] **Example 2:** **Input:** head = \[0,1,2\], k = 4 **Output:** \[2,0,1\] **Constraints:** * The number of nodes in the list is in the range `[0, 500]`. * `-100 <= Node.val <= 100` * `0 <= k <= 2 * 109`
null
Linked List,Two Pointers
Medium
189,725
1,041
Jhaal hello everyone welcome and welcome back to my channel today were going to solve the problem with different for different video please like and subscribe my channel subah kyunki not fur when and nutrition new video software for any positive let's get started show the problem is this robot Bonding current very easy and interesting problem used to be online infinite plane robot initially forced to stand SDO and a note to what is the standard which region and its placing north robot can receive individual instructions yes me to go straight one unit and means broken Online Degree Tubelight Will Just In This Direction Will Not Move Left Justin Distraction 0 Study Army 2019 Or Game But On The Right Side 9th Robot Forms The Instructions Given In Order And Repeated And Forever Just Justice System And Appointment In The 9th Question Dad Instructions With Robot Will Get It Will Repeated Forever E The President Rule 19 Only Be Reduced Circle in the Plane Decoration Robot Never Leaves Decade a Minute to Find Out Weather Robot Is in the Movie in More Minutes in Can Find Path This Time Can Find Solutions Can Find That Circle Did Not Go Outside Park Complex Robot Is After Going Clear And Glowing Hair And Crows And Someone Clear Like This Is Not Leave This Work At Last 100 When Will Discuss The Test Cases For The Question Open To The Question A That Of The Other Test Subscribe to Space 100 With Instruction Expert 128 Suzy Means Tech Wires Goa Unit Head Element 1090 Degree Left End Army 2019 Rate 234 Initially The Robot Forced This Eight Zero Phone Anup Singh Not Addressing Note To 102 Effective GG Means Goa Is One Unit head to love the robot boy go to wala unit head 2002 Jio ka march 09 mein we ko forward arange is the means ko unit head for the robot boy nov-2012 head for the robot boy nov-2012 head for the robot boy nov-2012 that and robot is vve singh notes with going in opposite direction write an essay Blackmail Fuel Tunni Degree Left Torch Light The Sea The Robot Is A Space In North Effect To Left With Acid Citric Acid Turn Left Know It Is Pe Singh Ki A West North Facing West Sea Spaced Left Over All Should Not Return 9319 Sunao Facing West A Love Again Left Now Life Again With Robots Is Hair Spacing West This is Right and Left His Right for the Robot and Slept for the Robot Robert Venter Ne Degree Left for the Robot Will Go to Will This Again and Will Feel the Reaction of World Facing South Na Suno But Office Leaders Of This Scheme Not Moved Her Destiny Directions From This Year And Facing South Rate That Boat Which English Means Course One Step Ahead Shobhante Bread Videsh Sudhro But Will Come Less Notice Nuclear Facing South Superhit One Step Ahead Again Robot This Mode 108 Sunao To Butter Kendriya Kamal Holiday Robot Movie Sarkar Valve Website Circle Of Radius Two Roads Parted From 28th That Sudhir And To Radiation Hai To Interest Ke Sansad Bittu Because Robot Boy Movie Inside Sarkar This Is On Kar Innovative Way Inside 202 To Ego Heavenly Welcome Back to the day this is cheating and this day back seat thing and return from back pain that this acid land record twitch them for the original position take care a love letter this tasks and sorrow birds initial districts are forced that and it's due To no degree left the return of three layer pendant three does it is currently facing north west have no clue means the robot subscribe 100 subscribe button 10000 but they should not give way to give back to same position and will return to a right now again dance Drama Hai I Hope You Understand Dushman Main Pehle Thick Gel Ki Suji Ki Gel In Notice Of Glaucoma Zero And Facing North I Will Not Write Note Should Not Proper Taste Bhu Ko Jeans Instructions That To Goa Unit Head At Will Goa Unit Head Zero Commando Force Ko Do A Still Facing North Na Them Located In District From Land That Improve But Will Nau Been Facing That Vaishnav Action A Right Now You Will Say It's Not Coming Back To Reconsider It's Wide No A C P C O C Close Loop Question And Was Written Daughter in Law Order It Will Repeat Game For War Between Repeat Game Forever Dot Means Destruction Jail Three Meeting Hai Na Lagae That Bigg Boss Minute NGO Wickets And Right Now Abhi Is Accident Loose -Loose Benefit -Loose Benefit -Loose Benefit Robot Boy Singh Left Processing National Do It Will Go One Step Ahead G It Welcome Dear 80 ML Means Twilight Valid for 200 Left 16 Stitching Waist and Laptop Waist is the 0 121 Just Interaction Leg Distraction South Mein Lagae I One Tap and Left Sufi Left of This Will Be Sworn Affidavit Field This Is The Percentage Singh South Sudan Left After Portion With One Step Ahead In This Way You Will See The Tune Mouth Decide This Protection Meet Gift Times And Drop Will Again Came Back To Reach In This Coming Back To Ease And Can Handle This Movie Ne Samay But return to today not even seen water empty and restaurant systems lineage's 12th cellular and eight knowledge tree another one month will also worked in just now movement will be something like this in right direction in others like this 200 on college srinagar test That Jiyalal Suji Alarm Late When Indulgent Person 10 Close Loop Slow Increase Robert Is 800 And Space In North East Facing North Tag New Zealand To WhatsApp 2014 That Tenets Of Stone Left Solid Will Be Now Facing West Direction Which Section That In The Last To Go Right Left Facing West Direction Hotspot On Again Or Right 98100 Feeling Distraction Of Which Is Not Forgive Forget And Destruction Will Be The Chief Guest At Least 1000 Will Withdraw Its Moving Away From North To Where The Robot Boy On This Will Return For A Day Few Might Have Noticed We Pattern For These Test Cases Test Is With Robot Comes How To Reason Come To Reject That Handsome Versus Legal Movie In A Circle And Is The Direction Of That Is Always North Correction Involves Not Like This Is The Robot Boy Movie The Final Decision Of The Robot Boy Note Office Let Me Love You For Telling Direction North Delhi To Which Biwi Who Is That Sudha To Members In Condition Fish Understood From This Question In Order To Get Answer Through I Do n't Weakness Jain And The question is not don't don service to in the key stuffing and any to-do list for the problem and attached and now at this table from going to win but came but his scream was so MP3 a plate here romance Have so these dysfunctions 120 Bird and interesting of instruction correction do interaction is note because in the question is the giver the robot it zinc want to be taken every force observe and its value note who is the original position of the robot com x n y Coordinate in 100 Days Give the Problem Sudhir Vo * The Protection Sudhir Vo * The Protection Sudhir Vo * The Protection That Pension Is The Means See Is Platform Shoulder And Long Weight For Conducting Or Taken Current Direction Is Available Which Were Taken In English Lead Value Notes 98100 And Wise Geet Flash Lights Were Discussed Tips 9 We are going to itch instructions for country are ji that Nav ji Vyas will do ji Sushil then moving from 010 addictions and add new item one step ahead you will reach your comment is means what will start from its quite well scene was quite will change by One hand juicer is what they are doing give instructions g instructions to remove corruption is not only will change the flash light how to what will you see my coordinator sorry will change for a quite amazed to comment tomorrow morning see the dawn to is the direction Off South Correction Virtual Menu All To Go Down To Minus One Boy Decrease Defeatist Coordinator Will Increase 102 To South Minor That Ifiko Is It Well God To Destination Explain Increase Benefits Based Activities One To - 1404 Activities One To - 1404 Activities One To - 1404 Main Tujhe Singh Jasbir Have Written In This All Are It Is not why will just increase road in this right to contest world is so once a good eve was recorded in the guru ji we can go to the loop and construct and action steel north means and why will increase by one of their survival in Playing And Welcome To 209 Bhi Aap To Come Hair Left Now Let's See What Happens To Innovation Instruction Of I Is Left Hand Will Go In This A Big Boys Main To Hridaya Beach Just Need To Change And Correction Be Caused Severe Way India Left Person Chest Kunwar Singh Direction Robot will inspect Inspection Milungi Change Left Right Left also 293 Left or currently facing North and half inch is optional 200 Means the Correction Notes Left is a distraction and not the current direction Vinod Chintu West is west is not coming is loot a view to inside Robot Left Just Itna Dhokar Interaction Na Udhar Action Vikram Bhatt Improvement All The Condition Score Photos How To Right Now After 10 Leftists And Conduct Vikram Best Ko Tight Login Bhi Court Cricket Khel And Sunao Ya Get Tel Will Again Govind Sales E Will See Till More Interactions Vaishnav Current Activist And Need To Left Minute Only From West To Fear And The Best Flute With Right And Will Be Left With No Option A Specific Pocketing This Is The Person Spacing West Is Life Changing Celebrate Tried To Enter Interactions Adapter Left Hain To Dhan Nude Action Vikram South Direction Medium Saath Daru 10 Comes Out Ki Shaurya 209 This Is That Nau Visit G Can They Get G End Corruption Chauth Decree - Decree - Decree - 151 D0 Commando Ko Kumawat Joe Will Decrease Ball on English Wicket Inspection With can decrease pressed width him after all this instructions are kumar and send message to this video my favorite origin to be discussed it difficult to condition in robot is to region and directions note so it's inner circle and will return to 28 last edited version Means will return to and here action was not incidental to this interest kitna GLR world test after similar and not in this real engineer short term of repeating this four times but welcome back to reset 202 will be done through in both cases and otherwise returns That the commission did the studio code and approach Advocate Vinod Comments Time complexity is open eyes were just looked into the instruction ring and space is one because it will not be in its true detective agency old soft also contact and fruit that UP Roadways Employees Video Please Share subscribe To My Channel Highly Motivated Chuye Benefit Thank You
Robot Bounded In Circle
available-captures-for-rook
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that: * The **north direction** is the positive direction of the y-axis. * The **south direction** is the negative direction of the y-axis. * The **east direction** is the positive direction of the x-axis. * The **west direction** is the negative direction of the x-axis. The robot can receive one of three instructions: * `"G "`: go straight 1 unit. * `"L "`: turn 90 degrees to the left (i.e., anti-clockwise direction). * `"R "`: turn 90 degrees to the right (i.e., clockwise direction). The robot performs the `instructions` given in order, and repeats them forever. Return `true` if and only if there exists a circle in the plane such that the robot never leaves the circle. **Example 1:** **Input:** instructions = "GGLLGG " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South. "G ": move one step. Position: (0, 1). Direction: South. "G ": move one step. Position: (0, 0). Direction: South. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0). Based on that, we return true. **Example 2:** **Input:** instructions = "GG " **Output:** false **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. Repeating the instructions, keeps advancing in the north direction and does not go into cycles. Based on that, we return false. **Example 3:** **Input:** instructions = "GL " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West. "G ": move one step. Position: (-1, 1). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South. "G ": move one step. Position: (-1, 0). Direction: South. "L ": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East. "G ": move one step. Position: (0, 0). Direction: East. "L ": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0). Based on that, we return true. **Constraints:** * `1 <= instructions.length <= 100` * `instructions[i]` is `'G'`, `'L'` or, `'R'`.
null
Array,Matrix,Simulation
Easy
null
1,091
[Laughter] hey everybody this is larry this is day 16 of the mainly go daily challenge the like button to subscribe and join me in discord let me know what you think about today's farm and especially that intro uh as you can tell or maybe not i don't know i'm in atlanta so i'm just hanging out and trying to figure out what's good here uh yeah let me know if you have any hiking feedback or just recommendations or whatever excuse me today's problem is shortest path in binary matrix given n by n binary matrix given uh return the length of the shortest query path in the matrix the query path is such that you go from top left to bottom right such that all visit cells are zero or adjacent are a connected okay yeah i think this is just a regular shortest path i don't think there's anything weird about it um the distance is one for each adjacent one and it's an eight directional so this is going to be already intuitive by first search problem um there are a lot of different shortest platforms so definitely be familiar with it but first search is probably the most uh or one of the ones that you learned earlier on so definitely get um for me a bit from a little bit i still have some uh allergy issues so not so great there but yeah let's just get started so we want to go from uh let's say distances you go to uh let's also get length is equal to great c is equal to length of grid sub zero of course for some context make sure you uh double check that it cannot be equal to zero so this is an n by n grid so you don't even need that but i like to generalize it anyway why not it doesn't really matter um times c right and then in just some big numbers fine yeah and then we have an enqueue function and this is just going to be on q you have x y and then the d so distance of x y is equal to d and q type append x y t maybe yeah okay and then now we want to enqueue zero at distance zero and then while length of q is greater than zero we have x y d is equal to q dot pop left this is way standard bfs uh that i write mostly the same thing every time i win probably at this point hundreds or thousands of bfs co codes so it's way even in python because i think i've done a lot of languages as well but so like you know i'm going a little bit too fast that's the reason why and this is something that i would just say um you know be sure to practice right there's really no um yeah there's really nothing about it other than practice that's what i would say uh yeah okay so yeah so then now oh yeah i always like to write directions out this time it's going to be um the a direction so let's just do it i know that this is a little bit tedious maybe and i don't know sometimes i worry and how i write it um but it comes into play easier when you do like chess related things when you have knights and other funky stuff so bear with me for that part i suppose okay so then now for d x d y in directions next x and x y is equal to x plus d x y plus t y and then yeah if nx is and the distance of nx and y is equal to infinity then we can do it oh i guess we don't have to do it and that's pretty much it really uh and then at the end we go i mean we can you can do it in a couple of ways you can also early termination just in case you have some wrap-around just in case you have some wrap-around just in case you have some wrap-around thing that'll save you some time but for today i'm going to be a little bit lazy so yeah so i'm just going to check if this is equal to infinity then we turn negative 1 otherwise we turn this i really hope this is right on the first try i've been a little bit silly lately um it's by showing something that like i should very much get the basic of this so um so i don't get it right away i'm gonna be a little bit sad i think this is just off by one because i don't i count the first cell with zero um you can easily change that by maybe not maybe i'm wrong in other things too but i was gonna make this one to count the first cell was one cell unless i missed something huh well this is a sag but one two three why do i do it this way did i have a typo in any of this sometimes that's possible but it's okay hmm huh i am really confused i don't know yeah sometimes you just have bad weeks i was i keep saying bad days but i feel like i have a couple of bad days today already so oh i am dumb dude all right i feel like i've made this mistake a few times actually and it's kind of sad you have to make sure that this is they're all zeros and also in this case uh we have to make sure that if grid of zero is equal to zero i don't know if that's promised you nope so i think yeah okay uh i think i've been doing making this mistake lately where i keep forgetting the grid you know i check everything else maybe i need maybe i'm a little bit too much on autopilot uh i need to really think about the problems again it's been giving me issues okay this looks good let's give it a minute cool i'm much faster this time for some reason 776 yay what did i do last time that was slower i mean this is same idea really oh i did the fold last time is that much slower i don't know that's really awkward actually anyway this is going to be linear time because for each cell we only get looked at eight different times from the eight directions so this is going to be o of v plus e where e is a times v so this is going to be o of v um yeah and that's pretty much all i have and v is of course r times c or n squared so just to be clear but that's linear in the size of this of the input um and in terms of space also linear in the size of the input because we keep track of distance and the q uh yeah that's what i have with this one let me know what you think stay good stay healthy to good mental health i'll see you later and take care bye
Shortest Path in Binary Matrix
maximum-average-subtree
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
Tree,Depth-First Search,Binary Tree
Medium
2126
1,806
hey everybody this is larry this is me going with q2 of the weekly contest 234 minimum number of operations to reinitiate uh a permutation um hit the like button hit the subscribe button join me on discord so you can ask me questions about this other problems whatever you like um but yeah this is basically a simulation problem um and i actually did it in a funky way to be honest um because i probably should have just did a wow true um but i actually knew that this part i mean so first of all this is simulation and what is simulation is just basically just do this operation one at a time uh i took a long time on this one i actually end up taking seven minutes what the what is going on here but uh that is very fast but that's because i don't know i miss about to promise these are choices i need more sleep sometimes i think i was very um and it was a little bit off this contest because usually i mean this is a speed contest and usually i do sweet contest pretty okay um but i end up rushing it but yeah so basically this is just simulating it one at a time and that if this is you go to the initial answer which is the initial permutation we return t plus one um and i think the only thing that you might have questions about is that um is that this may take a long time right um and i think you know i could buy that uh but you know not knowing the worrying about like oh this can take forever how can you prove a thousand right well the thing is that um you know the number of permutation is and this is a little bit hand wavy but it's roughly speaking equal to um you know the components of the permutation cycles uh and there's some math on that um in this case you know that every you know that for each um for each number that's in the initial thing you know that um how do i say this so you know that i mean this is obviously like even without looking the function because that this is deterministic that this mapping function is deterministic knowing that this map function is deterministic you know that for every you know say index before it's equal to some index afterwards right um and because of this because that um uh and in this case you know and the usual the number of um what i what we call like how many times before loops is usually you go to the product of the size of the permutation cycles um and if that doesn't mean anything to you um it's a lot of math i'm not going to go over too much and that's obviously also a rough uh answer it's not exactly the product it's actually the least common motor bone uh but um and you know i'm hand waving a little bit but in this case because you know we have these simple uh operations where this is just dirty by two and this is like this is almost like um the inverse of the perfect shuffle right um so basically like this is yeah literally this is the opposite of the perfect shuffle and if you uh wear the perfect shuffle then you know that um you know that it's one big permutation cycle um possibly maybe roughly speaking um is that even true hmm i don't think that's necessarily true actually uh because otherwise you just have the same answer but uh but basically you have you know this perfect shuffle and you do know that it's gonna uh repeat at some point before n because um because the components because the um because the components are all going to be like you know even numbers are matched up because n is even so yeah um yeah that maybe is the i don't know i don't think that's a great explanation but in any case that's how i that was my i think that was the intuition behind the reverse perfect shuffle um because this is basically the reverse perfect shuffle and you know maybe you know you could look up perfect shuffle but um but because that is one of the things that you know perfect shuffle you do know that it um yeah so this is the perfect shuffle group theory that i was talking about um i just googled this and actually turns out that you know there was a simpler answer maybe but um but yeah but as a result um you can kind of see that you know um this will be in the idea and that is going to be bound by end in the worst case and therefore i just did it end time so i should have just did a while true loop so that i didn't have to prove it and every time sound i wouldn't know another way of doing it anyway and this is q2 so there's some matter about that as well that's what i may recommend but if you are interested in learning more about it um because the inverse function is it's going to have the same properties in this case anyway as the um as the regular shuffle so i would recommend reading up on the perfect shuffle which is apparently also called the fairways shuffle i didn't know that um but yeah uh let me know what you think uh hit the like button hit the subscribe button drop me a discord let me know what you think and yeah um oh no oh you and you can also watch my how i solve this live uh next during the contest um but you know but this is o n and this is going to be o of n ish so it's gonna be n square in the worst case um yeah uh and in terms of spaces it's linear because we just have a lot of linear stuff depending how you want to count we allocating memory but that's an easy optimization um cool that's where i have this from let me know what you think and you can watch me live next um huh i'm so confused this one this i don't want what oh man i am dumb what that nap was terrible okay man really bad right now yeah uh let me know what you think about this farm and explanations this isn't in my final ranking there's way more penalties because i just i don't know i ate too many wrong answer attempts but yeah let me know what you think uh hit the like button subscribe and join me on discord i hope y'all have a good day have a good night solve more problems if you like or you know too many acs and yeah it's a good mental health i'll see you later bye
Minimum Number of Operations to Reinitialize a Permutation
count-of-matches-in-tournament
You are given an **even** integer `n`​​​​​​. You initially have a permutation `perm` of size `n`​​ where `perm[i] == i`​ **(0-indexed)**​​​​. In one operation, you will create a new array `arr`, and for each `i`: * If `i % 2 == 0`, then `arr[i] = perm[i / 2]`. * If `i % 2 == 1`, then `arr[i] = perm[n / 2 + (i - 1) / 2]`. You will then assign `arr`​​​​ to `perm`. Return _the minimum **non-zero** number of operations you need to perform on_ `perm` _to return the permutation to its initial value._ **Example 1:** **Input:** n = 2 **Output:** 1 **Explanation:** perm = \[0,1\] initially. After the 1st operation, perm = \[0,1\] So it takes only 1 operation. **Example 2:** **Input:** n = 4 **Output:** 2 **Explanation:** perm = \[0,1,2,3\] initially. After the 1st operation, perm = \[0,2,1,3\] After the 2nd operation, perm = \[0,1,2,3\] So it takes only 2 operations. **Example 3:** **Input:** n = 6 **Output:** 4 **Constraints:** * `2 <= n <= 1000` * `n`​​​​​​ is even.
Simulate the tournament as given in the statement. Be careful when handling odd integers.
Math,Simulation
Easy
null
231
today we will solve a very simple problem of checking whether a number is a power of 2 or not so first thing you must know about the numbers which are power of 2 like 2 4 6 and not 6 2 4 8 16 32 and so on and even one is that they have just one bit set in them for example here are four examples of numbers which are power of two so this if this bit is uh set then this means it's 2 raised to the power 0 that is 1 if this is set then it's 2 raised to the power 1 that is 2 4 8 16 32 64 128 so this number is 128 similarly this one will be 32 this one will be 8 and this is 1 all of them are power of 2 but if we have more than 1 bit set then you cannot get that number using power of 2 let's say we have this is a power of 2 this is 1 2 4 this number denotes 4 but if i set one more bit let's say 1 0 then it becomes 6 and 6 is not a power of 2 so how we will find it one simple trick is that you can keep you can count the number of bits in the given number if this count is 1 and the number is greater than zero then you return true otherwise you return false so there are a few ways of doing it one is that you have a ready-made function in c you have a ready-made function in c you have a ready-made function in c plus called bit set and here you specify the number of bits you want to represent the number let's say 32 and if you pass here let's say uh 5 then it will return 32 bits a few zeros and then followed by one zero one and if you want to print it you can do two string to print it and if you want to count it you can call dot count method so you do bit set given number and dot count is equal to 1 and number is greater than 0 then we can be assured that this number is a power of 2. now let's see some other method where you don't use this built in function so what is the peculiar thing about this power of 2 let's say we have this 1 0 there are more zero bits i am not bothered about that so this is two four eight this number is eight if we subtract one from it we get seven and what is the representation of seven all once and everything else zero so if uh kth width is set let's say this bit is set at kth position in power of two only one bit will be set so let's say it's at kth position and everything to the left and right are 0 so if this number is n and if we do n minus 1 without even doing any calculation we can write it as all zeros till keep this point and everything else one and here you can see one example the same will hold true for 16 as well this is 16 and this side zeros if you subtract 1 you get 15 so its representation will be 1 so till here it will be 0 whatever bit was set and everything to the right of it will be one so if you take the end of these two what will be the result it will be zero there is no bit common and also uh you have to add that check n greater than zero so our formula becomes that if n is greater than zero and n and bitwise and here we are doing is zero then it's a power of two otherwise it's not you may be thinking that what if we do instead of minus why don't we do right shift and do the end that would be faster but you see that here it will work right shift but let's say you have number like this 1 0 and here it's 0 so this is 10 if you right shift it to 1 it will become 0 1 that is 5 if you take the end of these again you will get 0 but this is not a power of 2 so in this case doing that will hold but not always maybe some non power of 2 also satisfies this condition so that's why we are doing negative minus 1 so i hope it's clear now let's write the code for this in c plus java and python so first let's say use that bit set that may not be you may not use here but that is a very useful thing to know so i will represent it in 32 bits and let's say you want to see the representation then you can print it also and there are many more methods to this bit set one of the one of them is tostring when you want to print them or see the content in the string form other one is count which you which returns how many bits are actually set so let's run it so you see we have printed this and it shows the representation of this number one so let's try a few values let's print 10 5 and 16 so 10 and 5 are not power of 2 16es and we know the bit representation of 10 and 5 and you will see how easy it is to use bit set to know the actual bit representation so this is 10 and this is 5 now let's use the other formula that we had seen so this was just for your info that bit set can be very useful here it's not required it's a very easy problem but in some cases this may be very useful and you must know it so let's write our one liner code which is return n greater than 0 and n minus 1 n and n minus 1 this should be equal to 0 and let's add a few negative values like minus 5 minus 4. and it gives correct result for oh so it gives wrong result here this one third last which is 16. now it's correct so let's submit and this solution is accepted now we will not require any change in any other language i think it should work and it works so let's submit in java this is accepted finally we will submit it in python and only thing is that this will be end and this bit by hand remains same also remove it and this solution is also accepted
Power of Two
power-of-two
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_. An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`. **Example 1:** **Input:** n = 1 **Output:** true **Explanation:** 20 = 1 **Example 2:** **Input:** n = 16 **Output:** true **Explanation:** 24 = 16 **Example 3:** **Input:** n = 3 **Output:** false **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
191,326,342
1,854
do that welcome back friends today we are going to solve lift problem 850 char maximum population hair soft reminder already aware that will come open create solution videos in java j2ee interview helpful videos and would have created a big play list all ur videos 28 over 65 problem Solve and Explain Along with Example in Java Please Subscribe to this Channel TRP Print for Java j2ee Interview This Channel Reduce Please subscribe this Channel Solid But Rest More People So Let's Look at the Problem 80 Per Giver Today Interior Elections Where is Clock Off Side Is Birth and Death and Birth and Death clearly indicates the birth and death years of side per saint The population of Shami Vriksha is the number of people who lived during next year The right person is continuous Are its population of 1 Pimp Rudra Inch Chup Birth and Death - Want Super Career Office Late Se and Death - Want Super Career Office Late Se and Death - Want Super Career Office Late Se 99 or t-20 The Person Will Be Coming To Live From t-20 The Person Will Be Coming To Live From t-20 The Person Will Be Coming To Live From 1992 Noticing - 120 - That NSS Noticing - 120 - That NSS Noticing - 120 - That NSS 9900 Question Is Not Counted In The Air Diabetes Patient Andar Last Year With The Maximum Population This Difficult To Return He brother population how maximum birthday suit with and last year in the giver nearest in the given range officer robbers this problem and share and will just tried to create one example problem user can explore new song basically a pain rangers for example dispersive witch light from Note 3 Say And Died In You That And Second Neighbor's Is Alive On 1995 Since 1998 Night So According To What Your Say Intact Two Cups They Have To Count Person Only For The Years Only Sewa's Note In Your Site In These Cases Will Calculate Loot given here for example will go from nov 30 min subscription * free withdrawal on thursday start like this page will start from note 3 so this retail 1993 show will start getting from 93225 exactly 293 and 294 also will go and 1995 will Go On Torch Light Deepak 1996 Will Not Count Because Of Diet Inverter Show Where Only Computing This Cream And Will Keep Track Of How Many People For Winters Right Now Only One Person Rape Victims Were Soon After 10 The Greatest Person Will Start From 9097 And Will Check to howrah train map entry in the giver incremental video entry for example no veer already getting country will update the 1212 and another new entry for a new person will be 98100 tags one person right after upanishad is fold hai re din wahan vyaar lekar updating This frequency and basically how many people who live in how many difficult and frequency they are updating tight software updating of frequency from 12423 what ever we will keep track of the maximum of population that they have seen some maximum 21 equal to two in this a Ride In This City Menu Yaar Like Look Into This Map They Will Update To This Updater Maximum To So After 10 Way Stream Of This Positive Will Again Go And Tricks Map And Will Draw A To Z Yudh Maximum 900 First Will Check This 930 Not Find The Maximum Day You'll Go Check 1994 You Won't Find That Me To-Do Man 1950 To Find The Maximum Movie Chintu 340 Is That's The And Last Year When The Population Begum Maximum Basically 800 Going To Return That's Well Population Air Chief Debit the same in the map software 1995 that details maximum which studied is 100 you get evil return our answer 1995 in this case right a to reverse limit implementation ko so absolutely Ronit Roy example of working 500 to 1000 result-2012 * return exactly maximum result-2012 * return exactly maximum result-2012 * return exactly maximum population is Created Fear and Creative World Maximum Should Not Give To End But For The Time Blog Directory And Start Trusting Again Here Internal Are Start From Birth Year And Will Give The Day In The Year Will Automatically Avoid Basically Day - 8th Edition Vidya Winter Check-In Quizzes And the three for the tier one this whole find entry viewers get the interior and will increment entry day to you will check gift data entry day to you have you in the map is it like maximum not compete with maximum and will just update maximum that the Interactive Where Getting From Mac And Adding One To Eat And Where Calculating So Maximum Basically Software Tracking What Maximum Were Finding Right And Exactly Printed To Shoulder And Is Removed After Death But After The Maps Populated Air Force Populated The Map And Where Formed Maximum The Maximum for example in this case I studied and again width map and 135 days to entry hui turmeric basically date during this subscribe 100 years in treating them map again and vhp here two maximum entry here someone will find the maximum entry hui are just getting From the map and what is the year when the population vikram maximum bread to you taking over result variable and win back in the 10th result 100 mm super se example of data 1008 so let's radiation this example is so let's you can see the maxu is too -Do is so let's you can see the maxu is too -Do is so let's you can see the maxu is too -Do List And Max Vikram To In More Than 1000 Answers Higher Correct Answer Sun Will Just Run Through All The Examples This One And Mixture This Is Also Accepted And This Comment The System Of Solid Is Accepted So Let Me Yes Comment Of This System Locked and submit flat se the power solution god accepted by it's good for this is the way you can solve maximum population here by using trim app and you know by keeping track of maximum variable then adjust no aya offer create videos in list solution assessments java j2ee Interview Helpful Materials Against Discuss Different Interview Frequently S Problems and How to Answer Friend Problems Also for Interview Tips and Other Interview Tips Please subscribe this Channel You Will Return to Good Motivation for Your Interview Preparation Please subscribe thanks for watching this
Maximum Population Year
maximum-population-year
You are given a 2D integer array `logs` where each `logs[i] = [birthi, deathi]` indicates the birth and death years of the `ith` person. The **population** of some year `x` is the number of people alive during that year. The `ith` person is counted in year `x`'s population if `x` is in the **inclusive** range `[birthi, deathi - 1]`. Note that the person is **not** counted in the year that they die. Return _the **earliest** year with the **maximum population**_. **Example 1:** **Input:** logs = \[\[1993,1999\],\[2000,2010\]\] **Output:** 1993 **Explanation:** The maximum population is 1, and 1993 is the earliest year with this population. **Example 2:** **Input:** logs = \[\[1950,1961\],\[1960,1971\],\[1970,1981\]\] **Output:** 1960 **Explanation:** The maximum population is 2, and it had happened in years 1960 and 1970. The earlier year between them is 1960. **Constraints:** * `1 <= logs.length <= 100` * `1950 <= birthi < deathi <= 2050`
null
null
Easy
null
954
given that array of integers with even less design an algorithm to check whether this array can be reordered such that in two pairs one number in the pair is exactly the twice the other number that's about today's video Valley this is where my dream started hi everyone this is Steve here today we are going through a little problem 954 array of double pairs here let's take a look at the problem first given an array of integers a with even n so it's neither two or four or six or eight return true if and only if it is possible to reorder it such that a to your times n is the index plus 1 equals 2 times a 2 times I for every single and I mean that is greater than or equal to 0 or less than half of the array length let's just take one example 3 1 3 6 this is the output is false let's take a positive case to go through so that we can have a better understanding of what that actually means ok let's take a look at this one 4 minus 2 &amp; 4 we can take 2 and be Apple is 2 &amp; 4 we can take 2 and be Apple is 2 &amp; 4 we can take 2 and be Apple is true this is the only positive case Apple is true we can take two groups the explanation goes like this two groups minus 2 minus 4 and 2 4 to form either this array or this arrays so that it meets this requirement let's take a look what that actually means this one so here we'll say I equals to 0 right ok I equals to 0 so this becomes I equals to 0 so this is 0 plus 1 so anyone any one equals 2 this is n is 0 2 times 0 is 0 so a 0 is here and 0 is minus 2 so minus 2 times 2 is minus 4 and this one is 0 plus 1 is 1 so any one is here a 1 is minus 4 so minus 4 equals to 2 times minus 2 which equals 2 equals 4 that's why this these two elements in this group meets this definition meets this requirement right okay we just finished going through this pair and now since here I equals to zero so we just finished on equals to zero then let's increment I by one i because i becomes 1 at this point then we have here i becomes 1 which is let's just use this one as the final example as the final result to regroup reorder this array so i becomes 1 at this point then we'll take i equals to 1 here 2 times 1 plus 1 is 3 2 plus 1 is 3 so any 3 is here 0 1 2 3 and 3 index 3 is 4 right and then we'll take I equals to 1 again into this formula 2 times 1 is 2 so a 2 is 0 1 2 a 2 is here is 2 so 2 plus 2 is full so 4 2 times 2 is 4 and 4 equals to 4 right this is why this is one valid result then we can return the same is also true for this when we go through n equals to 0 and N equals to 1 we can have this one 2 times 2 equals 2 or 4 and minus 2 times 2 equals 2 minus 4 which also equals to minus 4 here that's why the explanation goes like this and given this input the output returned is true and that's the explanation of the positive cases there are working on three inactive cases for example here is 3 1 3 6 there is no way that we can reorder this array such that like saying it could be any pair we can reorder such an array for the outcome such that it can be grouped into a pair of numbers and 1 number of the pair is exactly twice the other number there is no such a possibility say this one can be grouped into one three times two equals to 6 but 1 times 2 is not equal to 3 so it's false so that's this one and that's the that's there are some notes here it is always even and defines the upper and lower bound boundaries of the given array that's it how can we tackle this problem there are multiple ways the way that I think of is pretty straightforward is that of course there's going to be inactive cases the way that I think of it is that we can first sort this array but of course we want to change one easy way to handle the inactive numbers is that we can turn all of the negative numbers into positive numbers this is one easy way to handle it but of course in real interviews and if you do this just to clarify this but when your interview will first because it's not always recommended to change the input so usually in Java or C++ it's when the usually in Java or C++ it's when the usually in Java or C++ it's when the parameter that texting is usually final so which means it's not recommended it's not practice the best practice to modify the original input but for the simplicity of this problem we can do it and what we can do is we can change first to change all of the negative numbers into positive numbers to simplify the problem and solve this array and then next step that comes into mind should be we can't use a hash map because I would okay use a hash map the key of the hash map okay let's just put it this way draw some notes to help understand okay the output is 4 minus 2 the input is 2 and minus 4 this is the original input what we can do is that we can first step that's just a 10 all of them let's turn all of them into none if integers so that we can easily solve them and construct a hashmap I'll go through that one by one so first turn all of them into non-negative like turn all of them into non-negative like turn all of them into non-negative like this and then max slap we're going to start it and then next step is we can view a hash map the key is going to be the number itself and value is going to be the count which is 2 here so in this hash map it's going to be looking at it there is going to be 2 entries here is going to be too much to you and for maps to 2 so what that means is that the key is going to be the number of distinctive values in this given array after we turn them into non-negative integers and the value of non-negative integers and the value of non-negative integers and the value of the hash map is going to be how many times that the same number appears in this transformed array why don't we read this hash map now let's talk about this when we build this hash map what we can do is that we can traverse this array the second time we can traverse this array again once but the second time when we traverse this array which is to check say this is the first time which reversed this array we check whether this do we have a corresponding table number in this map in this hash map okay so first thing that we're going to check when the second time we go through this transform arrays that first check say we build this hash map already and then we check we go through this array again so first we come in to two we check whether two does whether we have gone through this already if we have gone through this two we will mark the account value to be 0 that means we have gone through it we don't need to go through this again but say in this case this is the very first time so what just this the count of the number 2 is not 0 yes so it's 2 what we can do is that we can just double this number 2 times 2 it was 2 for the second thing we want to do is we want to check whether this map contains a key that has a value equals to the twice of this number right which is 4 in this case and then the third start what we want to do is to check whether 4 contains at least the same amount of frequency then this number appears in this array in this case is 2 so it's perfectly fine and if we can change it to 4 to 3 or 4 or to 5 that's to me fine and after this after we go through this who watches the decrement the double numbered frequency by 2 by this number because we need the same number of double numbers to balance off this number so that they can group they can be grouped into pairs I hope that makes sense in this case there are two twos and two fours and so it's a it's just a precisely balanced off so we can return to me in this case but for other complex examples we can just decrement the double numbers frequency by the number that the half number has appeared in this given array and we'll just continue to do this and the second number will go through is two but at that moment this one is already zero so again as I said once we encounter zero we're just going to continue in the for loop so here after going through the first two both value becomes 0 and then we encountered 4 again so again we check in the hashmap for we is corresponding to a zero so we'll just continue the same case applies to this fall we're checking the hashmap for is mapping to a zero so we'll just continue after that when we go through this entire ok after that after we go through this entire array if we didn't break out that means every single in this transformed array can be assigned can be recorded into a double pair that's what it means but had any moment saying if we have another case that's quite okay let's just use this example this is inductive example and a line here insert this is a puzzle and this is not 3 1 3 6 let's call it here 3 1 3 6 3 1 so what given 3 1 3 6 so the hashmap is going to be looking like 3 appears twice ok what started first one three six sorry first and then three becomes one has appeared only once in this array and three appears twice and six appears only once and at this moment we have beauteous husband or just to go through this certain terrain again so say one where we are encountering one once we go through the transform that array in the second time we check in the map when the one okay it's not equal to zero it has appeared once which has not balanced off yet so we'll double this number which equals to two will check in the hash map whether there's an entry with the key equals to two unfortunately in this case there are only two other entries which is three and six none of them equals to two so in this case we'll just to break out why because we're missing a tube that could possibly make this one a double pane because we're missing a two here that's why we can just return force directly from here or just to break out that's the part that's not active case I hope that's all clear if that's all clear then we can start writing the code then we'll go through that time complexity and space complexity in the air all right what we'll do as I said we'll just a first we'll transform all of the just in case if there are any negative numbers we'll just turn them into positive numbers yeah again this is not simple recommended but it simplifies the right the solution of this problem you would like to talk to your interview with first weather the original input could be modified if it cannot and if you still want to go with this route you can just use a temp variable to assign the original input into the temp variable and do modification on the tenth variable if a is smaller than zero one work to is a minus a ten on active numbers into nine active memories and then the world sought it why we want to sign it because every single next-biggest adamant should be we want next-biggest adamant should be we want next-biggest adamant should be we want to go through the smallest elements possible first let's see well saw the array and there will be a hash map as i said that key is going to be the distinct elements in this array and the value is going to be the frequency of that island so let's do this 0 plus 1 P 1 is 0 and plus 1 that's it and now we'll go through this array ok so first there's one more possible case which is which we can talk about which is this case on line here there's one more possible case for example it's this case in this case so what given like a bunch of zeros so depending on and apparently we know this is going to return true and this is going to return false and this is a special case and when the input of when the input arrayed this consists of all zeros so we know if it's an even number of zeros it can be all balanced out it can be two zeroes for zero six errors and we can always group any of the two zeros into one group which is a double case in a zero times two always equals to zero right but if there's given odd number of zeros in this case which is to return false this is a special case we'll just handle that first so saying we can't let me actually put them in variable map get see if number equals not equals to zero what do you a lot of things but else if number is equal to zero what we are doing just to check if count is odd or even if it doesn't equal to zero that means it's this case number it all the number is zero and we'll check the frequency of zeros if that 0 is not equal to is not an even number what just doing 10 false here that's what this is me and after all of that watch is to return true if it doesn't break out in any of these ok so now we'll just handle the regular cases where none is not equal to zero so looking at the nose here where num is not equal to zero so first what we want do is we will check whether this one is greater than zero let's handle then active cases first if count is smaller than zero what's that possible cases when that one is small what is the return false else if count equals to zero that's those cases like say after we go through the first very first element we decrement the frequency to be zero and we decrement the double number is frequency to be to decrement the frequency that the half number has in this case it becomes zero as well so if it becomes zero after we go through the first element we Traverse to the second element we found the second element value is already zero so in this case which means we have gone through all of them will just continue else is the positive case which means like say for example we visit the first time we encounter this too it doesn't it has a value which is greater than zero what we'll do is we'll use another number on double as I just said which is two times this number none yeah this number first we'll check as I just described or check this number times two is full whether for whether this hash map contains a entry that has in fact that has a key equals to full right this is one way to check if map contains key if it doesn't contain this number we can just agree return false already right this is this case 1 times 2 equals to 2 and this value is not equal to 0 and we cannot skip it which is to check if this map contains an entry that has a key with value to 2 - no it's not there key with value to 2 - no it's not there key with value to 2 - no it's not there are only 2 entries 3 + 6 Q so in this are only 2 entries 3 + 6 Q so in this are only 2 entries 3 + 6 Q so in this case we can just break up otherwise what we can do is well put in this double what decrement this double number is frequency by the whole number my name is count which is this case which is when we check there is two times two equals to four will decrement this doubled number is frequency by this count which is 2 minus 2 equal to 0 that's it yeah that's the algorithm let me double check oh the other thing that we wanted you as I just said what do this when we do when we first encountered this key which has a value that is greater than 0 what we want to is will decrement that 1 to be 0 which means we're going to remove all of them well we're going to try to find this number is doubled number value pair what decrement this one to be 0 first yeah let's try let's run code and see if there is any company where I hope ok accepted false enforced okay that's good all right then let's submit and see accept it yeah it's kind of verbose and lengthy might not be super optimal I see on discuss board there's quite a few users have put up solutions that don't necessarily need to convert then active numbers engine then active which is super awesome I didn't take too much effort to read through all of them but the basic idea is very similar to use a hash map to count the frequency and try to find the pairs then let's talk about that time complexity and the time come the most time-consuming part is to solve this time-consuming part is to solve this time-consuming part is to solve this array it's and log in and that space complexity is just oh and oh ok K is then the distinct number of elements in this given array because for every duplicate number were just to increment the frequency of this entry that's I hope you guys liked this video if you do please do me a favor and smash that like button and don't forget to subscribe to my channel I'll see you guys in the next video
Array of Doubled Pairs
maximum-sum-circular-subarray
Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[3,1,3,6\] **Output:** false **Example 2:** **Input:** arr = \[2,1,2,6\] **Output:** false **Example 3:** **Input:** arr = \[4,-2,2,-4\] **Output:** true **Explanation:** We can take two groups, \[-2,-4\] and \[2,4\] to form \[-2,-4,2,4\] or \[2,4,-2,-4\]. **Constraints:** * `2 <= arr.length <= 3 * 104` * `arr.length` is even. * `-105 <= arr[i] <= 105`
For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you already have a great algorithm brewing up in your mind in which case, go right ahead! What is an alternate way of representing a circular array so that it appears to be a straight array? Essentially, there are two cases of this problem that we need to take care of. Let's look at the figure below to understand those two cases: The first case can be handled by the good old Kadane's algorithm. However, is there a smarter way of going about handling the second case as well?
Array,Divide and Conquer,Dynamic Programming,Queue,Monotonic Queue
Medium
null
47
welcome to jbk school today we are going to solve number 47 permutation 2. so this is very similar at the Legacy that we served as 46 permutations and there is Norms array and then um we are gonna return all the possible Plantation but it should be unique so we are going to start first of all we are gonna sort this nums array because we want to avoid the duplication foreign became zero then we are gonna push Temple grain dessert and then we are going to return because um we are gonna filter it out so the permutation is like after one he'll be one two three and one three two three one so every time we are going to filter it out and then we are going to push it so if so we are going to iterate all right uh Twitter and num and index and if we index is not equal to I and we are going to put inside this array and then we are going to put the last over time plus orator I so finally we are since we are keep filtering if the index is same as I so binary our Advanced will become zero and so that time we will push the temporary in the result so uh if we push like this we will have some duplication that's why we sort the array so since the Norms is one two we sort it can be one to one about since we start to become one two foreign that's it so for the avoiding duplication we are going to sort on the top and then we are going to check if I the same as I minus one that we are going to continue otherwise we will iterate that's it thank you for watching today
Permutations II
permutations-ii
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Constraints:** * `1 <= nums.length <= 8` * `-10 <= nums[i] <= 10`
null
Array,Backtracking
Medium
31,46,267,1038
1,198
It is the number my elite qods belt that is called annoying fans as an element but rose what this problem is very simple we have this matrix and we have to find what is the smallest number that appears in all the rows for that we go to census of binary search society into account we only have to use the numbers in the first row because if not this tenth our finance test that says that it does not matter the others exist is not the number we are looking for so well first for simplicity we are going to copy They are going to be passing this matrix and 11 this I don't know how to approve all the numbers so and we are going to put check and valid something like that and we are going to pass it we are going to use the number that we are seeing at this moment which would be 0 and the column that follows which would be 1 no then this if so we are going to return of this value but with continue searching for it by search and we oppose by the number we are looking for and the lc column now not by alcohol so that you understand the search binary we always know together lentz in fact so this column that we are looking for then well yes uruguay the air m is equal to plus between 2 and then if I find it what is it is equal to the sky we find then let's see in the next one yes no then it means that this can be less than 9 is greater than not so then he's going to be equal to an elusive line 1 and if we never find the value between we return 2 so this is the minus one no because it's not right here come on we're on the first one it wouldn't pass is the one that follows ah of course what we're seeing another one this guy is the same yum because if I want we can go down but there are still a few left to see how I did it of course it's good because beaten the result seems
Find Smallest Common Element in All Rows
unpopular-books
Given an `m x n` matrix `mat` where every row is sorted in **strictly** **increasing** order, return _the **smallest common element** in all rows_. If there is no common element, return `-1`. **Example 1:** **Input:** mat = \[\[1,2,3,4,5\],\[2,4,5,8,10\],\[3,5,7,9,11\],\[1,3,5,7,9\]\] **Output:** 5 **Example 2:** **Input:** mat = \[\[1,2,3\],\[2,3,4\],\[2,3,5\]\] **Output:** 2 **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 500` * `1 <= mat[i][j] <= 104` * `mat[i]` is sorted in strictly increasing order.
null
Database
Medium
null
234
hello everyone welcome to learn overflow in this video we will discuss uh a little problem that is the palindrome linked list so this is a little problem and we'll see how what should be your thought process behind finding a solution of questions like this okay so the question is uh pretty short and simple the question says like that given a head of a linked list uh singly linked list they mention it carefully so there's a head of a single english is given to us and you need to return true if it's a palette if you remember palindrome palliative is something like say there's like uh three numbers uh you know add your link list or whatever so in that say there's like one two one so this is a palindrome so it's like the first number and the last number should uh like should be equal to the same okay so it's not three it can be it can extend up to five so uh in that case you need to check for every uh like every order the faster the last the second and the second last the third and the third last so it should go ahead in that manner so uh since there are five numbers so in that case it can go up like one two three then followed by two one so it's like uh one and uh one are equal and two are equal see the first and the last the second is the second and the uh second last so those kind of things happen if there are like four numbers both numbers is like one uh like two and two are equal one and one are equal the first the same thing the first and the last the second and the second depend uh it doesn't depend on the total level so that's not what the palindrome is now in this case we are given a lot of simply uh like paralysis or something like that but it's a link list given to us so what's the problem for us to check we cannot move back okay so there's like nothing moving back so in that case of what should be our approach so that's the whole question because we can check for that we can like in normal case we can start from the beginning and we can start from the end uh two pointers and keep moving till we don't see they are matching each other or copper crossing each other so that's not a case you can go ahead with a linked list because you cannot move back in any of the cases so what can be our idea okay what can be our idea the idea can be uh if you need to do that you can do two three things is more or less like you either can uh you can reach or like break this in two halves okay you can do that by two pointers i will tell you how so if you either can reverse the first half okay reverse the first half it means um it means like a one is there and two is there five in the first half i'm talking about so two will be pointing to one and one will be pointing to another fine so only pointing to null so that's the case you can go ahead with and or in the other way you can reverse the second half like if you do the reverse the first term then uh here is your start and the second start is over here you keep checking if they are going equally equal or not yeah and the other case you can go ahead is like you reverse the second half if you reverse the second half that uh the first step remains same like one points to two points to null uh and in the second half it will be like uh it will be same like this here's two here's one will be pointing to two and two will be pointing to null okay so that will be the idea because uh one is pointing to null so we are just reversing on each row now uh that's the whole idea how we should go ahead in uh finding solutions like this okay uh so that's our question we have but there's like a follow-up for us like can there's like a follow-up for us like can there's like a follow-up for us like can we do this in order of n uh time and order of one space so when it talks about order of one space so you need to remember you cannot use um a different uh space like an additional uh link layers or additional uh something like that but you can go ahead with something that is storing a single node or if that's storing a single value or something like that we can move with that so what how can we do that so to reach this uh half the first thing we should go ahead with uh the so fast pointer so one is like for each of the uh for every time we are moving one node in our slow pointer we should move two nodes in our first pointer so how what will that happen that we will be ending up in like in the second case will be after second step will be here okay and after second step will be at null so that's the first point so once we are at here at this uh like the start of the second half fine and the fast is pointing to none so we know that we got our second half starting so within kind of slow first pointer we do this kind of thing where on the first pointer is like uh goes two steps but the slow point is move one node at a time fine so in that case we will end up reaching the half of the linked list okay the second half and now once we reach the second half we can now uh reverse any of the half uh with our approach we can reverse any of the half and uh like skip check in that case what's happening see you are not going to the end like all the end nodes are not being covered okay so there are number of nodes we are not going to the end of the nodes like all the end nodes are not done so a few steps are remaining and then the second like while we are uh like going on with each of the slopes pointer we are going on why don't we reverse into each of the node like how do we reverse the linkage we reverse the linked list by we have a linked list uh say we have a node over here okay in a linked list that has been pointing to some other node over here fine now how do we reverse say we are at this node how do we first we keep a pointer like at this node okay and we uh simply break this pointer like make this uh next node like the negative pointer and mark it as null we mark it as the previous one or matrix null and uh in that case we then move on to the next node in the next node if uh we again break this the next pointer and mark it to its previous one okay so it's like uh on each node process so we are not traversing the node again so while we are moving in our surface pointer to find the uh middle of our uh like the linked list we can keep reversing our fast up i mean that will be much easier to do that we can keep reversing our first term so that we reach to somewhere uh like our fast stuff remains uh reversed and our second half is like we are done with our second half so that's the whole idea over here fine now uh we need to implement that okay so in the like normal sense we will simply uh check that if both the notes are going same we'll be uh finding a solution so that's the idea that's the easy idea we can go ahead with now um what let's do something else we quickly write down the code and then explain it to you again uh to what we are thinking right now and exactly how our code comes up close okay so let's do that uh whatever code exactly does over here so this is the part i just wrote right now so what we're doing we remember this uh it's giving the constraints over here so considering that the number of nodes in the list is in the red one to ten to the five so it's make sure like there's only one node now if there's exactly one node do we really need to check for this long to find if it's a link place like if it's a wall current or not if there's only one node there's no need to check we can simply say it's the uh paradigm for us fine so that's what i'm doing we are just checking if head dot next is uh current head and dot next will be uh the next value if it has if it doesn't have any next value uh that's null so you know there's one there's only one value in our head like there's only one value given to our linked list so we can simply say this is a true fine now uh now comes to the main logic of this uh four what are we doing we're just checking if uh we just we took like three uh pointers okay these are like why we're taking telling that this order of one space you can see like we are using uh three spaces only okay so if we using three spaces only so how many specifications order of three in order of one because uh it's in the order of one right so that's how we calculate the order now we took three pointers one is slow uh we named it as slow and it's pointing to head fast one two head and this is the reverse pointer it's pointing to initially pointing to null so this one will be helping us with uh holding the reverse of the first half fine so that will be our eye now what between you know step we are like checking file fast not equal none and faster next not equals that why because we'll be uh jumping twice with our first point okay so in that case why what we'll do first we will store our uh reverse uh like a pointer to a reverse in a temporary uh node at the stem and then we are pointing reverse to slope fine we are doing that and then we're traversing slow uh like once and then we're reversing fast twice further we are pointing reverse to 10. so let's uh understand this in a like single example if there's like one and two okay so there's like one and two given over here so what exactly happens to our one two in this case um so in this case if we have one and two over here then the first thing we'll doing will be pointing say river and this reverses are fine we're reverses initially none okay so there it is pointing to that and then uh there's select temp for i'm writing as t so temp is again pointing to null fine initially it's functional and we are at this ahead so slow is slowed out next so now and like 10 pointing to none and then we're telling reverse pointing to slow so we are quite telling reverse pointing too slow now so what is slow pointing so reverse pointing to this point because slow was initially pointing to head right now uh further we think slow equals to slow down text now slow moves to the next pointer so here is our slow pointer is setting over here after this line now next we are doing fast equal to fast dot next okay fast dot next now fast was also initially i said okay fast was initially i said now it moves to false dot next why is it pointing to none okay so now uh fast is first becomes none and we then do reverse dot max equal to 10 so reverse dot next reverse was initially pointing to the first node because that then that's where uh slow was pointing before slow was moved to the next note okay so reversal is pointing so reverse dot next will be rev uh we are parking to the temp so what is steam pointing can point to null so we are just breaking down this uh linkage and after breaking this linkage we are reversing it in the other direction and pointing it to null fine so that's the idea now we don't uh lost track of the rest of the list because slow is still pointing to there and fast is has movement to the next node now after this step uh can we move first because fast is already now fine if fast is already null uh in that case uh we cannot move this further so we know that we have two halves ready for us and next we will check uh i'll come to this a minute later fine uh then we'll check if reverse is not null while reverse notebook so the first is not pointing at all right now so we will check if slow value not equals reverse value return false so one not equals to return false yes okay and for the if this falls doesn't hold if they are equal then what will be we are moving slow to next uh in this case we don't have values and we are moving reverse to next reverse dot next was pointing here sorry there was no next point so it's like we are moving reverse to the next and we'll just go to the next we got in the middle and now we're moving back right and after like checking for the all the values uh if you find uh reverse is null so we are done without all the checking in that case what we will do is simply return true because that we found our target we found a match complete value of match now yes i mean uh left something just like fast naughty cause now why are they checking that okay i say there are like three values okay say there are three values so first uh like after this say there was a value like uh over here called once again fine so after this uh fast is currently pointing to this value and our loop will this particular while loop will break because fast dot next is not equals null so fast is not null but fast dot next is null so we cannot move to a null value so in that case uh like what we'll do we cannot move slow further but is this the middle because if we uh move uh like this is like what i'm meaning is say one two one right or slow is here our reverse is here and our fast is pointing here okay but if we start checking for slow and reverse from this position it won't match but we need to move slow to the next position so that uh like this is an odd number of cases like this holds true only when there's like odd number of values or all number of nodes over here right so that is the only check we are going on because there is no point checking for two but that's an odd number we will check for the this one and this one fine uh like not the middle value check is not made because that's anyways in a paragraph so that's the idea so this is how our code for works and obviously it works in order of n you understand why is order of one because uh we have only fixed number of variables we don't have a uh a complete link list or we don't have a complete uh value like that but we have simply uh like simply your single uh nodes for us right now uh what exactly we're doing we uh we exactly have traverse likewise the order of n order of and you can understand because this slow dot next look at the slower things this one is traversing only like uh like others are moving back moving forward uh someone is going back forward in two steps someone is moving back after fusif okay so but uh this load up next is one traversing the whole list okay in that case we find that this is uh traversing only once we are traversing again and again through the same list okay so that's how it's uh order of one point order of n as a time so that's more or less about this uh video guys also i missed this one why head dot next is not because uh there's one value right we are sure that there will be one value only now we got one value like there can be one uh father we are taking if a head is currently here so uh the normal check that we do is like if head is null or not if head is not it's not a case because there isn't like zero values zero nodes are not possible there is at least one so we uh are checking if head dot next is null or not if hindered makes this number that means there's only one value if dot next is not null that means there are other values it may be two eight maybe ten to the five any values like uh any number of nodes may present but then at least if there's like only one value we are done with this so that's more or less about this uh video guys so i hope i can make you understand how you can uh find a solution or think on finding a solution to this kind of questions and uh if you have any doubts on any thing if you don't understand make sure to comment down in the comments below i'll be happy to help you out in the comments as well uh so thank you all for watching this video uh hope you see you soon my next video as well thank you i
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
1,416
Hello everyone welcome you are going to do video number 26 of my channel ok and the name of the question is restore d are liquid number one on one six friend I am telling you even if you are a beginner you can solve it dog just a little bit Please wait for my explanation, it is a hard level question but it will be very easy once you understand it ok in this video we will make recjan plus from momo and further we will upload the video in which we will also learn bottom up ok so Amazon Microsoft Google and This question has also been asked in many companies, this question is called very good and don't worry, when I start a playlist with DP concepts, I will tell all the topics separately in it, like this is also a type of DP question, okay. There are many other types of DB questions, so this is also a type, many questions will be made on this too but that will be a different playlist with concepts. Okay, so today we have to learn and I am telling you again that even if you are a beginner, you can After solving, people, if I have explained to you why this is a DP question and how to write this question, then listen to me carefully, understand the input output and do the rest on your own. I promise, okay, if you understand the question. Let us understand the question of this, the question is quite simple that there was a program and it was suppose to print here but what did it do, it forgot to put white space while printing. Okay and sir, I know that a string of digits should be printed. It is written here and that which they know is the date which these teachers in de re were in de range of one. All the interiors of you were in the middle of one. Okay and there is no leading zero. Okay, so now it is asking you that it has given you the external which has been printed in the program without giving any other space and has given the value of one key, whatever value is between one and one. Wait, they will be okay, you have to tell the total number of possible arrangements which can be printed, which program should have printed it. Okay, so if you look at example number three, look at this example, this is a better example, such programs. I printed 1 3 1 7, did not put a space and see what the range was, how possible it would be that it was 1317, it was mine and it printed it and see it is fine between one and 2000. Now see this. It is also possible that the intake is between 1317, that is also between one and 200, it is 13 17, there are total 8 possibilities which can be the answer to this, see all, between one and 2000, okay, so the question. So it is understood, now we have to find out how many possible totals can be made. The answer is eight because look, there are eight possible races. You can see. Okay, so now let's understand how the engine was built. How did I know that this is a DP question? Then how will we write its explanation, let's also see. First of all, nothing comes to mind. How did I understand that this is a DP question? Then what was my tuition? Okay, so remember when I was watching this example in the lead code. So I noticed that once I broke it down and showed it could be mine, it must have been like this, okay, there was also this, if it is not a little, then it must have been 1317, okay, once again it happened that I saw a little from here, 1317, then it happened. That I have broken a bit from here 131 comma 7 So you are seeing that my breaking position is changing, here I have not kept a breaking position at all, okay, here I broke on this index, then I did not break on this index, a little on this index, okay So you have two possibilities on every index, either you can break it on the index or you cannot break it on the index, so what are the possibilities you have, like if mother takes 1317, then what did you think that brother will break? Not only this, we keep the division here, we got the complete number, second time, what did we think of brother, we break it here, okay, we got one number one, the second number is 317, but they have you insured, which one is the number. And this number 377 should be between the two, so we will check that, but what is my intention, how did I understand that there can be a question of DP, okay, so now look, I have many options. I can do a split here, look at this or I can speed up here, if you speed up here, then I will explore the saree option, okay and where I got a state like mother takes it, where I got a state which is First I have solved it, I will memorize it, okay and get the result from there, so let's do one less, make a small three diagram and understand its flow, look at its flow, let's make a tray diagram of it, take an example from us here. I have kept the bill you will always start from starting, okay so we are starting from here and now you just have to decide that right from the start you do zero one two three, from where to where you have to take which string. People can do it either from zero to zero. If you do it from zero to zero then it means that we have kept our India here. Okay, so what will you get, you will get only one number and the rest has gone back. Is it 360? Okay, 3817, so 3817. I will do further analysis, okay if I index it then one will become three, so what is the start here, this time I want to take the start from one to one or from one to two or from one to three, okay so now. And let's see the possibility, maybe I thought that if we don't take it to India, then we will take the string from zero to one. Okay, so what will I get? 13 A will go, right? 13 A will go, so many children will I have, 17 children, I will have 17 children, correct. I will say that if I want to take the number from tu to tu then I will get only one or if I want to take the number from tu to three then I will get 17, okay then we will keep taking further decisions and then what can be done in another language too, I said that No, let's take these up to this point. Okay, the index from start to end will be 2, so what will be the number? 131 will be left. Will I have only 7 left here and then I would have started here from 3. Correct because I have taken the numbers from zero to tu. Isn't it 131, one more last possibility, what is the brother, I took it and took it till here, this is mine, you will get the full number, 1317 and here is my start, I took the bump, otherwise my last start will be four, and by the way, here I will have an empty string. Okay, so see where the index has reached. I have reached the start index. What does it mean that I have made one more complete, one number is complete and which number is that? This one is the complete number. Took the complete digital and corrected it, so I got one answer from one thing and why is this answer correct for me because it is between one to 2000, see it is ok, now similarly to the other branches also these branches, so now this branch, now I can't go ahead, this is over here, now here in this branch, if I move ahead, there are many possibilities in this too, first of all, there is one in the beginning, but if I keep it till one in the end, then what will I get and I will get three back. Gone here 17 okay then here for 17 where will my start from you will start from you because I started from and my what is mine was till one now the next 17 is 1 and 7 so my start starts from you Now, similarly, similar further branches would have come here also. Now notice one thing, why is this a DP question? The answer I will solve for 17 will be mine and the answer I will solve for 17 will be the hope. This is from both the statuses, so why not I will memorize its answer and do it here, then date it from the same three drivers, it is easy to know that this is DP's question, it is ok and you will get the solution from here as well. It must have been understood that you will send index zero in the beginning, this will be the start, then you will put a loop on you and put the end everywhere, first you will say that keep the and till zero, keep the friend banded, then keep these till you, okay. So look at this story we have created, what would it be like if we just write the code for it, so first let's write its story point. First of all, what I said was that in the function I am going to write, I will start the index from zero. Okay, so zero. I will start with I will also send my S string and when I will send it so that I know from where to where I can take the numbers. Do you remember I told you the range? You have to make the numbers in between the lines, okay so this My start index is okay and what I said is that whenever your solve function is, what I said is that if your index is the start, if that is your start index, if that is your start, if it is greater or equal you become. What does s.length mean that you have exhausted all the characters What does s.length mean that you have exhausted all the characters What does s.length mean that you have exhausted all the characters and you have reached the end? On one thing, it means that you have successfully included all the characters. Okay, what does it mean that if you have found one thing, then you return one. Do dog here, which is the correct one, I am talking about you, I am talking about this thing, look, we have reached the start index, that means we have got one thing correct, here we have done all the characters and this is our result. It was there, that's why I had returned one from here, that one thing has been found, that is the total number, so one way has been found, so I have returned one here, okay, thirdly, one more thing, I had told that if the leading Should not be a hero, it is given in the question, if the starting of S is the starting, if my starting index becomes zero, if the starting index is zero, then brother, you cannot do anything, make the return zero, it means what will be the example, its example is something like mother would have taken. My S was something like this 0 1 2 3 Okay, so its leading is zero, no number can be zero, waiting for that, I had given in the question that whatever number is there, it must be between 1 to K. There ca n't be a zero, so even on the story, if you see a zero in the leading, then return it now and say that there is no possibility, thoughts are the same, I am answering this zero here, so I have returned a zero here, okay now. Let's move ahead, after this, what I said is that the most important thing is from where to where I would like to take the string. So what I said is that we will put a loop and where will I be from where to where, what will I say in the starting, let's take it from start to start. So there is more start, that is, from start to start, I have taken the character and how far can I go, I am taking the string, okay and here we will also check that the number being formed is not the same, give it should not be greater. It should not be greater than one and it should not be less than one means zero, we have put that check here, so here we will just check that greater den should not be zero, greater den will be zero. So there is no use in checking further, if it is correct then break it here only, there is no need to continue the loop further, break it from here itself, I will give you an example of when I am breaking, I will take your one. The limit given here is 15, but the S given to you here is something like this There There There was more here in the beginning, so what should I get? Okay, after that, let's take the mother. If you put it here, then you will get one thing from it, you will get 25 rupees. Look, this 25 has not come in my mind, okay, so leave this matter, now there is a need to make more, do you take more mother? If you have brought it to your place then you will get an even bigger number, you will get ₹ 253, which is for get ₹ 253, which is for get ₹ 253, which is for greater, give A 150, that means look, I came to know here itself, it was here itself that I came to know that the number being made is going out of this range. If it is increasing till the end then what is the need to increase it further because you will get a bigger number from the start till the end. If you get 25 here then if you increase the end further then you will get 253 and if you increase it further then you will get a bigger number then there is no point in further increasing. Date, break it there, okay, so what I am saying here is that if you get such a number, it is a greater date, then break it, there is no need to take it forward, okay, and if not, then it is very good. I will solve it again tomorrow and what else did you send? If you were sending the index, then remember from where the index started. Look at the start just now. Pay attention, what will be the number from start to start. Send n+1 in the index. Why that, what will be the number from start to start. Send n+1 in the index. Why that, what will be the number from start to start. Send n+1 in the index. Why that, understand from here. Only you will understand what I said, the start is zero and the Indian mother takes it till zero, okay, so this one is gone, the rest of the children, is it okay for next tomorrow, so this 13 was my number, this is 13, so my next. What will be the index? For the next time, it will be the number 17, so it is Tu Hai, which is N + 1, so Tu Hai, which is N + 1, so Tu Hai, which is N + 1, so what will I send here, actually, I will send plus one. Correct, S was sending and K was also sending, okay last. I will return the answer. Okay, so whatever your story points are, they are exactly the same as mentioned. Look at your treaty diagram, these three diagrams were important, so let's just convert these story points into code and where to do the memories. It will definitely be necessary, we will do it there, only one index is changing, only one parameter is changing, so our 2D, which I am sorry, which is memorization, will also be 1D, wo n't it? We will memorize the result in this, so you would have courted it. If so, it will be more clear, before saying OK and good, let me tell you a small option, remember I was saying that Maa takes it, this is our number and your start is here and Maa takes it and is here, then you have to repeatedly- If you is here, then you have to repeatedly- If you is here, then you have to repeatedly- If you were right in the beginning, then it is better to do the substring than doing the substring. When the loop is going on, at this time you form the number. If you were right in the beginning, then my number in the beginning must have been zero. Okay, then what will I do? The number is equal. What is your number, look at its number, it is 0 * 10 + 2, What is your number, look at its number, it is 0 * 10 + 2, What is your number, look at its number, it is 0 * 10 + 2, now my current number is you, it will be here, okay, then number 25 should come, my number is 25, how will it come, look now, what will be my name, 2 * 10 + 5 will be 25 then Baba, it 2 * 10 + 5 will be 25 then Baba, it 2 * 10 + 5 will be 25 then Baba, it is not necessary to extract it by substringing. Substringing itself is a one-off operation, Substringing itself is a one-off operation, Substringing itself is a one-off operation, so the time limit will be the same. Okay, so the but loop will be running like your but how were we going to write the look, but here we have It was written, sorry, please check What should be the length from the start, then the time limit will be reduced by one seat and the best option after is that you measure everyone tomorrow and keep making the number, isn't it, during loop only, so this is a short one. Then we will check it by doing all the string related things, it will not be accepted, you can check it, okay, so let's code it, first of all, we used to keep a global variable in which I have lancrizerized the string and kept it as n = length, now we have stored it. I will write my recjan recursive function here I am doing zero in the start and send the string and what am I sending okay I have to write my function in and solve enter start my index is this and what are I sending okay now look here First of all we have exhausted and they have reached a good path in which we have included all the characters and our arrears have been stored. Okay and one more important thing what we have to check is see if I have zero at the beginning of S. What does it mean that it is not valid because it is given in the question itself that there cannot be any leading zeros. Correct and there are no leading zeros in D, hence we will put zero here, okay. After this, let us create a variable named answer. Okay. And what did I tell you that we will keep making numbers simultaneously, it is okay, I told you the story point, then it will start from the beginning with N and plus, so if we keep making numbers, then the numbers will be in 10 plus whatever is my current character, so what is the current character? Start off steering off and if you do mines off zero character to convert it into interior then it will be converted while waiting so this is my number A. Now I said that if my number is of Greater Dane then at this very moment I will break further me. There is no need to move ind because the number will keep getting bigger and bigger. Correct and if &gt; bigger. Correct and if &gt; bigger. Correct and if &gt; k is not there then we will store the answer in our answer plus then we will do the function tomorrow and this time my n + 1 will be the do the function tomorrow and this time my n + 1 will be the do the function tomorrow and this time my n + 1 will be the further index. Why there will be N + 1, further index. Why there will be N + 1, further index. Why there will be N + 1, why there will not be start plus one, I have told you in the example, okay while explaining, send S here, send K here and our answer in the last will be the return answer, okay, we have sent the answer here. Given and given in the question that if you want to send the answer in the modal, then let's define the modular one here, keep it a constant, power it 9 + 7, okay, let's solve it with this value here and power it 9 + 7, okay, let's solve it with this value here and put the modular here. Let's also put a modal because the value will be too big. Thought it was said in the question that we will put a modal. If we submit then what is the time limit DB of Hey, if we take it, let's take the vector of size and populate it with minus one, it's okay, now this observer will also have to be sent to T here, I send T to the vector of and T and check here. Let me tell you, before proceeding further, if I have solved this state, first this note is equal to minus one, then it means that it is already solved, so I store its value and send it back. And if it is not there, then it is my duty to store it everywhere. Before sending it, I also store it here. Let's make it a memory before sending it. Let's run it and see what is missing here. Okay. Here also we will have to send T, okay, I will maintain this time, you guys can also do it. If you did not do it, now I told you that I am making money here and also if you do not do this then the time will be lost. Okay mother, let's take it, you have not created the number here, okay and you are creating the number by substringing your S, so most likely it is bill given time limiting, okay, you can try and see, but by the way, this is a very good question and this The topic is fine, many questions come based on this, so we will do it on the playlist with the concept of our DP, I hope, I am able, you can help, any doubt is resident, common area and try, help see you, gas video, thank you.
Restore The Array
check-if-an-array-is-consecutive
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits `s` and all we know is that all integers in the array were in the range `[1, k]` and there are no leading zeros in the array. Given the string `s` and the integer `k`, return _the number of the possible arrays that can be printed as_ `s` _using the mentioned program_. Since the answer may be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "1000 ", k = 10000 **Output:** 1 **Explanation:** The only possible array is \[1000\] **Example 2:** **Input:** s = "1000 ", k = 10 **Output:** 0 **Explanation:** There cannot be an array that was printed this way and has all integer >= 1 and <= 10. **Example 3:** **Input:** s = "1317 ", k = 2000 **Output:** 8 **Explanation:** Possible arrays are \[1317\],\[131,7\],\[13,17\],\[1,317\],\[13,1,7\],\[1,31,7\],\[1,3,17\],\[1,3,1,7\] **Constraints:** * `1 <= s.length <= 105` * `s` consists of only digits and does not contain leading zeros. * `1 <= k <= 109`
Try sorting nums. If nums is consecutive and sorted in ascending order, then nums[i] + 1 = nums[i + 1] for every i in the range 0 ≤ i < nums.length - 1.
Array
Easy
298,549,1542
383
Jhaal Ajay Ko Hello guys once again welcome all of you to your YouTube channel TLC so what is the list in today's video new question ransom note nutrition is easy if you have not subscribed the channel before starting the video please Do more ignorance today I am creating a complete playlist of Ignore the Day so just for now regular like we are editing so Dhan now we will also do Jeev GKP mode so just after this video the next video should be uploaded just man Let's start the EP mode, let's start the video, there are two settings for life, friends, we have a note and a magazine and it is being said that it is true or false, tell us that if the anthem note can be made from the maxi, what to make? Told the method that if there is a ransom note, friends, our note is something like ABCD and magazine are something like this magazine also has some tractors, there is a train, there are some characters given in the fridge, all the Lok Sabha are sitting, this is ABCD and we are told by doing this. That we can make a tension note from this magazine, how to make it, we just have to use each character in the magazine only once, the sign is that like now A is here, if B is used then not again if love. When it was done, it was removed, so I took note of the festival, took out one lettuce from this, then there was another heavy president, it was not needed because there is only one empty, this one is there is one here, so I took out the middle one and also one C. If taken out then yes we can become an 11 inch emperor magazine, but if I add one more thing in this, see I am in green, I would remove ABCD from here and make it simple so that it is AB in Desperation Demonetization Na because there is one, then come Will go wife will come 80 will come so that's all I have to do so what to do this let's make the hanging room part and in the lineage now for the tractors of this point note what is what and that time trust for its crush our Here my work will be done by only one person, what frequencies do we collect for the characters of the deposit machine, so now just one answer, open the Ghaghra app and go to Catering Magazine, a magazine, this character in m1 vs Rush. Battery saver mode switch off sequence so f-18 f-18 f-18 customer services for each character in run sham note what else can happen in the character then I would be that if the character which is in the character or in the is in the but the frequency of that What is it that if it is not allowed then what have we said otherwise what can you simply say return forms left in these prescriptions will give if in the vantham note then in the magazine then that is the character but its frequency is already 0 we are pregnant We will put a condition for embarrassing the matter, here what do we have to do in the character notice lemon otherwise, simply we will reduce the frequency of whatever character is ours and in the magazine, if there is that too, then I will pour it, meaning what will we do? In the map, that particular currency Rafi Ghanti will be minus one and then we will check that if its fee becomes zero, if it becomes 3.0, then they can fee becomes zero, if it becomes 3.0, then they can fee becomes zero, if it becomes 3.0, then they can simply remove it to the joint collector, then on the basis that now it is of no use, anyway, we have duplicated it. Have to do pet last, if everything goes well, then returns, be patient and share, Siachen ransom note is ok, point note, I am loot, ok, if you like the video, then like it and just after this video, I am uploading. The videos for the problem of date of birth workshop starting playlist please play list also and subscribe the Channel join the group and Lakshmi the next video ok guys back
Ransom Note
ransom-note
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_. Each letter in `magazine` can only be used once in `ransomNote`. **Example 1:** **Input:** ransomNote = "a", magazine = "b" **Output:** false **Example 2:** **Input:** ransomNote = "aa", magazine = "ab" **Output:** false **Example 3:** **Input:** ransomNote = "aa", magazine = "aab" **Output:** true **Constraints:** * `1 <= ransomNote.length, magazine.length <= 105` * `ransomNote` and `magazine` consist of lowercase English letters.
null
Hash Table,String,Counting
Easy
691
1,046
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem is last stone weight very easy problem we are given an integer uh area of integers where stone of i is the weight of its stone so this integer error is given to us and each uh element at each index is the weight of the stone we are playing a game with the stones on each turn we choose the heaviest two stones so whatever have like two heaviest stones whatever heavier stones are your we will choose them we'll miss we'll smash them together so suppose the two heavier stones have weights x and y uh with x less than equal to y so if x is equal to y meaning like x is a weight of one stone y is the weight of another stone so if their weights are same so both stones will be destroyed like obviously when we smash them if weights are same so both will get destroyed completely and let's say if x naught equal to y so whichever is greater like if so y is greater so y minus x amount will be left right so that is if x is greater than x minus y will be left okay so at the end of the game there is at most one stone left so it might happen that there is no stone left or it might happen that there is only one stone left at the end of the game so we need to return the smallest possible weight of the left stone so see what could be possibility they are saying that at the end of the game at most one stone will be left one stone so either zero stone like meaning no stone is left or one stone is left so if zero stone is left that will be obviously the smallest weight left stone zero is obviously the smallest value and one stone is left then that will be the smallest value so we need to obviously we'll be choosing see that we have to choose the heaviest two stones okay for example let's see this test case so here very easy problem right just we need to every time pick up two heavy stones so see here these all are the weights of the stones right zeroth weight zero stone weight one two three four and five so first of all what we will choose seven and eight these are two uh or the big values heavy um like largest values in this area so one stone has weight eight and other stone has weight seven so when we smash them together uh eight minus seven one will be left right y minus x one will be left so array will become two seven sorry two four seven is gone now seven is gone and eight is gone two four this one and the left this one okay now again we will pick the two most heaviest stones so these are two and four so if we smash them together two and four are smashed together so how much will be left four minus two so this is gone one these three ones and this two right now this is there now again we will pick the two most heaviest stones so those will be two and one so when we smash them two minus one will be left so this is gone and this is gone so one and this one okay now again we'll have to pick the largest stones two largest stones so obviously all are same so we can pick one so x also is one and y is also one so if they are both are same so both stones are destroyed hence left will be nothing right so this is also gone this one and this one is gone now see only one stone is left so this is the smallest weight which is left at the end smallest possible weight of the left row so either uh no stone is left or at most one stone is left so at most one stone is left we cannot smash it with the any other because there is no other stone okay so output is one so i think it's pretty much clear right what approach we should use uh what we are doing here is see what we are doing is we are every time picking up the two largest values so here uh what it will be 2 7 4 1 8 1 2 7 4 it is 4 1 8 1 one approach is that we can do simply sorting we can sort it in decreasing order right every time we sort it so 8 7 4 2 1 will be sorted and these will be the two largest values we will pick them if they are equal then nothing will be added in the array but if any like if they are not equal if x is greater than y we will do x minus y and add it to array and if x is less than y so we will do y minus x and we'll add it to the area similarly we again do the same steps we sort the error right and again we'll be doing the same thing right so this is one approach but obviously we can see right this is not optimized approach because every time for every iteration we have to sort there right so if let's say we are doing m time so m times and every time we have to sort the array which is n log n so this is not optimized approach right we need to think some thing better so now see whenever sorting is there right what you can think of is using heat you can use heap right heap we can use and here we need to get the maximum values every time right so what we can use maxi so let's see how we can use that let me raise this just try to think how you can use maxi uh so see we'll be taking a max heap because every time we'll have to take two largest values right so see what we will be doing very easy we will have this max heap initially we will add all the elements in the maxi 2 7 4 1 8 and 1 okay so every time what we will be doing we will uh this maxi will arrange the elements in the like whenever we pop from the backseat it will give us the maximum element right this is what maxi does it will give us the maximum element whenever we pop element from it so first of all let's say x we are popping we get eight and then we are popping wire we get the next greater element which is seven so these are popped from the maxi so this is our maxi max okay now x is here c obviously every time see this since x we are popping x first so obviously it will be having the maximum value and y will having the less lesser value obviously x will be greater than y because we are popping from max e when this value will be bigger and then we are popping y so obviously that value will be smaller right either they will be equal or they x will be greater than equal to y greater than y so if x is greater than y we will add x minus y in the maxi so he here x minus y eight minus seven will be one so one we will push in the maxi so now maxi is something like this is not there and something like this is the maxi okay now again we will do iteration x we will pop from the maxi x will be the bigger value for 4 which is the maximum and then this will be popped right and second value we will pop y which is 2 so 4 minus 2 will be 2 hence 2 will be added in the maxi so 2 will be added in the maxi okay now again we will be iterating the max heap until max heap size is not zero or empty right uh is like one or empty so if uh max heap size is one we will stop there otherwise if it's zero also then we'll stop so see now again we will be popping the maximum value which is two and this will get popped in the next maximum is one only so one will be popped out two is greater than one two minus one will be one so these will be popped out and one will be added in the maxi okay again so right now since maxip size is not one or less than one so we will keep doing this we will pop from the maxi one and next one will be popped out now they are equal one is equal to uh one is equal to one so we will not do nothing we will just pop them we will not do nothing we will not do anything because here both stones are destroyed right nothing needs to be added so just please get removed from the maxi okay now see now max heap size is e is equal to what 0 is equal to 1 right there is only one element in the maxi hence we will stop here now we will stop and this will be our answer okay i hope you understood this approach now let's see the code for this uh python code will be in the description as well as java code so see uh just do one thing try to code yourself pause the video and see and try uh writing code by yourself so see this is maxi we are taking right this is maxi and then what we are doing here we are first of all adding all the elements in the maxi so first of all we added everything in the maxi and until size is greater than one we'll be keep on popping from the maxi if x is greater than y push x minus y in the maxi at last if empty uh max heap is empty then 0 obviously will be returning because 0 is the minimum weight smallest weight which is there otherwise we will be returning a top element which is right one okay so i hope you understood the problem uh java and python code with me in the description if you found the video helpful please like it subscribe to my channel and i'll in the next video thank you
Last Stone Weight
max-consecutive-ones-iii
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone. We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is: * If `x == y`, both stones are destroyed, and * If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. At the end of the game, there is **at most one** stone left. Return _the weight of the last remaining stone_. If there are no stones left, return `0`. **Example 1:** **Input:** stones = \[2,7,4,1,8,1\] **Output:** 1 **Explanation:** We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then, we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then, we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then, we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone. **Example 2:** **Input:** stones = \[1\] **Output:** 1 **Constraints:** * `1 <= stones.length <= 30` * `1 <= stones[i] <= 1000`
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
Array,Binary Search,Sliding Window,Prefix Sum
Medium
340,424,485,487,2134
373
Hello Gas Welcome To Me YouTube Channel Today We Are Going To Solve D Daily Leaders Challenge And Produce Problem Name Is Find K Pairs D Smallest Some So D Question Statement And One Elements From D Second Ring Written D K Pairs With Smallest Some Question Elements Of D Terms tu have tu return se relatively in the first three bears then they have tu return d deej prepare ok that is what will show here that they bill fight that de basis of de sum and return after that then they will do the root first when Did something more optimize? You solve this question but I also tell you what you are writing. How to define which value, what is it representing? Example: I have two elements, here what I am creating will act. Mid hip is okay, basically it will pop or you will move it on, just fix the value of the next greatest element possible, and I am moving on the number one, so this one is less at 72, I have already done the value of priority, value of one. Okay, now the minimum element is one comma four, so I will pop this also and apply it in my answer. It was available to the student. Again, I want to explain once again if I am late then I am right now. If I move forward, I will get seven comma four. Next okay, if I move nurse 2 near me, then next I will get band 6. They are already no. That we should not always move. In this way, the reason was that because the 7 comma was you. They are already available, why is it a priority and they cannot put D to par again multiple times, but what is the reason here, but one comma is returning 6, so one approach is because the number of one six is ​​minimum and we have to If you want minimum all is ​​minimum and we have to If you want minimum all is ​​minimum and we have to If you want minimum all pairs then it was and have put it d one comma six second region we don't know what is there, we do n't need to check, we can speak directly then it will always be my elder okay so what will we do, ca n't move on Because it is D and so all the pears and K signifiers are finished, there are 13 so 7 comma four will pop at the last one and it will be included in the answer which I have to return then the problem is it is possible. I will form them, I will put them in priority, I will prioritize the elements, then I will pop them, after popping them, I will check that the element which I have put in the particular which I have popped from d witch is there on d top of d priority you date is its next supplement in it. If available, then I will prioritize it again by restarting it by keeping D and value of Jas once tu which is the next element. If I want to prioritize off, then one witch is having minimum. How will I implement it? Basically, by doing this to find Date I would you should also tell if there is index but in that index is made NMPS element is in the period that index is proof if sum is told then sum of these elements is ok and if you construct inward you insert d value then I will give priority of note type Index and buy sum of D value only in the evening. How to do this thing is this method. User can define cooperative. We have to write the operator and here the two values, Noida, have to be kept on the top. If its sub is minimum then I will be greater. Give equality, what am I telling you, if the sum of A is greater than us, then just return the function, I will tell you, then it will keep A at the bottom in priority, okay, this thing has to be kept in mind, I am passing parameters to myself. Inside our operator, there will be a user defined cooperative second parameter, it will come on the top, it will come at the bottom, the second parameter is due to this, I always have the minimum of elements, those notes are on the top, so you have understood the mic cooperative, so I have discussed what we should do first. Were fixing the index, will make a foothold with every index of number one on priority, now we know whether we need this purse for IT men or anti analysis, I have already liked the number of players who are available, how can I do that? If it is less, then how did the handle date particular come to him, this particular country, well, what am I doing after that, I pop the element on top, I pop it, I know the element is there, but the vein one index one will be the element, okay and then If I want to do an element then I wanted to give brother id any value on 2, index it, now I make friends in my priority, I will ever have a smaller than the range, if it is smaller then what will I do, I will make a separate one in priority. New note will be made of de par and next one index tu plus tu and its sum kya hoga element will be available I can return date so thank you for watching this video if you found the video helpful then please subscribe to me YouTube channel like this video thank you
Find K Pairs with Smallest Sums
find-k-pairs-with-smallest-sums
You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`. Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_. **Example 1:** **Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3 **Output:** \[\[1,2\],\[1,4\],\[1,6\]\] **Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\] **Example 2:** **Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2 **Output:** \[\[1,1\],\[1,1\]\] **Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\] **Example 3:** **Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3 **Output:** \[\[1,3\],\[2,3\]\] **Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\] **Constraints:** * `1 <= nums1.length, nums2.length <= 105` * `-109 <= nums1[i], nums2[i] <= 109` * `nums1` and `nums2` both are sorted in **ascending order**. * `1 <= k <= 104`
null
Array,Heap (Priority Queue)
Medium
378,719,2150
1,551
hello everyone welcome to my channel code with sunny and today i'm going to discuss the problem minimum operations to make array equal index number is 1551 and the problem is of medium type of lead code okay so before moving further i wanted to make clear to you all guys that this problem i don't think that this problem should be categorized into as medium type because once you understand what is happening here in this question the very simple logic that is actually implemented here if you are going to understand this then it will be like very much simpler to you to analyze this problem and find out the best solution for this problem okay so let's for now let's read out the question first we have been given an array of length n where every element of the array is like a start with a zero based indexing i and area of i should be written as twice of i plus one okay for all valid values of i in one operation we can select two indices x and y and it would be like x should be greater than 0 and y should be less than n and subtract 1 from the array of x and add 1 to the area of y that is perform this operation okay the goal is to make all the elements of the r equal now it is guaranteed that the all elements of the array can be made equal using some sort of operations given an integer and find the length and the length of the array find the minimum number of operations needed to make all the elements of their equal okay so now the problem is very much clear we have been given the array actually we have been given the length we can build up the array like this and we need to find the minimum number of operations to make all the elements of the array okay so let's move further to look out the constraints and it's going to vary up to at most 10 power 4. okay let's move to the example to find out what should be the best solution for this problem okay you can see i have taken over here the two examples where in the first example n is going to be odd and second example n is going to be even now you can see area of i is basically like twice of i okay so i'm going to write it clearly twice of i plus one so if you fill up the array if you find out the array it would be like this one and this one okay here for n is actually six and here n is actually five okay so now what is the main logic that should be uh you can say interpreted to find out this and so you can see uh the what should be the like median of this array basically i want to calculate if n is going to be odd i am going to just make all the elements uh coincide to this middle element you can see basically we want to make the all the elements of the array equal and we are basically finding out the median what should be the median of this array you can see if the array is going to be like sorted order the median of array is going to be at 5 so my base my basic approach should be just make all the elements just coincide to this median value okay and how we are going to do that and why should this approach is optimal you can see uh basically i need to do this operation array of x should be like subtracted by one and area of i should be incremented by one now you can see these two elements are like symmetric about median if you pick a five the difference between five and one is exactly four and the difference between five and nine exactly four that is one is less than five uh less than uh by amount four to the left of it and 1 is more than by amount 4 to the right of it this gives me the idea why not to find the median so that we can have an optimal approach we need to decrement by 1 and we need to increment by 1 to any of the elements okay at one time in one cost operation okay so i'm just incrementing one to two and nine to eight and i'm going to do that until and unless when the elements coincide to this five okay and you can also see in one operation i can just increment one to two and decrement nine to eight and in again operation i can just increment two which is my new element to three and eight to seven okay these are the two operation again you can see uh i have the elements of the array like you can see uh three and again three and they had it is five and here it would be like seven and here it would be like again because i am finally at 7 i have applied to operation 7 now you can see again these two are elements exactly at the same difference about the median and to the right of it has the same difference that is if you subtract 2 from 5 it is coming out to be 3 and if you add 2 to 5 it will go out to 7 it means the elements are going to about symmetric about the median okay so just to subtract 2 times more that is 7 to 5 in one operation and corresponding to that 3 should be incremented to five also so this will give us the optimal approach that is start to start making all the elements just go inside to the median okay now the one more idea that i should want to give to you is that you can easily see this is basically the arithmetic progression you can see the difference is coming out to be 2 3 5 has also the difference two and five seven are also the difference too and you can easily see if you find out the sum of first n terms of this arithmetic progression it will come out to be n square sum of first one terms one sum of first uh two terms you can see 1 plus 3 is actually 2 squared 4 and sum of first three terms one plus three plus five it which is actually three square nine and which is our sum of first four terms which is common coming out to be sixteen let's check it out one plus three four plus five nine seven sixteen yes it is valid so this is this will give us the o of one time approach okay that's why i'm trying to fetch the elements of the error h this sum using uh this formula n square now one thing i need to mention also in case of n is going to be out to be even you can also see when n is going out to be even i can concentrate all the elements to the median what is the median here that is the you can also see the average value of these two five and seven what is the average value of this five and seven eight which should be six so in case of when n is going to be when i need to concentrate all the elements to six that is one plus three plus five should be first concentrated to five and remaining would be like 7 and i need to concentrate it to 6 so just to add these 3 5's by amount equal to 3 so it would be like 6 and correspondingly in one operation these also be these three elements also be decremented by six decremented two six it should be like six okay so this is the basic approach for n equal to odd and for n equal to even so how we are going to calculate this efficiently so i need to mention that also okay so for the simplicity of the code okay so let's head over to the uh analyzing how we are going to approach this problem inefficiently okay so let's find out what should be the if n is going to be odd if n is going to be or let's find out the middle value which is actually 5 so i am going to find what is the first two n by two terms of this one which is coming out to be four okay and but i need the value that i need the value should be like five so what i'm going to do is just find out the middle element and find out the sum that is okay so i'm going to write the required sum would be like five which i need the value should be equal all the elements of the other should be equal to five so i need the required sum as 5 into number of terms that are going to be left of it okay so 5 into you can see there are two terms so i'm going to add 5 into 2 minus what this is the actual okay so this is the required sum and what is the current sum uh you can see my current sum is nothing but n square first two terms which is coming out to be four you can easily see this is coming out to be ten and this is coming out to be four and the difference of this should be our answer because in one operation i can increment some value of the error and correspondingly i am going to decrement this some other value of the array okay so if i'm going to increment 1 to 2 correspondingly 9 will always be decremented to nine to eight okay and in this case also i'm just going to find out first the sum of first three terms which is coming out to be nine square and then i'm going to just to i need to just increment the answers and what is the my required sum would be like 6 which should be the median into number of elements to the left of it which is coming out to be 3 18 okay and i need to find like 6 into 3 is 18 and i need to have subtract today my actual sum that is current sum 16 to 3 is 18 and my nine is my current sum and i need to do nine operations to make all the elements of the r equal okay so let's head over to the code to find out the best implementation that is of one space and 100 percent runtime beats solution to this problem okay so let's move further okay i have already written over the code okay so why not i'm going to just i've already submitted some code okay so let's okay so here is accepted code okay so you can see all the test cases are passed runtime is 0 ms per second and runtime beats is 100 of cpp submissions okay so what basically done is if n is going to be odd find out the number of terms and what is the sum of first and terms you can see current semicolon terms square and the required sum is find which is the median into the number of terms to the left of it okay and my answer if n is always required some minus current sum and what about when n is going to be even find out the number of terms first then current sum which is terms into terms and the value terms that is i'm going to find the median twice of terms minus one if you're going to calculate this it is go it is it will coming out to be same okay note that difference is going to be one difference is going to be adjacent difference will always be two that's why i have incremented one it should be like uh when i'm coming out to at five i need to find the median which is coming out to be six that's why i've done five plus one which is coming out to be six okay and my required sum is value into terms and what should be my answer minimum number of operations required some minus current sum and finally return the answer okay so here also i have the code i can submit that okay you can see faster than 100 of cpp online submission so if you have any doubts let me know in the comment section of the video and i'll ask the viewers to like this video share this video and do subscribe to our youtube channel for latest updates thank you for watching this video
Minimum Operations to Make Array Equal
npv-queries
You have an array `arr` of length `n` where `arr[i] = (2 * i) + 1` for all valid values of `i` (i.e., `0 <= i < n`). In one operation, you can select two indices `x` and `y` where `0 <= x, y < n` and subtract `1` from `arr[x]` and add `1` to `arr[y]` (i.e., perform `arr[x] -=1` and `arr[y] += 1`). The goal is to make all the elements of the array **equal**. It is **guaranteed** that all the elements of the array can be made equal using some operations. Given an integer `n`, the length of the array, return _the minimum number of operations_ needed to make all the elements of arr equal. **Example 1:** **Input:** n = 3 **Output:** 2 **Explanation:** arr = \[1, 3, 5\] First operation choose x = 2 and y = 0, this leads arr to be \[2, 3, 4\] In the second operation choose x = 2 and y = 0 again, thus arr = \[3, 3, 3\]. **Example 2:** **Input:** n = 6 **Output:** 9 **Constraints:** * `1 <= n <= 104`
null
Database
Easy
null
1,372
hello guys welcome to deep codes and in today's video we will discuss lead code question 1372 that says longest exact path in binary trim so here you are given the root of the binary tree and you need to find the longest length of a zigzag path so now what is the zigzag path so let's say you choose any node in a binary tree okay you choose any node in a binary tree and then you move to in any one of the relation either right or left so if you choose right then uh move towards the right shell of the current node otherwise move towards the left chain now for the next time change the direction from right to left or from left to right so if you have taken the right chance then for the next node take the live Channel and vice versa so yeah that's this way you have to travel in a zigzag manner of for a given binary tree and you need to return the maximum length of first exact path that you can travel okay and the maximum length is number of nodes travel in the path minus one so this is the length so let's take a look at the given example for better understanding so guys here if you take a look in this example so One path can be this is also zigzag path but this exact path is of length two so another zigzag path is this and this so this exact path is of line three okay one another's exact path is there from here to here this is of length two right and is there anything possible so yeah these are some of those exact paths that are possible and from that this one starting from this node and ending here so this is the longest of a length ring so yeah guys that's why we written three as our answer got it now if you take a look at the second example uh starting from this node uh One path possible that is already drawn here this is of length four another let's say uh if you start from this node so then this is one path possible yeah correct uh this is also One path possible this is of line two but the longest is only this of length four so yeah guys that's why we written four Sr also and here there is only one node so uh we return 0 is our answer so guys uh I hope you understood that what is this exact path for any given tree like this so guys for any given trade like this what are the different parts that are possible so let me show you one zigzag path possible is see this is one's exact path possible Right This is exact another zigzag path possible is this complete is once exact path right this is one's exact path possible then this is one zigzag path possible of length one right uh this is another the exact part possible so yeah there are difference exact part possible and from that which we will choose this exact path this is our answer right this complete path is our answer so guys here how we will check whether uh whether the given whether the taken path is Sig or not so how we will conclude to a path that is the maximum length so for that we need to Traverse travels all the nodes right all nodes now guys if you see that we will start from any one node and take us exact part towards the bottom so we will start from any one node and move towards the bottom so that is move moving towards bottom so that is what when we move towards the bottom then that travels the technique we use is known as DFS that is depth first search right so we move towards the bottom in a depth manner in a zigzag manner but we are moving towards the bottom so yeah we will use DFS here till here now the another thing here is we have choices right Clear Choice is either to move left or to move right so since we have choices we can write a recursive solution that will cover uh to cover all choices right we can write because the solution to cover all chances so DFS is nothing but recursion only so this is nothing but recursion the only thing in this recursion we have to take care of choices that we will curve all the choices what are the choices is uh to move both left and right from each of the node right so yeah we will Traverse out the nodes since we have to move towards the bottom of the tree we will use DFS and then we have to take care of all the choices keep only these three things in mind and let's go for the solution right the coding part is very much simple it is more than likely the DFS code only that we will write with a slight variation so you know what another thing we have to take care of after this to make sure we travel in zigzag MN error to make sure we travel in zigzag so we have to make sure that we travel in zigzag manner so for that we will keep One Direction uh variable so we will keep detection variable right so with the help of detection variable we will maintain that either we are traveling in zigzag manner or not that will help us to travel in a zigzag manner so that's clear till here this is only uh Four Points these are simple four points that will keep in mind while coding for the solution okay so now let's move on to the coding part right uh let me take this tree again so let's now take a look at here so here this is our given function longest exact that we have to code so from that function I called the solve function or you can say DFS function twice one from for passing the root and passing through so what is true so here I have one variable left Direction so if this is true then we will move in the left Direction and if this is false then we move in the right direction so yeah we'll cover both the test cases moving it towards the left and moving towards the right so yeah that's why I call this all function twice and initial I have this Global variable max line that will store the maximum length and we will return that maximum length at the end now here I am taking three parameters one of the node is a second the left direction or not and third the current path steps or the number of steps taken in the current path okay now uh what is this let me show you so if the left direction is true that means we have to move in the left reduction right if the left for this we have to move in left Direction so for that I what I did is mode of left move towards the left Direction and then passwords right for the zigzag once this we have moved towards left now we have to move towards the right so we have passed force and increment the current path step to one with one now from the same node we can also move towards the right this is one another choice so if your move towards the right then the next step must be left reduction so we pass to n the current path step would work so here we are restarting our path so that's why I passed one okay so let us take a look with this example so let's say here we have having a root we have passed the root node left direction is true and current path step is zero so let's face this let's stress this so here we are moving we will move in the ref deduction right so here from this node we will jump here life detection is two so we move towards the left and then password and current step is one so here after uh coming till here this current step will become one okay zero plus one it is one so now the from this same node we can also move towards the right so since we have moved towards the right we can take we have to take Next Step as a left so we pass this parameters to and then one so here from this direction what we move towards the right and we pass uh as a true n uh the length is one right okay now here we have two nodes in our recursion stack so let's take this node first so from this node since we have taken the left detection next node reaction we have to take is the right so we move towards the right and here our current step value will become 2 and from for this node there is nothing on the left so here it is null so stop so whenever you there is no node or the null we return okay so yeah one is the answer on here now we have only these node in the recursive stack right so from here you move towards the left this value becomes three and also you move towards the right the value becomes 4 okay and after that there is no so we didn't did anything right so guys from here since we are traversing in zigzag direction we move towards the right but there was also one point that we have added that we can restart right we can restart by taking this value as one current step is one so from here we have distorted there is one other option that we have restarted and value from here will become one right that is one traversal and so after reaching this we can also reach this so This value becomes two so that's why see the initial path we can continue but after that for each node we can also restart by taking one New Path right we can just start by taking A New Path so that's why this step here so this is the step for this time and this is one step for restart so that's why we that's how we are restarting the value and we can take the path right this exact path so for that we have added this line to restart the new path from that node so I hope you guys now clear this see once uh if we have to move towards the left reduction so we will continue from the top and move towards the left or move towards the right s by this value also along with that we can restart A New Path from the given node so yeah for that we move towards a new Direction and we restart and same here we move towards some one New Direction and restart our path and yeah before this calculation we have this maximum length where we will store the maximum length comma current path steps so yeah guys the code is very much simple it is nothing but a DFS but with a slight change that every time what we are thinking we are taking the current path that we are following and we are starting a new current path in a new part so uh that's how we will cover all the different choices possible Right and at the end we return the maximum length so yeah guys that's all for this video now talking about the time and space complexity the time complexity here would be uh we go of n plus and N is the number of nodes by two types of n because we are calling this all function twice so yeah twice time of N and the space complexity is also nothing but a recursive stack that we will use so that will be also n plus n in a worst case so you can say n plus n here for the space complexity so yeah guys that's all for this video if you guys have any doubt then do let me know in the comment section make sure you like this video And subscribe to our Channel thank you
Longest ZigZag Path in a Binary Tree
check-if-it-is-a-good-array
You are given the `root` of a binary tree. A ZigZag path for a binary tree is defined as follow: * Choose **any** node in the binary tree and a direction (right or left). * If the current direction is right, move to the right child of the current node; otherwise, move to the left child. * Change the direction from right to left or from left to right. * Repeat the second and third steps until you can't move in the tree. Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return _the longest **ZigZag** path contained in that tree_. **Example 1:** **Input:** root = \[1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1\] **Output:** 3 **Explanation:** Longest ZigZag path in blue nodes (right -> left -> right). **Example 2:** **Input:** root = \[1,1,1,null,1,null,null,1,1,null,1\] **Output:** 4 **Explanation:** Longest ZigZag path in blue nodes (left -> right -> left -> right). **Example 3:** **Input:** root = \[1\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 5 * 104]`. * `1 <= Node.val <= 100`
Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.
Array,Math,Number Theory
Hard
null
49
hello welcome to my channel today we have leeco 49 group anagrams so given an array of string strings group the anagram together so you can return the answer in any order so an anagram is a word or phrase formed by rearranging a letter of the different words and phrase typically using all the original letter exact one exactly once to um first what's the anagram enneagram in here you can take a look at this example so um they have the same character and then they're just in different order so this can be formed using the same letters so that's called enneagram and can we can group any enneagram in a group so this is another enneagram they add both enneagram and this is individual one so the group in the group can output it that's the answer so in this solution we can use the hashmap that the individual anagram and then put it into the list so like uh we have a map right here and this is the anagram and here's a list of all this how do we know it's anagram so take this example you know if we sort this uh string after sorting will be a e t in the order what we can do is sort this uh string and put it into the key which is aet so it's anything like if this one is an anagram so after sorting this string will come up to become also become aet you can see a and e and t so the sorting string will be the same put that as a key and create an empty list so if you see uh any anyone have the same key put in here and then we'll come up a string i mean come up with a ray like this until we capture all the individual key in here we'll have another uh keys here's another key so now we capture everything and later we output based on the key then that's it for this solution so now we start looking look at the code now first we have a edge case to consider so string it cannot be no or string.trn cannot be zero so if that's the case we turn new arraylist something like that so edge case done so next thing is the creator output right here list of list outputs equal to new arraylist so after creating that one uh we also need a map that have the string and the list of string sorry um now we can look through every word inside the strings now first thing we need to do is rearrange the string we bring the string into the original order so make a character array um current equal to string dot 2 character array and then we use arrays.sort and then we use arrays.sort and then we use arrays.sort to sort that array then we'll have all the character in order and we build that string by sort string equal to string dot value of this current array so now every this three step will rearrange s into a sorted string so now we have sorted string we come to the map and check if map dot contain key sorted string so if it doesn't contain we create a list right there map dot put sort string put store string and give them a new arraylist string so now we definitely have a list for this source string so we can do map dot get to get that list right now source string and after we get that list and we add the s which is the current string in the strings input we put that into the map to capture every individual string inside the source string so now the source string will contain all the anagram in here after this for loop and we can output so output equal to new array list that contain all the value uh i think it's values because the order doesn't matter so it should be good and we turn output as a result so let's take a look uh misspell t h yeah they're in different order but it's okay so now we submitted cool and a bit 81 sounds good this is an easy solution if you have any question please comment below and please feel free to give me a feedback if you like i would love to hear that uh until we meet next time so see you next time bye
Group Anagrams
group-anagrams
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** strs = \["eat","tea","tan","ate","nat","bat"\] **Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\] **Example 2:** **Input:** strs = \[""\] **Output:** \[\[""\]\] **Example 3:** **Input:** strs = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strs.length <= 104` * `0 <= strs[i].length <= 100` * `strs[i]` consists of lowercase English letters.
null
Hash Table,String,Sorting
Medium
242,249
1,071
hello everyone so today we are here to see lead code DPP first question which is uh greatest common divisor offering the let's see what the question is saying basically photo string snd we say t divides s or it's Sim like that like 40 by 2 uh if and only if s equal to this concatenation of T's and given to string uh string one and string two return the largest string X such that X divide both string 1 and 2. so like first of all let me uh clear you like I hope like this question is clear to you but let me explain this so what it is like uh the question meaning wait yeah so yeah the question is basically saying you have to find a string X which divide string uh string one and two which means let's say here is example a b c and ABC so you need to find a string x which divide both which means that let's say x is our ABC fine so it will be ABC if you do means if you plus 2 times ABC plus ABC this will become this and if you do at only once so this will become this so like uh the length of this is 6 and the length of each X is 3 so 6 divided by 3 is possible so that is the reason it is possible and the length of this 3 so 3 divided by 3 1 so like that elements I hope that like this question is clear to you and if not like let me explain again uh another one which is a b and another one is a b fine so in this you can observe that if you put directly a b into this so it will not become because the length of this is 6 and 6 divided by 4 is not possible fine so basically if we take X as a b x as a b so a B plus a b will become this and AV plus a b will become this fine so 6 divided by 2 equal to 3 and 6 divided by uh like 2 will become 3 so I hope like this question is clear to you and fine so yeah let's clear this so uh I hope that this question is clear let's Let Me Wait a second okay yeah I hope I think some problem is here with this okay yeah now it's clear so let's move uh to the implementation and the logic part and observation and like that thing so first of all think that in any question you need to observe something so what is my mindset when I read this question so the first thing which I got it here is the time complexity the first thing is time complexity so the complexity for like here is thousand so like string length is Max to Max goes 2000 so the answer like the time complexity would could go till o n Square fine because in one second 10 is to power it will go so it will be 10 raised to power 3 into 10 raise to power 3 10 raised to power 6 it can go highest so we can use our Brute Force approach or we can say O N squared approach the question become very easy observation is clear second part is logic so logic will be very easy like if you see that the string whose length is minimum this we will only take the string whose length is minimum and we can say that the RX will be something substring of the minimum length string fine because if it is a b c and a b so it is obvious uh not like ABC Fine like this so it is obvious the means the string whose length is minimum from that substring only uh we can take X then only it will divide uh both of them fine so if I say that substrings and the another thing is that we can use a Brute Force approach so the question becomes very easy like what we can do in each Loop means we can use a loop in which we will take first this a then a b then ABC we will try all type of X possible fine we will try all type of x a b a c of that minimum length string and after that we will test both of them like if we take a so what we will see that alenth is first so we will see that uh six divided by 1 yes it is and 6 divided by 3 yes it is 3 divided by 1 yes it is then what we will do that 6 divided by 1 equal to 6 3 divided by 1 equal to 3 so our X if we take 1 so uh we will means like at six times so it will become a till 6 and it will become a and after that what we can see we will do we will check that this string is equal to string 1 and string two if it is then only we will store in some string s and the thing is that at the end the r string will be the maximum because like we will go till uh till the length of three fine like the length of maximum of that minimum one so like that I hope like this logic is clear is it will become very easy if you can take all type of X because it will be shorted that the substring of the lowest length string so this is what about the logic and if you move to the implementation but it is too easy because as I told so uh let's see that logic part I already did to save the time so basically this is the string which I said uh like the answer string and this what I can I'm doing that like I am just swapping like because I want the string one is always be maximum length one fine this I did and the length of both after that what I am doing I am using the Brute Force approach string two because it is the minimum and here is our X or here I said a which is like uh go means I take in the substring that first a then a b then ABC like that because 0 comma I means the from starting to till the length wait a second yeah so till the length n and here is rx and after that I am seeing that length is like divisible of N and M if both it is divisible then what I am taking this I am making a string of their length because n by I means total like if 6 divided by 3 equal to 2 then we need to add both like if x is a b and the length of that string is 6 so 6 divided by 2 equal to 3 so a B plus a b like that I am doing so I am doing like that which I explained and after that I am comparing that string Like This Ss and SK is equal to string 1 and string two then only it is divisible and if it is so put the answer in s equal to a and it will be the maximum length only because we are going from 1 to this like length so I hope the question is clear to you and like I submitted this uh previously it got accepted and uh like this wrong question because like I forget that we also need to check with that string too means it is also divisible with it so like that this question is pretty much easier so hope thank you very much
Greatest Common Divisor of Strings
binary-prefix-divisible-by-5
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times). Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`. **Example 1:** **Input:** str1 = "ABCABC ", str2 = "ABC " **Output:** "ABC " **Example 2:** **Input:** str1 = "ABABAB ", str2 = "ABAB " **Output:** "AB " **Example 3:** **Input:** str1 = "LEET ", str2 = "CODE " **Output:** " " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of English uppercase letters.
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
Array
Easy
null
1,742
hello everyone so in this video let us talk about the easy problem from lead code the problem name is maximum number of balls in a box so the problem statement goes like this that you are working in a ball Factory where you have N Balls numbered from the lower limit to the higher limit inclusive so what you can see is that you have N Balls numbered from the lower limit to the higher limit now your job at this Factory is to put each ball in a box such that the box with the number equal to the sum of the digits of that particular ball so whatever ball you have to do the summation of all the digits of that particular ball number and whatever digit you will get eventually uh you will take that particular total sum whatever total sum you got and put the particular ball in that box which has a total sum so you have an infinite number of boxes okay there are a lot of boxes now your total problem boils down to that you have a lower limit and upper limit of what is the N Balls you have you just have to assign every ball to a box and then you have to return a number of box the number of balls in the box with the most ball so whatever is the most amount of balls in the same box you have to return a number of maximum number of balls in any box possible okay that's the whole problem statement let's take a small example let's take that you have n numbers okay n number says that you have the lower limit as one and high limit as 10 which means that you have balls from 1 till 10 and you have to take every ball one by one from one till ten let's one two three and do the summation of all the digits in that total number so this is the ball number okay this is the ball number now let's say the first ball has the only digit of one which is one now you take that particular ball and put it inside box with label as one so you have a lot of boxes as well and you will keep on doing that until you have finally the frequency of every box like how many balls they are stored and you just have to find the maximum of them now do you have infinite number of boxes but what is the maximum value you will be getting okay as you can see that it is and you have five which means that like what you can observe is that I can get at Max like uh numbers which has let's say like five nights let's assume so nine five forty five so which means that maximum to maximum you can get uh you can say if you just add all the nines okay you can get a ball you can get a box with all the nines and thus you can get a maximum Alexa modified just take a buffer Also let's check 56 in normal so which means that in the worst case scenario also whatever ball you will get the total sum of digits of that particular ball will not be more than 60. so what you can do in this problem is just make a vector of array or sorry an array object you can say an array in which you will take the size of the array as 60. now these are continuous boxes which you can assume that these are boxes itself now for every wall from the lower to the higher limit find out the sum of the digits and then whatever the sum you got take that particular Poland assign to the particular box and then finally just find out the maximum value of balls in any vertical box and just printed out pretty much simple that's over Logic for this particle problem let us move on to the code password through it make it more clear what is you can observe here is that we have an array or you can sub Vector of box which is of Atmos 60. now what you can do is that you will just do a for loop from the lower limit to the higher limit okay now taking every ball into consideration now for every I find out that is the ball you can say digit of ball number now find out the sum of the digits of that particular ball number you will call this function that is digit sum we have some sending out this I and whatever digit sum you got you will take that particular delete sum and foreign you have this array okay all you can say Vector in that take that and particularly assign that particular ball to that particular box okay and increment the account that I have taken this particular ball which has the total date sum as let's say any number and then corresponding to that box just increment number so that I put that ball in that bottle box now I have all the balls assigned to a particular box now in the end you just hit it over all the boxes one by one and just find out the box which has a maximum number of balls too simple pretty much just return on the number of balls in the maximum case possible now this function is just used to find the sum of digits of the number that you have so just iterate over every number for every digit what you can say so you will just take the digit that you actually just take the number let's say 257. so you just take the last digit out 257 to 7 digit will take out add it in total and then divide the number by 10. so now today it becomes 2 7. so this is just a simple function to take out every digit 11 from the number you have and add it in total so that in the end you have the total that is the summation of all the digits in a partial number pretty much simple function as well which is used to find out that and this is the whole overall code to find out the sum and find other actual boxes which has maximum report now the total capital city for this particular problem is that you are doing a for Loop here which is O of n this is not very large you can say depending on the problem it is O of N and then for every o of end you will find out the sum of a digits okay of that particular number you have which is like a very small which is like constant time only you can say okay because it's uh Maxi negative five so five units so almost constant time so this is constant only so this is our volume and then again you are doing a follow-up so total again you are doing a follow-up so total again you are doing a follow-up so total is O of n Only so that's over a second for this particular problem as well and that's it that's the logic and the good part for this particular problem if you still have any doubts you can mention in the guide box or this particular problem I will see you in an flee coding and bye
Maximum Number of Balls in a Box
widest-vertical-area-between-two-points-containing-no-points
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number `321` will be put in the box number `3 + 2 + 1 = 6` and the ball number `10` will be put in the box number `1 + 0 = 1`. Given two integers `lowLimit` and `highLimit`, return _the number of balls in the box with the most balls._ **Example 1:** **Input:** lowLimit = 1, highLimit = 10 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls. **Example 2:** **Input:** lowLimit = 5, highLimit = 15 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each. **Example 3:** **Input:** lowLimit = 19, highLimit = 28 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls. **Constraints:** * `1 <= lowLimit <= highLimit <= 105`
Try sorting the points Think is the y-axis of a point relevant
Array,Sorting
Medium
null
1,671
hey what's up guys this is juan here so let's take a look at number 1671 minimum number of removals to make mountain array so this is the last problem of this week's bi-weekly contest i think this is a bi-weekly contest i think this is a bi-weekly contest i think this is a pretty cool problem you know basically you know you guys know like the uh how this array will call it a mountain array right basically we need to have like a strictly increasing and then strictly decreasing right with a piece of peak somewhere but so for this problem it asks you does you what's the minimum number of elements to remove so that you can make this nums a mountain array so for example the first one right we have one three and one it's already a mountain array so which means we don't need to return it we remove anything that's why we have zero and for example two here right we have two one five six two three one so one of the solutions is to remove this one and then the uh and then this one so that we have one five six and three what basically that's going to be our answer right so that's why we knew we removed three numbers and yes but how can we find the minimum number right to remove if you think about this right i mean we have to think it in a in the different way basically you know so the way it works is like the uh we're assuming right basically we're picking each of the we're basically we're trying each of the uh the numbers as the mountain and then we will see how many basically how many uh how many numbers on its left which is increasing and how many numbers on the right which is decreasing and if you think it that way i mean basically we are having like this x ax x right and then let's see this is the current the peak we're assuming right so at this point we want to know how many numbers on his left which is smaller than p right it's not smaller than p which is like uh like increasing until p and how many numbers on the right side which is uh decreasing until p right i'm sorry it's also increasing until p so now the problems uh becomes what so our ass right basically the longest increasing subsequence on each side so once we figure that out you know all we need to do is just that we just have to precalculate it the longest increasing subsequence from at each of the location for both uh for both from the left side and from the right side and then after we have after com precomputing that's the longest subsequence for both sides we can try each of the peak and then we can just use that value and then we just get the maximum out of it right among all of them and then the answer will be the total number the total and minus the max of those two of the sum of those two right so i mean in terms of the uh the implement implementations i'm gonna just use like helper functions called ios to help me pre-calculate that you know to help me pre-calculate that you know to help me pre-calculate that you know and so the uh the main logic is like this we have in that and here you know it will return a dp right so the dp will just hold at each of the location what's the longest what's the ls okay and then here we have a length of the knobs here right and then we have a dp and left how about this and then we have ios nums right and then we have dp right i asked what since we're getting the increasing so from the right side i need to reverse this array here right then i have the answer equals to zero actually this is the max right max equals to zero and then here in the end we have a four in range what in range the in range from range n right and we try each of the uh so we just need to try from we don't have to try and all we need to try is from n to a 1 to n one to m minus two right because let's say for example here you know the possible peak is only from here to here right so we don't need to worry about the first one the last one that's why we just need to try this within this range and then we also need to verify this one if the dp left i is greater than one right so it means that you know if it is if it's equal to one then it means that it's there's no decreasing sequence on the left side same thing for the right side right so but for the dp for the right side here you know seems you know since i'm reversing this one basically you know i have to do it from the end basically n minus i minus one right so that's how i uh do it from the right side or you can reverse it here so that you can use the uh the in the same index for the for both left and right but i didn't reverse it here that's why i have to do it in this way and then i have answer equals to max of right so the answer dot dp basically this is two things right plus that and then i have to do a minus one right so why need to do a minus one because for example this one you know we have a one because it's pretty straightforward because we are counting the peak twice in this case right that's why we have to uh remove one addition one extra peak from the total length here and in the end i simply return the n minus actually so this is not the answer it's max that right that's the uh the main logic and now always labs it's just to implement this ios right so i mean a normal way to implement this our uh this is it's by doing like what the dp right so by doing like a nested for loop which is the dp equals to one and then we have a for loop with i in range of 1 to n right for j in range of i and then if the array dot j right is smaller than array.i j right is smaller than array.i j right is smaller than array.i right if this uh if this inner loop is the j is smaller than it then we know okay we can that's a valid entry point right basically it's possible that we can get to the current state dpi from that dpg from the dpj because this die is greater than j so we can simply update the dpi in the range of max dp i and dot dp j plus one right so and after this about necessary for loop we'll have this dp that can give us all the uh the i mean the longest the rs for each of the location right so yeah i think that's it let me try to run the code answer okay sorry here it okay so it's accepted right and so how about time complexity for this right i mean obviously we have a of n squared here that's the uh that's the regular solutions for our s which is an o n square and here just o n right that's why the total time complexity for the first solution is o n square and space complexity of course is often right space cool so i mean i think some of you might have might know a better solution for calculating ios which is the binary search in that case the uh the time complexity for this one will become to unlock n right so for that one basically we're using like a dp we're still using a dp to store the uh the actually the sequence and the final answer the uh the answer for that will be the length of the dp in the end but since but for this problem we are not only looking for the uh the final answer for the entire array but instead we are we're trying to find we need the uh the rs for each of the index so that we have to do a little bit of the mod the change here you know and so to do that you know i'm gonna here you know so the dp is still a dp here but instead the dp will be our final returns here but i'm going to use like sequence right to help us to keep track of each of the numbers here so basically now the number equals to array here and then we have index right the index will be the bisect we do a binary search by bisect left we search this number inside the sequence here right and then if the index is smaller than the length of the sequence right then we simply update index right we update the numbers and then else what else we append right because ours i mean it means that you know the current index the card number is greater than all the previous numbers then we can we know okay we need to increase the ios by uh by append right by append this number to the sequence and then here i just do a dp dot append right the current length of the sequence basically and this is going to be our the ios for the current index you know previously if we don't need to re the result for each of the numbers here we do actually we all we need is this one sequence right and in the end we simply return the length of the sequence and that will be our the answer the ios for this array here right so for this part i mean maybe i'll try to explain a little bit here so for those who are still don't quite understand this i mean this part so the way it works is like this let's say we have a 2 1 3 4 6 3 8 so let's say if we have this sequence so the way it works is like this so the first time let's only take a look at sequence here right we have the in the sequence we have two here right so the sequence we have two and so now one comes in right so when one comes in here so the index will be what will index will be zero because it's trying to insert to the left side and we see okay zero is smaller than one which means that we're going to update this to up this two with i mean this one that's why we have one here but keep in mind see notice that the length is still one which means that at this index the ios is one but here is also one right it's obvious right because this one is smaller than this one and now we have three here so three when we do a binary search with three here we'll have one which means that we need we'll do a append that's why we have three here and that's why for three the hours is two and same thing for four right so we're gonna do a four and then we do what we do six here now we have three here so three we will have like um uh how about let's do five here i think five is better so let's say if we have five here you know five is what five is uh it will be inserted right here right that's why the uh that's why this one will be updated to i mean if it's five but still as you guys can see so for this one the ios is still four the length of that and then in the end we have eight which is five right so that's how we use the binary search to keep track of this ios okay so yeah and i think this yeah this is finished let's try to run the code here okay accept it and then submit yeah and as you guys can see this one is much faster because now the time complexity for this one here has become unlocked right so the total time complexity is unlogging and all right cool guys i think that's pretty much it is actually this one is pretty it's a very tricky problem you know the uh i was trying to solve this one by using a greedy you know but it turns out there's no greedy solution for this one and then i try to use dp but you know the way the dp works is that you know i was trying basically i was thinking about can i use a simple dpi here to track off the uh basically track the uh with current i what's going to be the maximum sorry the minimum numbers i want to remove to make it 0 to i minus one uh function basically i was trying to use the definition of the problem but turns out that's not feasible either because we have like increasing and then we have a decreasing there's no way this d this one single dp can define that those two uh status and we there's no way we can track that so i think that's why you know in the end so we have to basically utilize this lls approach and then with this pre-calculated ios pre-calculated ios pre-calculated ios we just try each of the locations each after the each of the peak and then it's more like it's similar like a sliding window you know but it i think it's different but with each of the peak we can certainly we can easily get the uh our final answer right yeah so actually you know the more i think about it you know the uh i think this approach comes from a brutal force right basically the brutal force is like we try each of the elements from this from one to a minus two as a peak right and then we'll we given like a peak we'll try to see uh like the basically how many numbers i have element on the left side can be a d under decreasing sequence and how many numbers on the right side is also can be also decreasing sequence and then we're trying what the next step will be how can we improve the time complexity basically it's just a precalculation by using our ios right cool i think that's it for this problem and thank you so much for you guys to watch this video and stay tuned see you guys soon bye
Minimum Number of Removals to Make Mountain Array
the-most-recent-three-orders
You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some index `i` (**0-indexed**) with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given an integer array `nums`​​​, return _the **minimum** number of elements to remove to make_ `nums_​​​_` _a **mountain array**._ **Example 1:** **Input:** nums = \[1,3,1\] **Output:** 0 **Explanation:** The array itself is a mountain array so we do not need to remove any elements. **Example 2:** **Input:** nums = \[2,1,1,5,6,2,3,1\] **Output:** 3 **Explanation:** One solution is to remove the elements at indices 0, 1, and 5, making the array nums = \[1,5,6,3,1\]. **Constraints:** * `3 <= nums.length <= 1000` * `1 <= nums[i] <= 109` * It is guaranteed that you can make a mountain array out of `nums`.
null
Database
Medium
1688
394
hi everyone how are you doing uh sorry for haven't been posting for a couple of days I was actually in Toronto for a business trip and I was kind of occupied through work but now I'm back and we're gonna go to solve another problem in decode this problem that's actually kind of cool it's called decode string it's one of the more popular ones being asked in Google so I thought it would be appropriate to do it here and it's fun because this reminds me of my childhood where I'm not sure about you but sometimes when you when your child I guess in this day of air we don't do this anymore but when I was a kid we were writing notes but we also don't want teachers to catch what we've wrote so we would develop some sort of way to encode it and as long as give the as long as I give the password to someone or not password but the decoding methodology to someone else then they could actually take the note I pass to them and decode it and get the message for me that was the old way of doing things but now Pippi probably just do it through text or whatnot but anyways I do best I must get back into this question so this question is called decode string so I'll tell you simple you're given an encoded string and you Rico and you return its decoded string great like any decoding mechanism you just need to know the rules right so let's look at the rules the encoding rule is the following K an Open bracket encoded string close bracket where the encoded string inside the square bracket is being repeated exactly K times okay simple enough note that K is guaranteed to be a positive integer okay this is a key point remember what I mentioned positive integer right and you may assume that the input string is always valid no extra white spaces no brackets were what square brackets are well-formed what this pretty much means well-formed what this pretty much means well-formed what this pretty much means is that you're not to consider all those edge cases right you're gonna get some good perfect string that's gonna be sent to you not something like things that's not well-formed right cool things that's not well-formed right cool things that's not well-formed right cool furthermore you may assume that the original data does not contain any digits and that digits are only for those repeated numbers this is a very critical information right so what does that mean it means that you'll never see a repeat you could actually if you see enough character that equals to a number that means it's always going to be representing how many times repeat the things within the square brackets right so meaning that things in the square brackets inside there won't have any numbers and that's very critical because that's can be used as one of our key rules and solving this problem okay so let's look at some quick examples these are relatively self-explanatory these are relatively self-explanatory these are relatively self-explanatory you know three you're gonna repeat what's inside the bracket three times so therefore it's gonna be a and then you're gonna look at two and can repeat that twice so skimpy CPC simple enough right same thing here you have three and they're gonna repeat everything inside here basically three times right but however you need to note that okay remember what they said that a number actually means what you're gonna be repeating so if we look at the character cool you're gonna repeat a but then make sure that you have this subsection which is gonna be CC because you're repeating this to CC twice so it's gonna be a CCA you see ACC right self-explanatory very you see ACC right self-explanatory very you see ACC right self-explanatory very simple so let's actually jump into the actual coding question so before we start I want to write some P notes right so we know K is basically how many times we repeat stuff right the Open bracket is basically telling us okay well now I need to start look storing what I want to repeat and then we look at the closed bracket which is pretty much saying like okay well when I get to that character I just better start repeating betters are repeating great now let's actually create the question which is I'd like to use es6 so it's gonna be decode string which is gonna be equals to of a string that they pass in here great so before looking into this question right we got a step back and think what are they trying to ask us right how can we solve this we know that okay and the first hand we need to look at every single character right so therefore because every carry every character tells us something right of what to do so we know there's gonna be some sort of iteration on it so it's gonna be definitely o of n of something right it could be n of squared quadratic whatever may be but end of something right the next thing that the thing about okay how can we solve this now for this case on the second part if you think about it's almost like these are almost as you're solving the same problem but just over and over a time right there same problem was like as long as you give me a number and tell me what to repeat just repeat it right and then take give me a number give me what to repeat it right it's almost very recursive in nature and I believe if we wanted to we could actually solve this question you know recursive way right but with the stick staying back a little bit using recursion although it's kind of cool and fun and it's very important concept it's actually very expensive in time complexity perspective right because it's basically you know the more branches you have the bigger the characters you have to decrypt it's gonna take a long a lot longer time to solve right so using you know using recursion may not be the most optimal solution so let's think of another way to solve this problem so what we need to know is like okay we need to make sure that we iterate through all the characters right and then do something with it right we need to know what we're repeating right or how many times were repeating things and what are we repeating right so maybe something we could start off is just you know maybe we'll store that somewhere right as I write maybe I'll store that information and then do things as I approach to these different steps right so one of the things I'll probably start creating is like okay let's create some sort of way like multiplier multiply so these will tell me like rules of what I'm gonna be multiplying right and then I'm gonna go saying what's my what's the substring so or repeat string what am i repeating right just keep a stack of it right let's just say like okay cool I know the rule is like I'm gonna repeat something say three times but like we repeat a three times but I'm not finished iterating through the edge character right so let's just keep those in memory so at the end we can just like remove the stacks and actually start constructing our solution right so let's go back into here we could multiply things but okay cool so one of the things I remember we talked about we need to you know we'll take this example that's a case right that's the example we're looking at what do we need to do right we need to iterate through each of these elements and do something with it right let's actually I'm gonna change this up we're gonna use the more fun example because this is more complicated this is a little bit too easy to solve okay cool so what I'm gonna do is make sure I iterate through all this whole thing so I'm gonna go for let the character of s being this particular string I want to look at every character and decide to do something with it right well remember the three rules I mentioned above here maybe may be a good start would be okay let's create some conditions to do something for each of these rules right so let's look at okay well let's check if the character is a number right so if for those who don't know is NaN basically checks whether a string value is can be interpret as a number if it is if it can be it will return like a zero so therefore having a this bang method asn't like okay but to zero that I'm gonna make sure that you know it's fall see ya there make you convert it back and so it'll become true so what I'm going to do right if I know that okay I'm looking at this first character cool it's gonna do something maybe in my next condition will be like else if my character equals to this open bracket I'm gonna do something again right else if my character is equal to this close bracket I'm gonna do more stuff right and then the final condition will be well what if it's not a number it's not this open bracket it's not this close bracket but it's just something like an A for example what do we well what do we do with that right we'll have to do something here I'm not gonna fill it in yet and let's make sure that okay well what are we let's not forget what are we actually doing this what are we returning right so we're returning a string so let's just dedicate that as a solution right I'm gonna create a solution right that's what we returning so just make sure that we returned that right away so we don't forget one of the things that I remember some folks going into interviews or when I'm interviewing them is the they forget to actually return the final response it's kind of because you're so nerve-racking in the interview you kind nerve-racking in the interview you kind nerve-racking in the interview you kind of forget about it but what I like to do is like generally structure things in a high level purport peel the meat in and make sure I return what I need to return which is the solution great alright so let's look at this example what can we do so we're gonna check if this first character because we're gonna go check the first character it's three so what we do we check if it's a number great it is a number but what do we do if it's like 31 right with this is a number this is also a valid number so we just make sure I'm we're constructing a full number before we start storing it into our multiplier right so one thing or one little trick I like to do is actually I'm gonna create a temporary thing temp multiplier multi it's good enough ten mult will just be a string and I'm gonna use some really nice magic it's called template literals and then construct these elements because as we iterate what are we really doing right we're just basically taking this character and putting it in here and then to make sure why we enter the second character make sure it's at the end right so what we can actually do here it's gonna go temp mult well equal to this BAM we're gonna kick put the temp mult in here right and also include the actual character right in the question okay cool so what does this do it's like when we look at three it's gonna go here it's a character great your first solution is gonna be like okay well this is gonna be a three right there's an Open bracket no is it a closed bracket no so we already went to this condition so it won't even go to the else statement right so it's gonna go okay cool that looks like love look at one what is gonna do okay well one is a character let's actually make sure our multi in this case was gonna be three and we're gonna plus the character which is the one here so this particular one would be 31 right great now let's iterate to the next character which is this open bracket so once we are in the open bracket what do we want to do so when we open bracket we remember what you're set up here now we need to start storing what we want to repeat right if we take a statement you can think of okay well what do we need to store to know what we're gonna repeat well we're gonna know like whatever how many times were repeating things and what are we repeating right so let's actually go over here and look at okay my multiplier and I multiply dot push I'm gonna push the temp mult in here right and make sure that I reset it mult to be it's already stored so I don't I need to make sure I we said it so it doesn't like increase in to 321 then that's a bad idea so this pretty much stores me like okay now I know I need to repeat something you know 31 times which in this case would be 3 but not 3 1 but in our case will be 31 so in this array it looks like this 31 right now right and the next thing we need to do is make sure that our EP string we're gonna actually start storing stuff into it right so repeat string dot push what are we repeat ago would put repeat the solution and make sure the solution I'm reciting it over here back to that great so whoops so when we look at this we hit into this particular bracket what are we doing right well we're just saying like okay are we repeating anything no so in this case we're gonna actually put in here it's gonna be an empty right because we already said that okay well solutions give me an empty if I don't store anything so we don't have anything fall in this bracket but you know we're in here so in here we know that okay let's store the multiplier we're gonna multiply something by 31 times we don't have a net thing yet so let's put it here that's fine and that's cool so let's them to go next condition okay well we know that we had to go into a right is it a number no is it an Open bracket no is it a closed bracket no but we need to do something with it right so now because we are within the brackets in here we should probably start constructing a substring of sort right that is to be repeated so I'm just gonna reuse this thing called the solution because it's a good way to keep back our substring so solution will basically be equal to the character right it's gonna equal to its existing solution plus character in this case our solution was the empty string plus the a right now which is going to basically effectively be a that's what's gonna happen we go into a right now remember this thing over here we our spring actually is gonna be that right now because we're assetid it cool so work up to now okay well what is - so work up to now okay well what is - so work up to now okay well what is - we're gonna go in here it's a - great we're gonna go in here it's a - great we're gonna go in here it's a - great construct - great move on now we're construct - great move on now we're construct - great move on now we're gonna open bracket again okay well what's that gonna do we're gonna go in here put the two in here we're gonna kill off the to reset it and we're gonna start pushing the solution which we have over here being a and I'm gonna kill out the solution again boom so this is gonna be empty right so I'm here into this float rocket now the next thing is gonna put the see what's gonna happen with the sea we're gonna dump it in here alright because we're gonna look at ok well the solution see great it doesn't fall any of these conditions it's gonna put here great so let's move on the next okay now this is our first four close bracket right what are we doing in this close bracket remember I said the rule up here saying closed bracket is basically when we start repeating stuff right so let's write some logic to that now what I want to do is pretty much go listen solution I'm gonna plus well equal to something right what's that something so let's actually look at what we know what we need to know okay so we need to know that okay we're gonna be repeating all this stuff certain amount of times right so let's actually look at that so we know that okay well I'm gonna go and look at my repeated string right repeat it repeat oops spell repeat string dot pop right so I'm basically taking that and putting the a in here so in this case will be like a great but I'm not done right because I need to make sure it's gonna be a CC so how are you gonna get the CC that's we remember over here and are all the things that we start C's right here right so we can actually just go plus the existing solution type but repeat and how many times we're repeating that CC right we're looking here well this tells us multiplier so multiply to fly dot pop so obtained in the last element and I'm gonna go okay cool I'm gonna repeat this C twice so that's gonna be CC great my solution is give me a CC so here theoretically it could be a c that's my solution right are we done not quite done yet right so next part is like well since we already popped these two elements are existing rate has this right now we're entering our second component here which is like okay well that's great I repeated what's in here once now but I need to repeat this 31 times right in order to do that we have to make sure going back in here well it's a closed bracket what's gonna happen right in this case is gonna be what's our repeater what are we popping right we're popping an empty thing so this is gonna basically be something empty right and we're plussing basically the solution which in our case is a CC 31 times right so that means like this would solve this problem and I think we have our solution so let's run and check it out of course I'm not gonna it's not gonna 31 times in our test case right here I'll just delete that and the test case here you know you should have this solution so let's try running it run the code right let's try putting some more advanced things like this boom put the test case in here for those who don't know you can actually put your own custom test case run was chugging along must be a lot of people using it great cool I got the right solution now the big drum roll is to see if this actually is good enough to solve the problem submit and great we beat 88% of most submit and great we beat 88% of most submit and great we beat 88% of most folks so this problem was kind of fun I know I've had it solved a couple times I try to you know I got stuck in one of those engineer mentalities which is trying to optimize as much as possible so I could prepare for you guys but pretty much this a fun problem making sure how to teaching you how to break things into steps I hope you learn something here I'm gonna continue to do some of these questions throughout the week as well please let me know some feedback if you like this way of doing these the solving or would you like to see a white boarding solution I could do either/or boarding solution I could do either/or boarding solution I could do either/or but hope you enjoy the show if you liked it please hit that sub and ring the bell thanks bye
Decode String
decode-string
Given an encoded string, return its decoded string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`. The test cases are generated so that the length of the output will never exceed `105`. **Example 1:** **Input:** s = "3\[a\]2\[bc\] " **Output:** "aaabcbc " **Example 2:** **Input:** s = "3\[a2\[c\]\] " **Output:** "accaccacc " **Example 3:** **Input:** s = "2\[abc\]3\[cd\]ef " **Output:** "abcabccdcdcdef " **Constraints:** * `1 <= s.length <= 30` * `s` consists of lowercase English letters, digits, and square brackets `'[]'`. * `s` is guaranteed to be **a valid** input. * All the integers in `s` are in the range `[1, 300]`.
null
String,Stack,Recursion
Medium
471,726,1076
1,656
all right so let's talk about design and all the strings so in this question you are giving the key and value in the insert function and then you have to return the bits of string for where your pointer point at to the id key so basically that is you have your id key but so you have a pointer to zero right and then when you traverse the entire array then you traverse this pointer with the iv key and if a pointer is actually less than the id key then you traverse to the left to ib key position then you return something and if not then you just return all right so this is this question but it's stupid so i also need a array uh screen array to keep track of the value inside the string right for the string array follow the string add the new string how many space doesn't escape right i need to create a different string inside the insert using arraylist and i need to uh insert into the string right in this situation idt is starting from in this one so you have to supervise you uh second by one so you get an index zero with a value and i also need to traverse the entire um entire screen array with the id key and the pointer point director is making sure the point is a bit less than uh single length you know so and also the string inside good to know since the pointer is like for the pointer is basically like just keep moving and you want to go back to the beginning position so you will have to increment your point every single time and then at least i'll add what do you add at a point in the strings so this question is pretty much because i read over that i couple times and still don't get it so i just go to the discussion to see what or what other people say and this is the solution so this is super easy to prove super hard to understand but let's talk about time and time in space for space is uh is all about right you have an array so it is all of them and represent the number of uh space inside the array and the time be honest is all open right every single time you travel with the array is when you're using a volume you may use follow doesn't matter but it's the same and it's a solution and i'll see you next time bye
Design an Ordered Stream
count-good-triplets
There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`. Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each insertion. The concatenation of all the **chunks** should result in a list of the sorted values. Implement the `OrderedStream` class: * `OrderedStream(int n)` Constructs the stream to take `n` values. * `String[] insert(int idKey, String value)` Inserts the pair `(idKey, value)` into the stream, then returns the **largest possible chunk** of currently inserted values that appear next in the order. **Example:** **Input** \[ "OrderedStream ", "insert ", "insert ", "insert ", "insert ", "insert "\] \[\[5\], \[3, "ccccc "\], \[1, "aaaaa "\], \[2, "bbbbb "\], \[5, "eeeee "\], \[4, "ddddd "\]\] **Output** \[null, \[\], \[ "aaaaa "\], \[ "bbbbb ", "ccccc "\], \[\], \[ "ddddd ", "eeeee "\]\] **Explanation** // Note that the values ordered by ID is \[ "aaaaa ", "bbbbb ", "ccccc ", "ddddd ", "eeeee "\]. OrderedStream os = new OrderedStream(5); os.insert(3, "ccccc "); // Inserts (3, "ccccc "), returns \[\]. os.insert(1, "aaaaa "); // Inserts (1, "aaaaa "), returns \[ "aaaaa "\]. os.insert(2, "bbbbb "); // Inserts (2, "bbbbb "), returns \[ "bbbbb ", "ccccc "\]. os.insert(5, "eeeee "); // Inserts (5, "eeeee "), returns \[\]. os.insert(4, "ddddd "); // Inserts (4, "ddddd "), returns \[ "ddddd ", "eeeee "\]. // Concatentating all the chunks returned: // \[\] + \[ "aaaaa "\] + \[ "bbbbb ", "ccccc "\] + \[\] + \[ "ddddd ", "eeeee "\] = \[ "aaaaa ", "bbbbb ", "ccccc ", "ddddd ", "eeeee "\] // The resulting order is the same as the order above. **Constraints:** * `1 <= n <= 1000` * `1 <= id <= n` * `value.length == 5` * `value` consists only of lowercase letters. * Each call to `insert` will have a unique `id.` * Exactly `n` calls will be made to `insert`.
Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good.
Array,Enumeration
Easy
2122
332
Hello, today we are going to do the granddaughter question of reconstruction department. Now let us take an example in this . How to see this if we go from A to P and there can be another answer to this. In which we first go to the one which can give the correct answer according to the answer, which has according to the answer, which has software , then I have to keep the order literally but not that, we have to take care of that also, what can we do for this? So we will push B in our answer then now we will go then we story is not going we can do extra so in this we do tomorrow and nrt and from tomorrow we story is not going Now if we reverse it, the answer will be NIT JFC. If I shortened this part, what will we do with it?
Reconstruct Itinerary
reconstruct-itinerary
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. * For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. **Example 1:** **Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\] **Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\] **Example 2:** **Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\] **Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\] **Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order. **Constraints:** * `1 <= tickets.length <= 300` * `tickets[i].length == 2` * `fromi.length == 3` * `toi.length == 3` * `fromi` and `toi` consist of uppercase English letters. * `fromi != toi`
null
Depth-First Search,Graph,Eulerian Circuit
Hard
2051,2201
811
hello everyone so in this video let us talk about a medium level problem from lead code the problem name is sub domain visit count so problem statement goes like this that a website domain is named as discuss dot which as discuss dot which as discuss dot which consists of various sub domains at the top level it has com as you can see here at the next level it has lead at the next level it has lead at the next level it has lead and at the top and the lowest level it has discuss. so as you can see discuss. so as you can see discuss. so as you can see here wherever you find out a DOT okay then before that it consists of a particular domain particular domain particular domain discuss. so whenever you find discuss. so whenever you find discuss. so whenever you find a dot it separate out the you can say a domain now what your main task is that you are given account paired domain account pair domain means that you are given a string in which there is a particular number which is represented before then there's a space and then there is you can say a particular domain okay now this count represents that how many times you have visited a particular domain now when you are visiting a particular you can say let's given a URL then you will visit all its sub domain as well and you count it as well so let's take an example for this 9001 on discus dot so this 9001 on discus dot so this 9001 on discus dot so which means that you have which means that you have which means that you have and discuss dot and discuss dot and discuss dot all nine thousand and one all nine thousand and one all nine thousand and one time okay that is the oral idea here now you are given a list of count peer domains as you can see in the input which is named as CP domains count pair domains you have to return a new array in which you have to modify it and write down how many time each particular domain is visited and you have to just represent it inside of an array so let's take the first two examples to understand more of that what we have learned so let's say that we have this as a string now this overall represents that I have visited com as you can select dot you can see here uh what is the output yeah come so just represent like don't put dot so com lead and discuss put dot so com lead and discuss put dot so com lead and discuss dot lead all noun 9001 times so dot lead all noun 9001 times so dot lead all noun 9001 times so as you can see in the output you have represented I have visited nine thousand one times 9001 times one times 9001 times one times 9001 times discuss dot date and discuss dot date and discuss dot date and okay so all those sub domains as well everyone is rated this number of times let's take the next example in this what you can see here is that I have to make some sort of a map you can directly understand for me itself that in this you have to understand that I have visited com 900 times that I have visited again 900 times and Google dot I'm just putting G google. google. google. okay this is google. again 100 okay this is google. again 100 okay this is google. again 100 times now let us moved on to the next as you can see that now I've visited com again 50 times so I have to append 50 to it now this is the to Yahoo now this is the to Yahoo now this is the to Yahoo .com 50 times .com 50 times .com 50 times the next string com again one time so I have to add one to it so mail have to add one to it so mail have to add one to it so mail we have seen here that I have weighted again so it is 90 times so plus again so it is 90 times so plus again so it is 90 times so plus one so which means that I have traveled a previous sub domain I have to append the times we have iterated over it so this one is the value you have to add okay that's not the idea of this it read over all of these different you can say CP domains that you're given to and you just have to return this in the end that I have returned like I have a this number of time this number of time this number of time this number of time gmail. this number of time gmail. this number of time gmail. at the summer time and so on at the summer time and so on at the summer time and so on in the output okay so it's pretty much simple you can understand it from the logic itself that you have to make a map in which you have to store this string as well as the count of how many times a particular domain you have visited okay for that you can make a map and that's nothing much complicated here you just have to first you can say find out in the particular string what is the count and what all are the different domains here and then for that you just have to make a map and then again from the map you just find out the financer let's go over the code chart so that you can make understand of what we have learned as of now so let us see here okay let's scroll this down a little bit so I've added yeah so what we have done here is let's move all of this out first so we have to make you can say a map okay that will store a string that is this domain and the number of times we have uh visited that particular domain so that is stored in mp now we'll iterate over all of these CP domains one by one using this point now what we'll do we are given a string in the input you can see here it just if I just move this out just go off you are given this as a string that is this 9000 and the all the domains okay so you have to first take that butter follow that and convert it into this part and the other domains part okay so for that I have written down this convert function okay that will just divide this into the integer that is this integer and the string this complete domain like this how you can take it out you can write it as a shout out using this space because of this is space whatever is before that is the number before what is after that is the particular domain now you have all of that is with you that is stored in this pair that is integer and string now you have this string you will have to editor all its sub domains and the sub domains are defined by this Dot and it is made you can just edit from right to left not from left right because these are made from righty left let's say one is column that is say one is column that is say one is column that is rather is so everything is rather is so everything is rather is so everything is formed from right to left so you just have to iterate over the string from right to left as you can see again for Loop and whenever you find out a DOT so let's say we have this string okay discuss.t I'm iterating from discuss.t I'm iterating from discuss.t I'm iterating from that right to left whenever I find it a DOT which means that now I have formed a particular sub domain so all the string that is after this dot is one of a particular domain so I have to make a substring so whenever I find it a dot it is whole string from I to left when I find a DOT I'll make a substring from J plus 1 that is after this dot whatever string is there I will make a substring out of it and that is one of the domains so I will take out that particular domain that is stored in name put it inside the map and how many times we have visited it that is stored in that we have extracted out from the string that is this pair that is in the value what first that is the first value that is uh how many diameters iterated that is it like extracted from this modular state so that is how we have got everything out but because we are starting out in these domains based on this dot I will take out com I will take out but there is no dot before but there is no dot before but there is no dot before this so there is one string that is already left out for that we have taken this as a thing that when the complete string is done whatever is the complete domain also that you have to take into account and also append that now we have created all of these domains put their frequencies inside the map that is all completely done insert MP now we have to make a new you can say a vector of strings in which we have to reappend third times every domain is visited and the domain itself and make it a complete string so we have to deliver all the entries inside the map and then what we'll do we will take out the value like How Many Times Reporter domain is listed that is an integer so I have to convert it back to string because I have to make it a complete string so to string convert that particular value to you can see string add a space behind it as you can see here in the output and the domain name okay then this is a new domain you can say a new CP uh you can say count paired domain and this you have again appended the number of times a particular domain is listed and the domain itself and now take that new string and push it inside the answer Vector that we have to just return in the end we just return the two but the answer that's the overall logic and just uh just to before closing now just also show you the code for the convert function and how this convert function is done is that uh we have given this a string this complete string that has the integer and the complete domain so I'm just iterating over this whole string 151 from left to right whenever I find out a integer I keep on converting it into from string to integer because it's 9001. okay so when I treating over left right I whenever I find out an integer value I will keep on converting it into a corresponding integer okay so that we have the final integer whenever I find out a space which means that the integer is finished at that particular point I know that the all the strings after this space is the domain and all the number that we have just computed is the integer so I will return the number and the string and how we can find out the string that is the substring of this complete string from I plus 1 because I is a space so I plus 1 till the end that will form a substring from I to I like I plus 1 till then that is a complete you can say the complete domain and the number itself that we've extracted out from the very starting of the CP domain and just return a pair out of it and that's it we always get it out so we'll just run out this particular thing that's the convert function and that is called here to get out this will turn the particular value and the particular complete domain from which we extract out each domain one by one and just keep on appending evaluate it that's all logic and the code part for this particular problem if you still have any doubts you can mention in the comment box for this particular video I will see you in the next day coding and bye
Subdomain Visit Count
number-of-subarrays-with-bounded-maximum
A website domain `"discuss.leetcode.com "` consists of various subdomains. At the top level, we have `"com "`, at the next level, we have `"leetcode.com "` and at the lowest level, `"discuss.leetcode.com "`. When we visit a domain like `"discuss.leetcode.com "`, we will also visit the parent domains `"leetcode.com "` and `"com "` implicitly. A **count-paired domain** is a domain that has one of the two formats `"rep d1.d2.d3 "` or `"rep d1.d2 "` where `rep` is the number of visits to the domain and `d1.d2.d3` is the domain itself. * For example, `"9001 discuss.leetcode.com "` is a **count-paired domain** that indicates that `discuss.leetcode.com` was visited `9001` times. Given an array of **count-paired domains** `cpdomains`, return _an array of the **count-paired domains** of each subdomain in the input_. You may return the answer in **any order**. **Example 1:** **Input:** cpdomains = \[ "9001 discuss.leetcode.com "\] **Output:** \[ "9001 leetcode.com ", "9001 discuss.leetcode.com ", "9001 com "\] **Explanation:** We only have one website domain: "discuss.leetcode.com ". As discussed above, the subdomain "leetcode.com " and "com " will also be visited. So they will all be visited 9001 times. **Example 2:** **Input:** cpdomains = \[ "900 google.mail.com ", "50 yahoo.com ", "1 intel.mail.com ", "5 wiki.org "\] **Output:** \[ "901 mail.com ", "50 yahoo.com ", "900 google.mail.com ", "5 wiki.org ", "5 org ", "1 intel.mail.com ", "951 com "\] **Explanation:** We will visit "google.mail.com " 900 times, "yahoo.com " 50 times, "intel.mail.com " once and "wiki.org " 5 times. For the subdomains, we will visit "mail.com " 900 + 1 = 901 times, "com " 900 + 50 + 1 = 951 times, and "org " 5 times. **Constraints:** * `1 <= cpdomain.length <= 100` * `1 <= cpdomain[i].length <= 100` * `cpdomain[i]` follows either the `"repi d1i.d2i.d3i "` format or the `"repi d1i.d2i "` format. * `repi` is an integer in the range `[1, 104]`. * `d1i`, `d2i`, and `d3i` consist of lowercase English letters.
null
Array,Two Pointers
Medium
null
44
Tiger so we will request some cotton match what has he done on this day and given one cotton does it match the pattern or not so friends in this way I will give you Loot Marg na he take any container Can send means he will become wife, this will also become semen or become the same character on Twitter, this kind of special thing is that black means anything, he will become someone 1234 That means it is not that, it does this or not Does this also for the meantime, there is one if I make Star stand for AB that Star should match you too and then any number of link fitness test matches can be done if Russ Star matches AB then this one. You can cancel a tractor by making a micro request, this can also be done if the proprietor will not come, if you want to make a D for this, then how can you do the registration? Okay, so I will give you my lion on one thing, BCA, BBA and BCA Star West Side. What else do I like in my mind? Reliance's discount is still there. Now almost the question will be asked. Time will send the meaning. Take the loot of a string. Ajay has become a robber, so I can keep it aside anywhere and think about it. Had taken introductory, this is where I clicked on the star question whether it is for the chief or not, and here is the complete beta tester question, from here to the problem, straight line pattern. Subscribe Now, if anyone here If you ask, there is only one we are inches where they are actually black patterns. Play Uday Singh's song. If force is not working then like button marriage like share cannot match anything. Now what is the meaning here? What is this meaning that we are in these What will happen that such a big pattern Essar a question mark is required Live score is matching So this is my say Question mark is matching black Question mark can match any one tractor No more no less Blank Chief I am not sorry, this wire has a strange skill that the wire can disappear or become a tractor or become two fanatics, I can become a gland director or two, according to the cut, the mosque can become three. The disease can become as per your will and it can disappear, so what will we do here to make it disappear, if there is something else, then match it with the line tractor, use the blanks in the blender, if you are not a customer, then there is something else, otherwise it will disappear. Go, you are the body, we will meet from below, which has been shifted from below to this one, I put a red color on top of this one, that it must have heard the body, okay, that the star is in the last over, all this goes on, this line does not match. If I could, then all these question marks, stretch, like, comment, this is the 111 needed in front, otherwise do a sorry column tomorrow and here the whole episode would have matched the black that Nikita Singh should make a difficult toe, it is also here. But now what will happen to you about the rest of the culture, we will think about it from Patan is a question mark, then we will think about that, it is a wire, you will think about something else, and then you are a character, think for a while, these three things can be done on this channel, question mark England. Came in front of your adulteration and so he will come back in front of you then wife addition will keep doing okay so question mark whenever someone like was hitting something here so let's talk with you about this a few months ago some Madhuri can For this reason, make sure that this string matches this trick or not, then by making a question mark, it can also be made of that mic, because of that, it will be made that if you make this smartphone then it will be canceled like this, then your The answer will depend on whether the question mark became its own and this one was declared a place match. Now the real question is whether a question mark was equal to a baby or not, which, if left here, will go to you here whenever in some case. Cast big votes and do nothing, I talk about this year, he will think in his mind, above this post, we were thinking whether this thing matches it or not, customer can make any cut, so customer setting is everywhere. Now it is possible that if the customer has become this then this and this then I have become so, actually let us see this question mark, if the BJP President used to do that match then there is no rule, only five, then the meaning which will be the answer to this and this is this trick and this. If there is a question mark, then they will keep it here by abusing. Now let's talk about the tractor. I am now some time character comes. Like here, does it match with what we have been seeing for the last one month or not, then it is a match. Only our question mark will be BA Semester, so that when you have character in your pattern, you will see that this team is a cricket team, if there is time, then pick it from the bottom and put it because you have matched it from both the sides, then also there is a question. This is that if it matches this one then this trick will be applied then this Mittu will come and if it does not match this one then he will stand here, now these matches will keep happening no matter if the next one below is not matching then he will get stuck. If these two are an item match, then nothing further, even West Pattern Message Superstring and neither cricket match, then leave the festival, they go on Monday or if the characters match, then dip them, but if the characters do not match, like here. But there is only one share, so let us ask whether B question mark matches with AB, it cannot be sold because it is the same bean, the one below can keep doing anything, whether A question mark matches with AB or not, it is still equal to itself. So here the army will come. Okay, so here are the two regions where the chapter has reached. If you match then go to the diner. If you don't forgive, then be all over smart and go to see. Now let's talk about the wire. Now let's talk about the star. If you can understand the essence. I've heard this trick hit a brush now here it's 44 cents for no7 glad toe no and tractor If the question is subscribed then all the fun can be gritty that it can become anything directly and if 0 inter then our happiness is that a question romances more than the path or not if the star becomes equal to one become reddy and If one becomes equal, then our need will be A question mark, does it match baby or not? If star AB becomes this, if the essence is everyone, then our one will be A question mark, does question mark match baby or not, if star AB becomes this? Our Sonalika was filled with cars, this question would have matched Mark too, that if only Akela could have become a star, then nothing would have happened to us, this Question Mark Black would have been the mastermind, then the next one, if Gadpati Jaiswal is here, then the next one would be full of laughter here. The rule is that everyone can become a star, AB can also be made from a star, Star TV can also be made from a star, OK, let me talk about myself again related to the star, we were checking whether the wire A question- mark par Id Kuchakra whether the wire A question- mark par Id Kuchakra whether the wire A question- mark par Id Kuchakra August star becomes black So for this we will also do that with the question mark If the star becomes a blank proposal then everyone does and it will become sa became sa This is to ensure that the question mark also matches more Does it or doesn't it? If Starr is determined to become AB then they have to match A Question Mark AB Kuch Karta and Starr becomes the first cigarette I have to match that A Question Mark B is the master so that A Question Mark AB does not do it and Starr is the only one Why can it be made, then we have to think that a question mark means like, comment, so that it doesn't mark one and a half, then one black is left in front of that mike, but anything can be made of it, what will we do when the star Either we will go to the next room from the very bottom till the last Jab Star Ban Gaye Black, which is clearly declared Black, we will think that a question mark has now become Shahrukh Line, then we will have to match that mark also, this point Jab Star Ban Gaye Exam will remain. Took the question Mark and Baby will come here to watch when DB becomes a star, even if it becomes clear, if it is difficult in front, then sit here and have some fun, talk about fun anywhere else, if this becomes possible, then we have to think about this. Question Mark Pacific matches or not and even if he becomes a star, then we have to think that Question Mark blackmails me, okay, that too, I will talk about it, first we want to enter our village Subscribe Accused I am going to stay for now, which is our rule, today I am going to write about your room, this question will be put to him for vote, if this character of Mark Diner is the same, then it is different and if it is a star, then here is the question for you. What does he like? So I am okay here now that the question has been asked here, the question matches the question mark also, now some Maruti can be made for the friend and the society, that Mike has become this and the question. Would have asked if Black would have matched Black, then the question would have been the power to match Mark Henry. The power to match Mark Henry was our destiny. Question does Mark match Baby or not? Customer, tell me brother, I can become more like this, so this became the one of unity. It remained that Black would also match. Now it does n't even match the line. Okay, so we had said this simple that if Karisma comes then we have to see the final. Question mark diner. Saw some smart baby nearby. I see the time of Fukushima. Question mark is there so we will see that our time has come for this. He has eaten up his leftovers even in the guise of Vishnu, nothing is left whether he sends a black egg for the baby or not, now he doesn't do it with a plate of Rs 11,000, so he doesn't do it with a plate of Rs 11,000, so he doesn't do it with a plate of Rs 11,000, so he reached here, he started laughing, now we will take this point. Being thrill question mark question is question mark also matches or not and it is equal to the apk file now what is this quarter inch down here question mark what is AB here one that mic and above it decides If he doesn't do it or if he doesn't do it then he is not from here and hatred just message us here whether he matches BJP or not. Now brother AB de Villiers, if no one can come then anything else happens in the same way. Now it will be seen in the next session. Here is the question. Question Mark gives many examples and can match them. There will also be a question of cutting. Now the question is whether some Margs are suitable for the baby or not. We have seen Pushti Marg. Couldn't satisfy the baby finally Bigg Boss then photo When we eat tomatoes in this way, here he asks four questions, what does brother like, I am nothing, I don't see anything here, I will try to be a Brahmin, if I go to Bangalore, then mark every question. If it matches anything, then there was a question mark, it did not match even, then he said, okay, if this is not being made, then I am in your middle order, so I will also eat, I will become Ruby, if I will fight, then question mark. Black matches means it cannot match Chandra Bose's star question mark middle. Now see here, now for the first time there is something better than you. If four question marks matches AB, then Saturday does each question mark. Is AB two? Satisfies you, how are the options is Tapu cent for black, if black remains, then your question is this smart baby, clean bomb 14, if it becomes one and eats, then the question will be a question mark with also four, this question of complete wooing by becoming AB, this question was with black, then see The complaint here when he became a bank is universal, nothing is the question, why do I clear the question mark Henry, I have the capacity, the next question was, if I take a hit, then a question mark for the chief star, everyone goes, yes baby. If it becomes a question mark, then judge Sahib's length should stop anywhere in this team because if it means anything then here in Metro, when the star becomes black, the one who becomes 4 black, then one, he clears Madhavi, one, why just marketing? I long to become a customer, so why did I come here, now I do n't feel like commenting here further, see four sons, Vikunthan Transport, I have nothing here, star question mark, what stars, does some mark clear the baby? This is a question, if we have 4 blacks, we will go here, this off will become, here we will take off, we will become here, and star Pooja Bedi will become here, we will go here, if there is a wave anywhere in it, if there is a two, then the obstacle will be broken. Staff has become clean, this one has come after becoming clear. A question mark used to clear Henry, it is over now what is the next question that wire question mark wire question A does many others now I can say anything, four will remain blank so the question was asked on A question mark then bank should be made So every one Osman Agriculture kept thinking that a question mark is like an agri, that man found star Javon Jhaal meaning it was covering it, then he looked here, does the question mark match the baby or not, then the star also became this, that is a question. What does Mark do while matching AB? If you would have searched for it somewhere, you would have gone. When the wish is being made, its chant is also being made, then the star question will be recommended to Mark also. Had a recent Gutkha along with it. Ate some aunty. Okay. So the power of a semester is zero and I can make corrections. Now we have to see this, so we will take it in this whole. Bittu, you tell me for 20, when has it happened, when you have eaten even by hitting, till the time this option of doing this will go. And Kimam Bhi Koi Ka Here Now Even Here In Schools Only Vishnu Hai To When Star Triple A B Is Stopped If We Stop A Koi From Star Trek To That A Is Gaya And Krish Marks Gaya Apna Sara Hai Ho If you find it somewhere in Gaya, then how did it happen, when someone did the target replay, then in this year we will give a question mark with A B and if there are votes, then I will do it, okay, let's also give a comment clearly and here the star. Successful Tushar Dhundli you till the bottom of this, now for the star, if it is puri, if you have taken it, then subscribe for this, if this egg is equal, then one each, Ghunghru, while thinking, there was a question here, four Tejas Mark 1, which was a question. A star a question mark at this point star question mark matches triple A baby in this so we have to see the miss you blood channel that question star question mark matches strip le bread which is He used to do what he used to do, it was cut like this, here we have Shahjahan will always ask bar question on Saturday, all these questions on the point whether triple this also matches to, play B, so this is how we click. So that's why we are seeing that this is matching the question mark which if I want, so this star took one and for the post mortem the equal game is very simple so here you like this so Noida Ko Katega See all the question marks below, does it match the WB or not or is it different, only the chords are also simple, the ghee behind the question mark can become any character, tracks are made, it will cut the character, now look at the lines, there is a star. So the entire row below will have to be given, after that you will have to complete the whole work, you will see all the works from the very bottom that they will get cricket, then two, why is it so because the star has to play the character of Vikram Bhairav ​​and one character of Vikram Bhairav ​​and one character of Vikram Bhairav ​​and one character of digestive cross three and hence in such a situation. It was discussed that if the village should be included in the live operation then what has to be done for that, listen that from here I repeat to you that you will have to wait a little bit and I will go back where you will have to cross the corresponding line so that the off medicine Right now, do I have to put a loop in the case of the star or not? Let me cry, if you take me somewhere, I will feel this wired road of the soul again. So, first I will fill you like that for some time. Ok, start from here. Let's do how I was filled, she is a big star, so this is her, look at it, neither is it erased from 204 to four, anywhere is the rule, you are two to 4, this is complete, said that if there is a tumor, then it is instant, to see this complete, you take her. Need to see from this all friends doesn't see two ways to think two ways of thinking now how we are thinking is important this is gonna think how we are thinking with the list either helps you with me Of the list, either now when we had given the puri, how did you think, our question was, I will make the entry upwards, ours was nothing, four question mark 41, Vaishnav, does it match with Eid, the service option, Meena becomes black, or is that the first one? go or become that or got for the question does it used to subscribe and had subscribed that wire plan made to a question mark on were wire-to-wire ho were wire-to-wire ho were wire-to-wire ho yes baby made aye marriage to your Two characters are gone, one bus is made, look at the marketing strategy, 3 Kattappas are made for the star, one bus is made, marketing is done, look at the meanwhile, four Eids are made, everything is done, one bus is made, marketing will be black, somewhere, we found that it was also made, when all were made. So 1 inch to hear this from here if subscribe definitely means the other and this has become a headache for us subscribe means does A also match with the question mark that with disappeared and keep the second story also taken and Survived even then, started looking here, Manoj is testing the question mark with baby, The Best Star, Manoj Baat, picked up one item out of four and subscribed, baby, so he can also pick up one item again, survey the jackfruit again. If you can, then one way was to think that what is the star plan, what is the wire, what is this four, what is the deer, what is good from the star, what is the side, what is the other wire, one should be kept, one is a yagya, two. The option will be the device is not at this time any frustration or 1 just think the owner with Id this is the point and on the other hand see here what does it mean that star 8 and still alive stitch we are seeing this means the wire question this you see What is the meaning of this that one of the accused in the telegram is still alive, then if there are two of these two, then you see this one, seeing this one is equivalent to seeing all of them, you know, think, this one is the result of all of them. No, this line is different for everyone and so if you look only at the Hindu sales, it is about you, okay, I am enjoying, this one is the sales, this one is the center star who has come, so this one is the sales, it is more of both of them. And there are more of them, similarly this gel is there of these three, whether Bittu can be found or is it just of these two, there are more of them, Indore is also there, meaning there are two rules with these skins every year, ISRO. Every person has two formulas inside him, you can understand that he is the other of all these, and understand that he is the other of these two, if you look, you will see this thing, meaning one layer of Sodhi, think about it, if this guy is one of these It would have been more of these three that he would have been of these days, if this guy was of these days, to make this guy, it is enough to do more of these two because he is of these three, okay because he is of these three and So only out of these 9th, you will get these four here, I have clarified here and I have heard from this, first of all I suggest you, pay attention to the one who is near, I say do more of these two. Turn on both of them, friend, I say Indore, Hello, this is the matter with both of them, this saliva was started on which it is shown as extra, so turn it down and I will put it here, who is the section of these two that the wire is for some time. Nothing was needed in this, no office is needed, if you copy the above then the verification below is equal to 2. Within this family, what I had already told you about, do more of these two and do Indore and this. Both of them are equal. Be careful about this one and uninstall it. By crushing it, he will notice pregnancy. Okay, now after this, why are both the same and do more of these three? How to hack Aaya Indore Golu, why is it Indore Ganna Simmba because it is actually these Both sides are equal. If it is made from these two then it is also equal to Hindus because both these pieces were equal. Then I will say one by one. See, for the first time this will be an exact copy of it, why is there a string here, there is an option, pick it up below. Either we should use this noose or take this hmm garlic and this way there is not just one option to go here to do this and this or not and this is for drama Next birthday for Ramesh too, this is absolutely fine, now for this dynasty, we apply for both of these and do Indore, this one and this one were stuck only then and this is the Jio SIM between these two, you will do these nine only then One is complete, if you do these two, then one is complete, and if these two pieces are equal, then any MS Word will remain a duplicitous, if we talk about those three, if you make one more, then it is two and by doing more of these two, you will make one. If these three will come face to face, if they are from Indore then Mittu will come and it is worth thinking whether it is the same or not, this one was equal to these two and these two, this one was equal to this one, you, the result of these two. Suppose you go to Indore, you got their job, you get the headache and take it in Indore, now think inside this one is also this one is proud of both of them, you can get a print job for this one because I made this one towards this one. From and asked for this two, this one of these two, which is sitting in its play, you have porn movies of Indore and this is full of them, when you do more of these two, you will do around these four, it is okay because This one is holding the result of these three, it is sitting like this, you were made on behalf of this one and this one is related to both of them, so it was tied on behalf of both of them, work is made between these two because of this, if there was equal then those options Well, this one used to represent both of them and became one, he was made on behalf of both of them and he used to audition for both of them, so basically I was from Indore for this. Now I have found these three more inside, this one that when I go to Indore, he will weigh the weight of these three, will he represent this line around or not, will I go to Indore in this fort and this one is the Hussain of these four, then this one will represent these two. And only by doing these five things, you will not be able to do anything else to the old people and by doing them, you will get it five times. Let me give you one last try, complain to me about trying again, so that you can get the complete link below. Stop, there is no need to do more, just you two. If you do this further, then you will be stopped downwards and will get how it will be given. Please stay with me, see more sweets, I have that today, first one, we have two methods, which was new and told, for this, in the wired row, you can only do these The criminals had told us to do it from bottom to top. They will also go like this, they can also add from this, take this from this, let's talk about this, think about this, here, this and this for x This is not possible, I click on this and understand that if we talk about X-One country eunuchs, then understand that if we talk about X-One country eunuchs, then understand that if we talk about X-One country eunuchs, then here I have given you both of these and now you must subscribe to this channel and I have given you everything. That's what we took out and our production started decreasing, I made it of 1 inch, so I will put the pattern first, I gave a picture of mine, put the virus pattern, the pattern is return link plus wave and put the interesting, drafting don't drink plus point, okay. Now we have point to daughters - - - a pointer equal to a regular ₹2000 of hero for daughters - 101 a regular ₹2000 of hero for daughters - 101 a regular ₹2000 of hero for daughters - 101 10 - - 10 - - 10 - - that if the last row is also and the last water is or only the last row is or only the last column. Will remember for the last row and write in this link Last Road Last Tak write in this link Last Road Last Tak write in this link Last Road Last Tak Yeh A The Last Till Last For - - - Plus Point For Last - 4a Plus Point For Last - 4a Plus Point For Last - 4a Main Last Ek Hai Kya Last Oho Kya Last Call Hai Kya Arrest So in the last romance resides, it is told that in A B P F I G, the salute to the last is successful in the last, that at two o'clock, I will tell you again brother, if black pattern black matches you, then the rule is black pattern for the rest. Can't send a message to ' black pattern for the rest. Can't send a message to ' black pattern for the rest. Can't send a message to ' Falls Here', what happens here, there Falls Here', what happens here, there Falls Here', what happens here, there is a question mark, you see, if it is not there, then the chords ABC will come, then if it was not matching anyone, if the falls will remain, then that black money can be found below, it is just fine, so if Your J is in the last over, if your character is my dear time, Candy Crush is also on the mistakes and posting has been put on the table, what is the problem, I belong to this group, I have to knead the patterns with love, I am only love, then you have to look down. If there is ABCD then there is a middle question then also there is a first system so you can see below so we have pattern dot right above in this way then you can take deposit 251 rates below now what is the story here, all your patterns are here. But it will depend, if the love inside the train is a string of question marks, then I told you, and with this, whatever is in your account, it is absolutely low, the voice does not have to be seen at all, and no one else. If it is there, we will put it in it. If equal to two plus two, the patrolling is equal, yet it is true that it does not keep the light equal, there are falls and wires, so I just told you that it is vertical and the heart is below the water only that we do this. -You will get the answer while doing this. that we do this. -You will get the answer while doing this. that we do this. -You will get the answer while doing this. Return the DP of Jio phone if wear mode is on. In the video, scientist Bill Gates said that if you do n't do anything in time, then you go to Lanka, then why don't you do it again. We submit the correct answer. Hopefully. If you are lucky then you would have enjoyed it, so if you understand this then don't keep watching Dhal Meghwal A
Wildcard Matching
wildcard-matching
Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where: * `'?'` Matches any single character. * `'*'` Matches any sequence of characters (including the empty sequence). The matching should cover the **entire** input string (not partial). **Example 1:** **Input:** s = "aa ", p = "a " **Output:** false **Explanation:** "a " does not match the entire string "aa ". **Example 2:** **Input:** s = "aa ", p = "\* " **Output:** true **Explanation:** '\*' matches any sequence. **Example 3:** **Input:** s = "cb ", p = "?a " **Output:** false **Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'. **Constraints:** * `0 <= s.length, p.length <= 2000` * `s` contains only lowercase English letters. * `p` contains only lowercase English letters, `'?'` or `'*'`.
null
String,Dynamic Programming,Greedy,Recursion
Hard
10
700
in this problem we have to search a value in a binary search tree so this is the classical uh use case of searching in a binary history no changes made so here we will look at a recursive as well as iterative approach and both will depend on where the node is located so if the node is located uh very deep then that will depend on the number of nodes that will lie before that so height of the tree from root till that node that will be the time complexity so let's see both the approaches first we will look at a recursive approach then we will look at the iterative approach so let's say we want to search for three year and this value may or may not be present in the tree if it's present return pointed to that node if it's not present then return null we did not find it so let's say we have to find three it's present here so we will return this pointer and you are given root of the tree which is the usual case so you have to implement this search you are given the root you are also given a value so here we have the value is 3 so what we will do we will check if root is null or not so if root is null then we can't do anything return null if root is not null we will compare its value it may be possible that a root is holding that value so if root dot val is equal to this val that we want to search then return root next if root dot well is more than well that means this root is more and in binary search tree everything in the left sub tree is smaller than root this holds true for all the roots all the nodes so this root value is larger which is the case in our case also 5 is larger than 3 so we know that everything in the right sub tree is larger than root so if root is larger everything else here would be larger so we would strictly search in the left sub tree so we will return search root dot left and the value else return search root note write and value so that's it so it will call search on this node again we will check if your root is null or not if it is not null we will check if its value is equal to this value or not so it here it will match so it will return this value 3. let's say we want to search seven so what will happen we will see this is not equal to seven its value so we will call the search on so we are calling search on five is the root and 7 is the value so it will call search 6 and pass 7 and here it sees that 6 is not equal to 7 so it's smaller so it will call on its right but its right is null so it will call search null 7 and when this call is made it will check whether this first parameter is null or not it will be null so it will return null that is we did not find 7 here so this was the recursive approach let's look at the iterative approach so let me draw the tree it was 5 3 6 and 2 and 4 so again let's say our function is search root and val so we will have a tree node current we will initialize it to root and while current is not null if current is null that means we have reached the leaf node and beyond that and still we did not find that value that means we have to return null we did not find that we never look at two nodes at the same level in the search so either we go left or right so we go left so we will not search in anything in right similarly here we will take any one of the branches and ultimately current will become null so current is here we see if current dot val is equal to val then return current we have found a node we have reached the node so we return it else if current dot val is more than well then what we should do current dot val is more than 3 that we want to search so we know that it cannot be in the right subtree so we shift current here current equal to current dot left else current equal to current dot right so here there is no recursion we have a while loop and we are iterating till current becomes null or we find the value these will be the two scenarios we can find somewhere in this case current becomes three so next when we reach the beginning of the loop again we will compare we will find it and we will return it else we will return null or current both are same since this will end when current becomes null so this will be the case when we did not find the node so i hope both recursive and iterative approaches are clear let's look at another example let's say 7 so current is here it's less than value so current becomes current.right value so current becomes current.right value so current becomes current.right so current comes here again it does not match so again current dot value is less so current becomes current dot write so it's right is null so current equal to six dot write and six dot write is null so current will become null and this loop will end and we will return null that is we did not find seven now let's write the code for this in c plus java and python so first we will write the recursive approach so if not root return null ptr if we found the value we return it if root is greater than well then return left and well if none of the two cases are there then that means this is more than this is less than well and let's see so it works so let's submit and the solution is accepted let's look at the time it takes so it's not that great it's around 13 only now we are at 45.53 that is now we are at 45.53 that is now we are at 45.53 that is at the main distribution so these things are random we jumped from around this region to this region very quickly with the same submission so now let's write the iterative solution here so let's comment out this part or we can also return current both are same and this iterative solution is also accepted now let's write both of these solutions in java and python as well and this solution is taking 0 millisecond that means it's better than all the solutions we don't have enough submissions i think we submitted early today so this is the best solution it takes 0 milliseconds so you cannot beat that so let's see in java if we make it recursive there is a difference in timing or not so let's comment this out so in general iterative solutions work better than recursive if the time complexity is similar and we can confirm it here and this recursive also takes 0 millisecond so we don't have enough distribution for runtime so this the test cases may be quite small so that's why both recursive and iterative are taking 0 millisecond each now we will do it in python so and this python solution takes 92 milliseconds finally let's try the recursive solution and this takes 96 milliseconds so in python it's taking a bit larger time and in java it's taking smaller time
Search in a Binary Search Tree
search-in-a-binary-search-tree
You are given the `root` of a binary search tree (BST) and an integer `val`. Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 2 **Output:** \[2,1,3\] **Example 2:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[1, 5000]`. * `1 <= Node.val <= 107` * `root` is a binary search tree. * `1 <= val <= 107`
null
null
Easy
null
222
Jhal Hello Hi How are you I am O Aaliya doing good welcome to the land co disney today will do come account complete free mode and it's really it's personal question this cancer it is not visit after wave some service given in this witch mins solution liquid up sid this company bank so baikunth wikipedia every level such parties possible is complaint field so complete binary tree and all the notes in the last level is possibly can have between one and two boys and 10 glass level morning that account number notes person benefit complete Devotion and solution azhar butt is given tute to complete your fit designs recent updates oppression legend of and solution subah you can do for me that graph and solution you have you were simply divine life with contact with just called development and years the left and web that This issue is the first ever discriminated all the investigation and painted is and complimentary feeding is on but how can we make the solution memory this and you can be minimized solution susur Applicator time to free dish soak of class fifth solution soil testing you simply arthur property Of problems which make a solution maura this and instead of getting back debt to apply for mother condition in between debt the solution in very easy way more efficient show how so let's take members for these five districts 307 various slapstick su a from Beethoven in the back Solution to you happy just you will go for every New Delhi to when account soen I will just take this manner a saiya to continue not but instead of counting every side what you can do you will simply check one old change left most part is equal To Dhara Ek Most Part One Not Difficult To Equal Din Behave Simple Formula And Its Uses This Tree Or The Complex Of Very Simple Matter Supreme Power And Good Also Left And Right Chaturthi Power Of With Images For Terrorists E Agree With Ashraf 50 Feel This A Narrative 12345 6720 800 to 1130 300 123 456 7days peth vikas complete 15mb subscribe hamala shyambir viewers destination in between and the life is the website is equal to two drops and not with distic where they can simply opinion 2013 - 2013 - 2013 - 1772 12345 from Z2 Travels in the ver ds in The Travels Dushman Video 90 Simply Return Seventh Agency This Is My Life Is Classification Also Do Not Have Been That Terrorism In The Happiness Travels In This Case Will This Is Left The Tight Appropriation Come Here You Can See Reduced Or Equal To You Will Simply Written In The Three Wings Tours 2012 - - 3D In The Three Wings Tours 2012 - - 3D In The Three Wings Tours 2012 - - 3D is 711 feature accessible v11 typing yes 12345 says notes videos improvements possible if university is placid in a ajay got a super spider man's i let me check box solution writing function is 102 so let's take a diff of account ok so let's take disbalance so this is the root of note in this just simply written in the 10 and here call buried sensor these all account difficult also edition bhi root a friend strange if ok so it's first ever for the website 102 210 Pink Left This Route Main Left Account Is 0 209 When Traveling By Left Side Ajay Ko Ki End Main Left Account Tomorrow Plus Exit Poll Increase By One And The Same Manner How To Right This The Road Flash Light Ko T20 And Tasty Virat Account Ki End Spirit is a special vast is pure right and it's my right account request dual app account is a distic well is body can she will simply return when you are free power of light account - mind chaudhary feedback this sandwich a - mind chaudhary feedback this sandwich a - mind chaudhary feedback this sandwich a lot of questions water proof I'll just returned Oneplus of account left of the root of left a plus account selection root of right a hai saunth baad railway station will make the function ok sona bjp has written dushman hai i hope reminder lage the ko select right choice 1115 ok sweater distribution list to samet End Sirvi Submit Note Ok Sir Know It Has Been Submitted In Single Strike By British Businessman Video Vidmate Video Till Donate Bye-Bye Take Care Vidmate Video Till Donate Bye-Bye Take Care Vidmate Video Till Donate Bye-Bye Take Care I Will Meet With Amazed E Jhaal
Count Complete Tree Nodes
count-complete-tree-nodes
Given the `root` of a **complete** binary tree, return the number of the nodes in the tree. According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`. Design an algorithm that runs in less than `O(n)` time complexity. **Example 1:** **Input:** root = \[1,2,3,4,5,6\] **Output:** 6 **Example 2:** **Input:** root = \[\] **Output:** 0 **Example 3:** **Input:** root = \[1\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[0, 5 * 104]`. * `0 <= Node.val <= 5 * 104` * The tree is guaranteed to be **complete**.
null
Binary Search,Tree,Depth-First Search,Binary Tree
Medium
270
148
hi my name is anley and welcome back today we'll see how to sort link list so we have given a link list say 4 2 1 and three we need to sort the list in ascending order and return the modified list so our output would be 1 2 3 and four similarly for the example number two in example number three when the link list is empty you can simply return the empty list so I hope the question is clear let's move on to important concepts for solving this question so if you're not aware of these three concepts please watch the video given in the description before moving forward first point says that you should know about slow and fast pointer technique because you need to find midpoint in the link list second you should be aware how mer sort Works in Array which involves working of merge sort and use of basic recursion okay third point is merge to sorted list link list basically so if you are aware of these concept you can move ahead in this question let's move on to important steps for solving this question so first point is handling the base cases if the list is empty or contains only one element you can simply return the hit so a base case is clear moving on we need to find the mid of the link list so mid is equals to Mid of the list and then in third point you need to sort the list from start to Mid and then from mid plus to end and then it will keep on repeating so we'll repeat step two and three until base condition is achieved which is head is either equals to null or head do next is equals to null then we need to merge the two sorted half and then we can simply return the result the merged list is the sorted result and we can simply return the hit but there is an important point which you need to notice in above steps should we be concerned about which midpoint we should choose for a list with an even number of elements or is it acceptable to select any midpoint let's figure out with the help of an example suppose we are choosing right midpoint every time and the link list is 1 2 3 and four so the middle will be three it will be divided into two list one two and three will be in the one list and list will contain only one node which is again midpoint is chosen which is equals to two it will be divided into two list one and list two very clear now here it contains even number of elements again and it is equals to two the number of elements are equals to two if we choose a right midpoint which is two it will be again divided into two link list one would contain elements one and two and list two will contain no element because M middle do next is equals to n again if we choose a midpoint it will be equal to two and again there would be two list will one will contain two elements one and two and the other list will contain no element so this chain will go on therefore we cannot choose right midpoint because there will be a dead blog whereas if we choose leftmost midpoint there would be no issue for example here 1 2 3 4 is the link list midpoint would be two divided into two list one containing elements one and two whereas list two will contain three and four if you divide it again the midpoint would be one and the list one would contain node one whereas list two will contain node two similarly node three and node four from here it will return one because head dot next is equals to null two do next equals to n it will return two and from here we get three and four therefore we should always choose leftmost midpoint when we have even number of elements in the link list so it's clear that in point number two you need to find leftmost midpoint and this is a code for finding the leftmost midpoint in the link list so I hope all the points are clear let's now move on to pseudo code let's begin with the pseudo code now so we have our function sort which takes the parameter the head of the notes so let's say list note head our first Target is checking the base condition if head is equal = to the base condition if head is equal = to the base condition if head is equal = to null or head. NEX is equals to null we can simply return the head note very well if base condition is not satisfied what we need to find midpoint so list node mid is equals to midad there is another function which will return the midpoint in the link list we have already seen this quote okay then after finding the midpoint our Target is to separate two list from the original list so one list would be from start till the mid inclusive the and the other list would be from mid + 1 to n other list would be from mid + 1 to n other list would be from mid + 1 to n for example here the link list is 1 2 3 and four our midpoint is two so our list one should contain one and two and the other list should be three and four how can we do that so what we are doing in temporary variable we are storing the mid dot next meaning the next node to the mid point which is three over here so temp will contain reference to node three and then we are saying mid do next is equals to null that is what we want mid dot next should be equals to null and we are able to from these two steps we are able to achieve our purpose of breaking the original list into two link list so what we'll do list node L1 will be Sol sort head now sort contains reference of node one contain reference of node two and node two will contain reference of null what we have done over here and list note L2 would be sort temp which would contain reference of node three and then we will merge L1 and L2 and for merging two sorted list we have already seen in the previous question link is given in the description this is the code for merging to sorted link list so I hope the whole pseudo code is clear to you now let's move on to lead code so this is problem number 148 sort list so I have already written the base condition so if head is equals to null or head. Nexus equals to run we need to return head if this is not the case we need to find the midpoint so let's say list node m equals to I've already written the function over here for returning the mid note we have discussed about this a lot in pseudo code and if you have any difficulty revisit the video for slow and fast pointer so we need to find the midpoint we'll pass in the head our next Target is to make mid. next equals n but before that what we need to do we need to store that in temporary variable so temp is equals to mit. next and then our mit. next will become null you know why we have done these two steps because we need to split the list into two part one from start to Mid and the other one is from mid plus one to end now as we have two list what we need to do we need to sort those list so we'll pass in Hit and the other list would be let's say list note L2 equals to sort list from temp right so now as two list are sorted what we need to merge these two list one and list two now if you remember the question here is to merge to sorted list which we have already done in the previous question so this is a code for it what I'll do I'll just copy paste from here so copy and let's do paste and just change the name over here and there you go let's try to run the code now okay so all the test cases are accepted submit it there you go all the test cases are accepted successfully it's time to have a cup of coffee and work on followup question the followup question here is you need to merge case ordered list this question is tagged as hard and has been asked in multiple companies including Google Facebook and Netflix so you are given an array of K link list and you need to uh sort all the link list in a sending order and then return the merged list for example here you have list as 14513 426 the output would be 1 2 3 4 5 6 so you're merging them into one sorted list if the list is empty you can simply return the empty list so I hope this question is very intriguing as it has been asked in multiple companies try to solve this question and if not we'll be solving this question in followup video I hope you have enjoyed this video very much notes are available in the description below please do like share and subscribe we'll meet in another video till then bye-bye take video till then bye-bye take video till then bye-bye take care
Sort List
sort-list
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 5 * 104]`. * `-105 <= Node.val <= 105` **Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
null
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
Medium
21,75,147,1992
341
Hello everyone Welcome to my channel here we solve problems Lead code today task 341 bringing a nested list into a plane Flat state level medium We are given a nested list of numbers N L Each element of this list can be either a number or also with it is necessary to implement an iterator such that it has there were Next next methods and the result of the iterator should be a flat list That is, if we look at the examples We see that we have a list in which the first element is a nested list with two values, the second element is the number two and the third element is also nested a list with two values ​​two nested a list with two values ​​two nested a list with two values ​​two units as a result we get a list of five elements flat if we look at the example in the code we see that Each element in our original list is not just a number but a special object nested integer which has three methods the first method which checks the integer Is this a number, the second method that gets the value of this number and the third method - the value of this number and the third method - the value of this number and the third method - this gets a list if it is not an integer, then we see empty methods that we need to implement first, let's create an internal variable which we will store our flat list for this we call the variable like this, field Q then there is a flat list will be in the form of a queue, we will add it to the end of the queue And we will return element by element and start to do this we will use the method Dec two-way two-way queue we will also have an auxiliary method which we will call which will expand our nested list and add elements to the queue the methods are quite simple in the method Next we will return a value from the queue using the Pop Left function, that is, we will remove elements from the left side of the queue, that is, first we will return F Next, we will return the queue, that is, if the value is not empty, that is, there is at least one element in the queue. So we have, respectively next element And lastly, we need to implement the method of filling the queue itself, let 's call the parameter Numbers in a loop, we go through each element and if this is a number, that is, we call the method from integ in the example above, if this is a number, then we put the number in the Self queue, we take the number, we call the Get method integ If this is not a number, that is, otherwise, we call the function again and pass Yes, our list is Namba Get L, in theory, this is the whole solution, let's try to run the tests, we've passed, we'll try to send this decision, the decision is accepted. Thank you all for watching, subscribe to the channel. Bye everyone
Flatten Nested List Iterator
flatten-nested-list-iterator
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the `NestedIterator` class: * `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`. * `int next()` Returns the next integer in the nested list. * `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise. Your code will be tested with the following pseudocode: initialize iterator with nestedList res = \[\] while iterator.hasNext() append iterator.next() to the end of res return res If `res` matches the expected flattened list, then your code will be judged as correct. **Example 1:** **Input:** nestedList = \[\[1,1\],2,\[1,1\]\] **Output:** \[1,1,2,1,1\] **Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\]. **Example 2:** **Input:** nestedList = \[1,\[4,\[6\]\]\] **Output:** \[1,4,6\] **Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\]. **Constraints:** * `1 <= nestedList.length <= 500` * The values of the integers in the nested list is in the range `[-106, 106]`.
null
Stack,Tree,Depth-First Search,Design,Queue,Iterator
Medium
251,281,385,565
763
hello everyone welcome to quartus camp i am here with another interesting problem from lead code which is partition labels so the input given here is a string and we have to return an integer array which represent the size of the substrings so the problem statement says we are given a string yes and we want to partition the strings into as many parts as possible so that each letter appears in at most one part note that the partition is done so that after concatenating all the parts in order the resultant string should be yes which means if we are separating them as sub strings we should not leave any character out of the substrings we divide them into and we have to written the list of integers representing the size of these paths so let's understand this with an example so here is our given input string yes and we have to return our output in form of integer array the problem statement says that we have to divide the given string into number of substrings and finally we have if we combine the substrings we have divided then that should result in the input string yes so now the condition says that if a character is present in a string then one substring should have all the characters in it uh let me put it this way so if suppose we are starting our substring with the very first character a then the substring s1 should have all the a's in the given string which means it should have this a and this a as well in string one we don't have any more a left in the rest of the string so till here or possibly it could be longer but at least till here our string s1 should be because that only will hold all the a's present in the given string so let's divide the string first to understand the problem statement better so here are the sub strings we have divided by considering the problem statement so clearly from here we can decode the problem statement mentioned that each character should be at most in one substring so for example if you see a we have started our substring s1 with a so this substring will have all the a's from the given string so here a and till here it has covered all the a's in the given string yes same way if you consider b so it had covered all the b's as well so there are two more b's in the given string and no more b's in the second of those string so that has been covered as well so again a and there is c so let's check if there is any c left after this character so if you see there is one more c here and there are no more c's left in the string yes which means this string has covered all a's b's and c's in the given string so that is what the problem statement says that it the sub strings should cover all the characters within itself no more characters should escape to other sub strings so again similar to substring one if you see substring two we have d e f g everything covered inside you won't find any of these characters left in the rest of the string same way h i j k all covered in this string s three so if you combine all three s one plus s two plus s three you will get the input string yes and we have to return only its length so the length of the first substring we have divided is nine and the length of the second substring is seven and length of the third substring is eight so hope you are understanding the problem statement now so let's see how are we going to approach this so as we have understood we have to cover a characters all occurrences within one substring so in order to complete that we have to first find the last position of any character in the given string so that we can think of where we can accommodate all its character within it so now if you see our uh yes starts with that the string starts with the character a so we have to first figure out what is the last position of a because by using that we should determine our first substrings length so if you see there are three more occurrence of a in given string yes and eight is the last position of a so we are updating a with eight and if you see we have three b's and five is the last position of b same way we are updating the last position of all our characters in the given string yes so this will help us to determine where our string es1 should stop and other substrings should stop so let's start with iterating each and every character and let's check whether we can accommodate all the characters within a limit so let's have a iterator i at very first character a so now we are going to iterate every time and update our variable j with the highest possible value so first we are iterating with our a so we have to check what is the last position of a and update our j which actually meaning to what is the last position of a says that till that at least our first substring should be because we have to accommodate all lays within this string so far our length of our substring is going to be 8 so that is what j indicates j is nothing but so far the size of our substring so we could put it that way yeah so now j is equal to 8 or i is equal to 0 so now let's iterate to the next position where i is equal to 1 so now our character is b so we are going to check what is the last position of b so if this b is exceeding this already existing 8 which means we should extend our length of our substring because we have to accommodate all the characters within itself already our size is eight so in this case we have to accommodate b as well so in that case we have to extend our length of our substring so obviously five is less than eight which means we can accommodate all the occurrence of b with an eight so we are sticking with our length eight so let's move to our next iteration which is having the character a again so if you see a is already been covered the maximum length of a is 8 so we don't have to change our substring because within 8 we can accommodate all our length so next again it is going to be b so we have covered b already so which is five which could also be covered with an eight so our next character is c so c is such a new character so we have to check its maximum last position so last position of c is seven which means we can accommodate all occurrence of c with an eight so we don't have to adjust our length so till now our length is going to be eight so the next character is p so now our iteration is at i is equal to 5 so now check b is equal to 5 we can cover b so now a i is equal to 6 so we did not reach a's largest position but we have 8 already which will cover all its occurrence so the next character is c whose last position is seven so which will also be covered by the length eight so finally we are moving to the actual iteration i is equal to eight where we have reached the last occurrence of a so now we have reached lo last occurrence of a which is 8 or j is also 8 which means we have reached the last position of our substring 1. how do we say it because our j is equal to 8 this is the maximum length we have fixed for our substring 1 so far so we have our iterator also have reached 8 which means we don't have any more characters that fits in this substring and we don't have any more characters that goes beyond this substring so whatever is present within 0 to 8 is present within the substring only we don't have its occurrence outside of this substring so we determine our result of our first substring is equal to of length nine because our position is eight but our array is zero indexed which means our length is nine so we are adding nine to our result array so sticking with this we are going to start our iteration fresh from the index nine because we have found a substring one so we are done with this string and its characters so we are going to start a fresh iteration with new characters so now going on to our iteration with d is equal to at position 9 our i is at position 9 and d's maximum occurrence is also 9 so now rj is going to be updated with 9 so we can uh fix a character by only this but let's continue and check the next character so our e is at position 10 so we are going to check if its last occurrence is going beyond nine so its last occurrence is at 15 so it's time to update our j to nine sorry to 15 so with ease last position so j is equal to 15 now moving on to our next iteration f so f's last position is 11 which will be covered within 15 so we are moving to e's last position is 15 g's last position is 13 which will also be covered within 15. so next character is d's last position is actually 14 i have updated it wrong here so 14 will also be covered as part of 15 so finally we reached e's last position is 15 our j is also 15 so which means we have reached the last position of our substring two so in this case we have to find our length of our substring already which is at uh 8 so 8 minus 15 is going to be 7 so we are updating 7 to our result so we have done with our substring 2 now rest of the substring is going to be rest of the string is going to be processed the same way to determine our length of our third substring or any more substrings we have in our result so now comes to the third iteration when j is equal to we are i trading for h's last uh position is 19 so our j is going to be 19. so we are checking for i's last position is 22 which is greater than 22 so our substring is going to extend till the position 22 so now jj's last position is 23 so again we are going to update our js equal to 23 so technically j is the last index 23 is the last value so even if you iterate them they are either going to be less than 23 or it is going to be 23. so finally our j is going to be 23 so let's do a negotiation from 23 minus 15 and the length is going to be 8 so we are going to update 8 here so this is going to be our result string and this is going to be simply achieved in the one pass solution by iterating the complete string in one go and updating our variable j and subtracting the length and updating our result so yes let's go to the code now so as i said we are going to first keep track of every character's last position so you can use any data structure as you like either you can go for a hash map or like i am going to do i am going to use an array character array to keep track of the last position so let me first declare j as i said we are going to uh our maximum length of string so far in this variable and variable anchor that is going to be our iterator to iterate our characters in a given input so we are going to iterate our given string by character and update our variable j with the last position of that character so we are going to check every time whether our j is equal to our i which means whether we have reached the last position of our substring if that is the case we are going to update our result with the length so anchor is a variable we move every time to the new position of the starting of our substring so once we finished uh calculating our length we are going to update it with the next characters index because that is when our next substrings first character starts so yes that's our finally our answer arraylist is going to hold our all our lengths so let's give it a try yes let's run oh yes our solution has been submitted and it runs in for milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
Partition Labels
special-binary-string
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
String,Recursion
Hard
678
305
to my YouTube channel and for this video we will talk about problem 305 this is the second iteration of number of Island and we will solve this problem using this joint set also known as Union find I want you guys to post this video to read the problem statement I'm going to make this mild assumption that you guys have seen this joint set or Union find in your algorithm class if not I want you guys to Google this and just to try to get the big picture of this what this is about towards the end I will talk about this but I really want you guys to um see like this concept called path compression I think that is a very beautiful implementation for this problem I came up with this position and here we have zero comma one comma zero two comma three blah and we have number of rows that will be five number of columns that will be four let's run this initially we are at zero comma one so we mark this that's zero comma one and number of islands will be one now we are at one comma zero that's this guy and number of islands will be two because these two are not connected for two comma three that's this guy well they are not connected so number of islands will be just three and here it gets interesting so we have three comma three and two comma three they are connected so the number of islands would be three not four we are at three comma one and that's this guy they are not connecting so a number of islands would be four and now we have three comma two that will make this guy a giant one single Island so we would have three for the number of islands and one comma one would be this guy and number of islands would be two because this guy is connected to this and this at two comma one that's this guy they will make this one single Island so number of islands would be just one and to solve this problem we will be we have to keep track of how many islands we have so far and you can technically use DFS at every single iteration but I think you will get time limit exceeded and that's that approach will be very slow so this is a problem where Union find will really shine and show its true potential so I create two arrays parent and rank and I also create a set let's call that Island so first let's talk about Island as we iterate on this position array we will be adding this zero comma 1 to our Island if when we are either when we are at this coordinate one comma zero we will add one comma zero to our Island this set so we will be doing that as we iterate on this position for parent and rank this is how I initialize so size here will be the size of this Matrix in this case will be just m times n number of rows times number of columns so initially all these index points to it themselves meaning that so let's look at this guy so parent of one is equal to one right this guy so this is what it means parents of one is pointing to itself so that's what it means however if we have something like this where one points to two meaning that one is a child of these two or two is a parent of one so parent of one is equal to two that's what this means where 2 is a I mean where one points to two so two is a root node of one that's another way of thinking about this another thing oh and for the rank just means how many nodes does this guy have including himself this one what is the rank of one it is just one the number itself what is the rank of 2 in this case you'll be this guy which is one plus this guy one so one plus one is two so rank of two is two because for this number two it has two and two nodes this guy and this guy rank up one here will be just one since we have a two dimensional like we have a two dimensional here but then our parent and rank arrays are one-dimensional so we have to find a way one-dimensional so we have to find a way one-dimensional so we have to find a way so we have to find the price action between them and the easiest one will be just we have a x times n plus y so for instance if we are working on say I don't know zero comma one here zero comma one that will correspond to the index one right there'll be X will be zero in this case and N will be four that's the number of columns the number of rows so zero times four plus one is just one if we are looking at one comma one there will be this guy that will be we are we should look at index five right zero one two three four five so yeah here we have Union function and find function and we are at here one comma zero as you can see so one comma zero and zero comma one they are not connected so we don't have that diagonal we um the only way two islands are connected is politically or horizontally we don't have diagonal parts so here's one thing that you have to remember when we are at one comma zero we can have up to four neighbors one two three and four this guy is invalid so we don't cons we don't think about this so among these three one two and three well they are not in our Island set in this case we do not run these two functions we run this Union function if and only if neighbors have valid coordinates and neighbors are in our Island set since zero comma 1 is not in our I mean since zero comma zero one comma one and two comma zero are not in our Island set we don't do anything here for now our parents and rank arrays stays the same they are not changed comma 3 and as you can see the its neighbors one two three and four this guy is invalid and 123. these guys are not in our Island set so we do not run this so this stays the same we are at three comma 3 is this guy we look at its potential Neighbors this guy and this guy well this is not a belly coordinate so we don't think about it we have this guy which is in our Island set in this case we have to run our Union function so let's look at this so we'll be running Union in this case P will be 15 to 15 is this guy and Q will be 11. Q is this guy so what is the root of P what is the root of 15 we have to run this function so they'll be find 15 and let's look at 15. well 15 is just this guy here we have 15 what is the root underscore Q that's just equal to find 11 which is this guy right you run this find function since 11 is equal to parent of 11 which is 11 so here we have 11. we look at the rank for both 15 and 11. both of them are 1. now since these two numbers root P root underscore p and root underscore Q are not equal we have what we have 11 and 15. so they are not equal so we have to make some modification well obviously rank 15 and rank 11 they are the same so we are in this L statement here we will be making some change to parent so parent of 15 we set it equal to 11 so that's what's going on here and rank 11 does this guy will become rank 11 plus rank 15 that will be 2. so what's going on here if you visualize this in graph so this is what we have 15 points to 11 is the parent of 15 and rank of 11 will be 2 because it has this itself and 15 so here we have 2 here and 11 points to itself so something like this and 15 points to 11 here this is the arrow and the rank of 15 Is Still the One right it's just itself here so for this guy we have three comma one and fortunately we don't have any neighbors that are in our Island set so there is nothing to do other than adding three comma 1 to our Island set at 3 comma two and that's this red tile if we look at this red tile obviously you can see that these two are connected and these guys are connected here we have something going on so let's try to run this Union function with three comma one that will be this guy so let's try to Union these two guys yellow and red we run Union 14 and 13. root underscore p which is basically fine this guy find 14 is just 14 right 14 points to itself so that's 14 and root underscore Q that's just fine 13 and 13. what is the parent of 13 that's just 13. and ranco 14 is just one rank of 13 is one we are in this L statement because they are not the same you know where we have root underscore p is not equal to root underscore Q so we are looking at this L statement parent of 14 will become pair 13 here parent.13 I mean parent of 14 will parent.13 I mean parent of 14 will parent.13 I mean parent of 14 will become 13. that's the change that I made and rank of 13 will become 2 because you are adding these two rank of this plus rank of this so we have two so that will be here rank of 13 is 2. and we have we still have to run this Union function so Union of 14 and 15. so root underscore p in this case will be 13. and root underscore Q is 11. with this rank of 13 equals 2 and rank of 11 equals 2. since they are not equal we have root underscore P at is equal to 13 root underscore Q is 11 so they are not equal and we are in this L statement too so we make the necessary change the parent.13 becomes 11 meaning that 13 parent.13 becomes 11 meaning that 13 parent.13 becomes 11 meaning that 13 13th parent is 11 so here if you look at here parent of 13 is 11 now and the rank of 11 will be 2 plus 2 equals 4. next we are looking at one comma one and one four one comma 1 we can connect these three islands all together the neighbors are zero comma one and one comma zero we will run Union of five and four first and then we will do Union of five and one Union of five and four there will be these two guys when you run when you combine these two we have to make the change to so we have to make change to parent of five that becomes four and rank of four will becomes two next you run Union of five and one and so this is what once you run Union of five and one we have parent of one becomes four and Rental four becomes three two comma 1 represent this guy the blue tile and in this case we have to run Union function Twice first one will be Union of 9 and 13. the second one will be Union of nine and five we knew two Union of 9 and 13 parent of 9 will becomes 11 rank of 11 becomes 5. and then when you run Union of 9 and 5 parent of four becomes 11 and rank of 11 becomes 8. that is this guy so that is really the key idea behind this problem yeah and let's look at my pseudo code for this problem my slow code for this problem and I made a typo here this one should be count so when I try this problem on my first try I got it wrong because I thought all these coordinates coming from positions will be unique but apparently it is there can be some repetition so if we have seen if we already have seen position and we can do that by checking whether if position is in Ireland then we have to append whatever we have to append count to our answer array and then we have to move on to the next one and we do that by having this continue in here otherwise meaning that position is unique we increment count variable by one we try all like four possible neighbors and those coordinates will be given by X tilde and Y tilde if x tilde and y t plus y till are satisfy this inequalities and X tilde comma y tiller is in Ireland then we have to run Union function if Union function returns false then we don't do anything else right when Union function returned force that means they are already connected so we don't do anything else so if Union function returns true what does that mean that means those we can connect position and we can connect the positions neighbor when you connect them we are so we are we have to decrement count variable by one because we are essentially forming one Island from two islands so that's what this is going on here and then when we exit inner for Loop we have to append whatever count variable we have to answer array and when we exit our for Loop we return the sense answer array that's it and that's the code for this Union and find and so this is the path compression this one line is a path compression unfortunately in our example we didn't have chance to see the full power of path compression so let's see a specific example of path compression so in the last step we are on two comma one and suppose we have a union of 9 and 14 instead of 9 and 13. so 9 and 14. well we have to run this Union function root underscore P will be just 9 because parent of 9 is equal to 9 but here root underscore Q is different we have to run this fine function with 14 as an input now we run Final 14 that will be parallel 14 equals find of 13 and we run final 13 here well we have to run find of 11 here again and find up 11 since 11 is equal to parent of 11 we return 11. and we send return we then that becomes apparent then we have parental 13 equals 11 right so we set parental 13 equals 11. and then we return 11. and we are at here so parental 14 will becomes 11. and we return 11 here so we have root underscore Q will becomes 11. so if you look at the if you look at this uh graph this is what we have initially so 14 points to 13 points to 11. 15 points to 11 and 11 points to itself once you run this find function we have this so 13 points to 11 14 Points 11 15 points to 11. every time we run this find function we are basically reducing this height and this is super helpful so this is path compression and so that is pretty much for this problem and let's see my code and this is what I what we get and that's for this video if you if my video helps you guys learning how to solve this kind of problem using Union find or disjoint set please give me a thumbs up and subscribe to my channel if there is some improvements that I have to make or if you have more questions you know you can write it in the comment section and I'm more than happy to respond to you guys thank you so much and have a great evening bye
Number of Islands II
number-of-islands-ii
You are given an empty 2D binary grid `grid` of size `m x n`. The grid represents a map where `0`'s represent water and `1`'s represent land. Initially, all the cells of `grid` are water cells (i.e., all the cells are `0`'s). We may perform an add land operation which turns the water at position into a land. You are given an array `positions` where `positions[i] = [ri, ci]` is the position `(ri, ci)` at which we should operate the `ith` operation. Return _an array of integers_ `answer` _where_ `answer[i]` _is the number of islands after turning the cell_ `(ri, ci)` _into a land_. An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. **Example 1:** **Input:** m = 3, n = 3, positions = \[\[0,0\],\[0,1\],\[1,2\],\[2,1\]\] **Output:** \[1,1,2,3\] **Explanation:** Initially, the 2d grid is filled with water. - Operation #1: addLand(0, 0) turns the water at grid\[0\]\[0\] into a land. We have 1 island. - Operation #2: addLand(0, 1) turns the water at grid\[0\]\[1\] into a land. We still have 1 island. - Operation #3: addLand(1, 2) turns the water at grid\[1\]\[2\] into a land. We have 2 islands. - Operation #4: addLand(2, 1) turns the water at grid\[2\]\[1\] into a land. We have 3 islands. **Example 2:** **Input:** m = 1, n = 1, positions = \[\[0,0\]\] **Output:** \[1\] **Constraints:** * `1 <= m, n, positions.length <= 104` * `1 <= m * n <= 104` * `positions[i].length == 2` * `0 <= ri < m` * `0 <= ci < n` **Follow up:** Could you solve it in time complexity `O(k log(mn))`, where `k == positions.length`?
null
Array,Union Find
Hard
200,2198
1,823
hello today we'll be working on Elite code 1823 find the winner of the circular game we're given a number called n an account called K what they want us to do is imagine that the numbers are in a Circle the numbers start at one and go up to the whatever value n is we start at one and we move a pointer around this Circle K amount of times K is how many spots we need to move when we start moving the pointer we include the number we start on so in the example they give us n is five so we have five numbers in K where our count is two so we start at one which puts our count at one and then we move to the number two and our count is now at two as well so we're finished counting because K is 2 and our count is two so whatever number we land on is removed from the circle then we repeat the process we start counting with the number right after the number that has been eliminated 2 was eliminated so we start counting at three for the next Loop the last number standing is the value we return so I'm going to show you two ways of doing this the first way we'll use a linked list and the second will primarily use math I'm going to show examples and solutions for each way of doing this all right using a linked list we can model the example that they've given us like this however you may notice that once we reach the end of the list we're at null when we create our linked list will make it a circular list by pointing the Tails next to the Head we can see that this models are diagram perfectly let's talk about what our algorithm will end up looking like so whichever node we're currently on will refer to as the current node and the node before the current node will be the previous node so we'll start off with our current node is one and the previous will be five so we'll start counting it one and move our pointer to the next node in the list until we've hit the same value as count each time we move the pointer we'll update our previous to whatever current was previously once we move K amount of times we need to get rid of our current node so how do you get rid of the current node so you get rid of the current node by pointing previous's next to the currents next like this then prepping for the next repeat of the algorithm we need to move the current to the currents next okay and we just repeat that process so our first time we started at one we counted one two and that removed two from the circle and we pointed the previous to three all right and then our current was moved to three so then we count three four is removed update 3 to 0.5 and move four is removed update 3 to 0.5 and move four is removed update 3 to 0.5 and move current to 5 as well then we have five one is removed uh the previous is next points to three and the currents move to three and we count three five all right so five is removed the previous will now point to fives next which is three and the current is also moved to three so at the very end of the algorithm when the previous and the next are exactly the same that's how we know that we're finished okay moving into the code so the first thing we'll make is a function for creating list nodes and this function is going to be similar to the function you'll see the code used for their linked lists the next function is create circular list this takes an amount of nodes we want to create we'll need a reference to the head and the tail of the list and then we'll default them to null so we need a way to create multiple nodes so we'll use a for Loop and loop for however many nodes they want we'll create a new node for our list and they want us to start counting at one so we'll add 1 to I so that makes our first node instead of it being zero would be one so if our list doesn't have any nodes yet the head will be null so the tail and head will both be the first node all right and then every loop after will update the Tails next to point to the node and then set the tail to this new node so once we're done looping we don't have a circular list yet to do this we'll point the Tails next at the head so this completes the loop then we just need to return the head and the tail and object or you could use an array as well now on to the main piece of the problem first if K is equal to one we can return n because whatever number we're on it would immediately get eliminated meaning the very last number of n would win we could leave out this line and it all work the same though so the next step is to create our list so pass n to create circular list and we can de-struct the head and the tail to can de-struct the head and the tail to can de-struct the head and the tail to be current and previous all right now we can play the game so let's create a while loop and we'll Loop while the current node is not equal to the previous node so if this is true that means we have one node that is pointing to itself which means we can return its value so in the while loop we'll create a for Loop and start I at one because we include our current node in the cow so one is account for the first node so I hope that makes sense so this will Loop K times each time we Loop we set the previous node to the current and the current to its next so after leaving the for Loop we'll update our pointers both our current node and previous next point to the current nodes next so go back to the diagrams if you need a visual of this updating the pointers removes the node from the list it's so it's out of the game when we finally break out of the loop we can return the value of the node for our answer so let's go ahead and submit this I heard dope our solution is accepted there is a better solution to this though so this algorithm would have a Time complexity of o n times K the space complexity of O of n so for each number in N we need to do K iterations and the space complexity is O of n because we create a node for each number um in N for the amount of n so I do have another solution this solution is focused more on math and it took me a bit of to visualize how this was working so we're going to start off with a recursive solution and understanding this recursive solution will help with understanding the iterative solution that will show you so let's say n is equal to 1 and K is equal to 2. so that means we have one person so if we have one person they're the winner because they're the last person in the group so knowing that if we add another person the winner of the two people will be K or two places away from the winner of the one person group so something I want you to keep in mind is that these numbers that I'm showing you represent the positions of the people not their actual original numbers like we've seen with the nodes and everything let's say n is equal to 2 now so we have a two person group and K is equal to two so we move two places again so previously the winner was one so we take that position and we count all right so one and then we count two and we're back at one because two was the last person so for a two-person group for a two-person group for a two-person group the person at the one position would be the winner all right so let's add another person so we have a three person group so one was the previous winner and we count two away from it so we two and then three so three is the winner here all right so we add another person so three was our previous winner and then we count the four and then we're back at one since four was the last person so one is the winner for a four person group all right one more time so we have a five person group one was the previous winner and count two away from it two three and three is the winner of the group of five which is the correct answer so the winner of a specific level is built off of the winners of the level below it so let's put this in the code we create a helper function that'll take n and K so if we're only at one person we return 0 because we're going to zero index our numbers all right and that's the position of the winner so zero indexing will help us with the next part of the algorithm and I'll explain more when we get there so if it isn't one person left in the group we'll do a recursive call with our Helper and we'll subtract one person from the group so we add K to the result of the call and this moves the result of the winner K amount of steps to the winner of that group all right so lastly we're and this is why we zero index is we do modulo n to the result of moving Our Winning position okay so we do modulo n to make sure our position is between 0 and N to keep it in the range so we can think of modulos looping our counter so we zero indexed so if we hit the last number in that group it takes us back to the very first position being zero okay so we'll Now call helper with n and K and since the number that we get back from our helper will be zero indexed we add one for the correct answer and that's it so here's a table for the recursive calls and the time complexity for this algorithm is going to be o of n because we do n amount of calls and the space complexity is O of n because we have to store each call in memory all right so moving on to the iterative version we're going to create a winning position variable that is set to zero because we're going to zero index again so if we look at the recursive table we can actually start our loop at 2 because setting I to 1 will always give us the zero position as the winner when we modulo it so the first Loop doesn't do anything to change our initial answer so to model the recursive version we say winning position is equal to winning position plus K in parenthesis and then we modulo I it to keep the result the answer in our range of the amount of people in the group all right which is I all right so once the loop is over we add one to the answer to make it one index I also made a table for the loops so in this case I included the first Loop to show us why we're not including it all right so I hope y'all learned something from this it took me a while to visualize what was happening with the later algorithms so hopefully you understand it now as well if you have any suggestions please leave a comment below and I'll see you in the next video
Find the Winner of the Circular Game
determine-if-string-halves-are-alike
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, and moving clockwise from the `nth` friend brings you to the `1st` friend. The rules of the game are as follows: 1. **Start** at the `1st` friend. 2. Count the next `k` friends in the clockwise direction **including** the friend you started at. The counting wraps around the circle and may count some friends more than once. 3. The last friend you counted leaves the circle and loses the game. 4. If there is still more than one friend in the circle, go back to step `2` **starting** from the friend **immediately clockwise** of the friend who just lost and repeat. 5. Else, the last friend in the circle wins the game. Given the number of friends, `n`, and an integer `k`, return _the winner of the game_. **Example 1:** **Input:** n = 5, k = 2 **Output:** 3 **Explanation:** Here are the steps of the game: 1) Start at friend 1. 2) Count 2 friends clockwise, which are friends 1 and 2. 3) Friend 2 leaves the circle. Next start is friend 3. 4) Count 2 friends clockwise, which are friends 3 and 4. 5) Friend 4 leaves the circle. Next start is friend 5. 6) Count 2 friends clockwise, which are friends 5 and 1. 7) Friend 1 leaves the circle. Next start is friend 3. 8) Count 2 friends clockwise, which are friends 3 and 5. 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. **Example 2:** **Input:** n = 6, k = 5 **Output:** 1 **Explanation:** The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. **Constraints:** * `1 <= k <= n <= 500` **Follow up:** Could you solve this problem in linear time with constant space?
Create a function that checks if a character is a vowel, either uppercase or lowercase.
String,Counting
Easy
null
1,849
Ajay Ko Hello Everyone Welcome to Lotus Camp Secretary and Other Interesting Problem Contest Which Split String into Depending Must Subscribe YouTube Channel and Considering Problem 05030 Number 4 O 90 Five for Entries Consecutive Dependent Arranged This Difference Between There Values ​​and Decreasing Old Values ​​and Decreasing Old Values ​​and Decreasing Old Students Where Is The Condition President Split String Into A Country Where To Listen To Return To 54321 First Number Two And 423 And 43432 21 Anagrams Of Subscribe Our YouTube Channel And Tap Hain Alphabets 14210 No Children Get Suggestions From Chronic Considering 5th Number What Is The First Number And 324 323 And 506 323 452 Number 2 And Considering Subscribe 430 First Number 2 F 2 The Circulatory And Imports From Starting Possible Number 2 And Its Present Condition Subscribe Complete The Subscribe Don't Forget To Subscribe Our Channel Queen Structure U Can Have Got Its First Number Four One Digit Number Which Is The Number One Digit Number And Width And Subscribe Our Channel Must Subscribe This Number And Conserve 12345 Vriksha Decreasing Number Chotu At Antioxidants Avoid Delay In Node For Exploring Subscribe For All Cars 2 F 3 Complete Seervi And Different Functions Subscribe Case Person Inside Channel Simply Ignore Friend David Last Not One Two Three Idiots 4999 Subscribe Don't forget to subscribe the channel and - 12th That Police Mot Ko Turn Seervi And Right To Health And Starts with Swaroop them third declaring long and Share and subscribe the Channel Please Click on the link for detail view Loot Templeton Shabd On Karo Yeh Humko Diclo Rakhkar Entry Loot From Bro And Good Night Mein Give Strength From Current Top Ten Plus To airtel and 132 213 adhoi subscribe value difference is joint press statement also fits presentation jab tum kaho ko switch on khol par madha knowledge reduce passing the sub string from i plus one thirty six children and sports events in his 4321 shower current field for Su Country A Good For Play Su Children Against Freud Subscribe To Parents Who Is Not Finally Return For U Ki Pure Set Recruitment Area Forest Condition That First Time Yar Exploring Route No Difficulty In The String In That Case Different Suno Difficult-1 Edifice Number 90 Suno Difficult-1 Edifice Number 90 Suno Difficult-1 Edifice Number 90 K SP Economic Sector With Different 121 Is For Parents Not Equal To Minus Point Parents Not Quite - To Subscribe And Parents Not Quite - To Subscribe And Parents Not Quite - To Subscribe And Order For All Should Not Be Satisfied In The Midnight Children Who Is Not Difficult To T&amp;C That And Parents Not Difficult - 110 That And Parents Not Difficult - 110 That And Parents Not Difficult - 110 Phases Of Test -2 Parents - Current 121 Surya Phases Of Test -2 Parents - Current 121 Surya Phases Of Test -2 Parents - Current 121 Surya Electronics Like This Loot I Let Submit That This Solution Person Is Updated On Android Sant Shiromani Sen Surprise For Watching Video Flight Video Like Subscribe And Let Me Know And Company Thank You
Splitting a String Into Descending Consecutive Values
maximum-absolute-sum-of-any-subarray
You are given a string `s` that consists of only digits. Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. * For example, the string `s = "0090089 "` can be split into `[ "0090 ", "089 "]` with numerical values `[90,89]`. The values are in descending order and adjacent values differ by `1`, so this way is valid. * Another example, the string `s = "001 "` can be split into `[ "0 ", "01 "]`, `[ "00 ", "1 "]`, or `[ "0 ", "0 ", "1 "]`. However all the ways are invalid because they have numerical values `[0,1]`, `[0,1]`, and `[0,0,1]` respectively, all of which are not in descending order. Return `true` _if it is possible to split_ `s`​​​​​​ _as described above__, or_ `false` _otherwise._ A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "1234 " **Output:** false **Explanation:** There is no valid way to split s. **Example 2:** **Input:** s = "050043 " **Output:** true **Explanation:** s can be split into \[ "05 ", "004 ", "3 "\] with numerical values \[5,4,3\]. The values are in descending order with adjacent values differing by 1. **Example 3:** **Input:** s = "9080701 " **Output:** false **Explanation:** There is no valid way to split s. **Constraints:** * `1 <= s.length <= 20` * `s` only consists of digits.
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
Array,Dynamic Programming
Medium
53
1,898
hi everyone welcome back to lead coding i'm your host faraz so i have decided to make detailed solutions to the lead code weekly and bi-weekly problems bi-weekly problems bi-weekly problems so here it is the contest number 245 and we are going to solve problem number two and problem number three so first of all let's start with the problem number three it was simpler than problem number two i guess many have solved this so now before moving forward if you want to get hired in the top tech companies like facebook google microsoft amazon then you need to check out interviewing dot io you will practice realistic coding interviews with senior engineers working at these places they will give you detailed feedback on exactly what you have to work upon interviewing dot io have the largest network of experienced tech interviewers in the world so you can book an interview with as little as 24 hours notice and the best part is you don't have to pay until you get hired so i have provided the link in the description you should definitely go and check it out we are given a triplet the target triplet and this we have to generate from the given set of triplets okay you must have read the problem statement carefully so what i came up during the contest is let us say we have a certain triplets and first the first observation is the first operation is if we have two triplets x1 x2 x3 and y1 y2 y3 and we merge them we know after merging it will be maximum of x1 y1 maximum of x2 y2 maximum of x3 y3 okay and let's say this is the resultant that is z1 z2 z3 okay now this is this was the first triplet this was the second triplet this is the resultant triplet now let us say we have the third riplet and that is a1 a2 a3 now if i want to merge this with this it will be maximum of z1 a1 z2 a2 z3 but this same operation the same operation is equivalent to performing the merge operation between these three taking the maximum of x 1 x 2 taking the maximum of x 1 y 1 a 1 x 2 y 2 a 2 x 3 y 3 a 3. okay so instead of merging 2 then merging uh then merging the result with another one we can simply merge these three all together all right so i hope you understand what i mean to say this is the first observation now the second observation is let us say we have a target and the target is a1 a2 a3 okay we want to generate this and we have a set of triplets now let us say we have a triplet x1 x2 x3 and the value of x1 is greater than a1 okay so can we take this triplet into account is it usable for us can we take it into our account no we cannot because once this x1 exceeds this a1 we can never get a1 again okay because we always have to take the maximum operation that is why if x1 is greater than a1 then we have to discard this triplet this is of no use for us similarly if x2 is greater than a2 this is of no use of this is of no use for us and if x3 is greater than a3 then also it's of no use so we have we are going to discard it in any of these three cases okay so this is the second observation now talking about a third observation so yeah so third observation is let us say we have y one y1 y2 and y3 this as a triplet okay now the value of y1 is smaller than a1 the value of y2 is smaller than a2 the value of y3 is smaller than a3 so if we take this triplet into account is it anyhow going to affect the result will it disturb the result okay the answer is no it is not going to disturb the result because there might be some another triplet that will absorb this after merging it will get absorbed but yes it is not going to disturb us so we can take this into account okay although it's of no use it's of no benefit but still taking this into account is not going to harm us so we can divide all the triplets which are given to us in two classes okay this is the class number one this is the class number two whatever triplets are given to us we can divide it into these two classes and this is the target triplet a1 a2 and a3 now let us say there is a triplet that we are going to check and in that triplet we will check if the value of the triplet uh let me denote it by x x1 x2 x3 if any of these values x1 or x2 or x3 is greater than their corresponding a1 a2 or a3 then we are going to put it into this class the class number one discarded okay then second class we can take this as taken okay taken and rejected is a better word here rejected okay so if any of these values uh if x1 is greater than a1 or x2 is greater than a2 or xp is greater than a3 then we are going to reject that okay because it will take us far away from the result and we will never be able to come back to the result we will never be able to achieve our target then the second class is the rest of the triplets which are remaining comes into the second class okay so whatever is not rejected comes to the class taken all right now as uh we discuss the first condition that we can merge them all together so whatever triplets we are we have taken we are going to merge them all together using a for loop okay and then finally check that if the resultant of this taken is equal to the target if it is then we are going to return to otherwise we are going to written false let me just show you the code it will become bit more clear so this is the result this which i want to generate now if the triplet is 0 is greater than or equal to if it is smaller than or equal to it means taken okay this is the condition for taken right the target is either greater or equal to the corresponding index in the triplet okay this is the condition for taken and we are going to merge them all together okay result of 0 is maximum of result of 0 and targets i 0 results 1 is equal to maximum of result 1 target i1 and so on these all are taken now finally i will compare whatever i have taken and after merging i got result i will compare the result to the target and then return it i hope this is understandable it is clear so these are three conditions that came up to that came in my mind during the contest and i came up with the solution so now let us talk about the problem number two and i think this problem was a bit tricky and yes many people were not able to solve this so uh yeah let me just show you what i came up during the solution i mean during the contest so what we can do is we can check one by one okay the first thing is we should know to compare whether one string is a substring of another one and how to do that comparison so it is abc acb a b c a c b this is the first thing we should know how to check if one string is a substring of another one okay subsequence okay so uh to check if one string is a subsequence of another string what we need to do is we need to assign two pointers okay and then keep incrementing them like if we are going to compare these two if these two are equal then we will be incrementing both of these i will come here j will come here similarly if these two are equal then we will increment i will come here and j will come here now j exceeds the range of this string so we will exit and we will say that yes a b is a subsequence of abc acb okay let me take something bit more complex here let us say i want to find the substring aca okay aca i want to check that if this is a subsequence of the given string so this is my i this is my j now these two are same so we will increment i will come here j will come here these two are not same so what should i increment i should be incrementing i not j because this we have to completely cover okay but we can skip some indices in this string s in p we have to cover all these indices so now j will stay here and i will go here now comparing these two are same so i will also increment j will also increment this is how you compare that if two uh that if one string is a subsequence of another string all right after that what we can do is we can go one by one okay we can start with k is equal to zero when k is equal to zero i can remove the third index okay so which index will be removed 0 1 2 3 a will be removed and we will be able to get a b as a substring abs subsequence okay after that i will take k is equal to one so i can remove one and three i will remove one and three so b will be removed and a will be removed but we still got a b as a subsequence okay so let me just take this example this one so this is the given string s then it is abcd and we can remove three two one four five six okay so first of all i will try to remove this three so zero one two three this is removed can we get abcd a b c d yes we are getting abcd okay so k is equal to zero we are getting the um we are getting p as a subsequence of s now check for k is equal to 1 in k is equal to 1 we can remove these two so 3 and 2 will be removed 3 is removed and 2 is removed now can we get a b c d we are not getting a b c d so k is equal to 1 is the answer and anything after this i mean we should stop at k is equal to 1 so yeah k is equal to 1 is the answer wait a second um if we remove the first index see it is not longer after removing the index three this becomes this okay a b series subsequence of this maximum k you can choose p is still a subsequence so we should choose such a k that p is a still subsequence so after removing 2 and 3 so this is 2 and this is 3 after removing the character at the index 3 this becomes this is still a subsequence so we are able to remove this okay all right i got it so we have to actually tell that how many k's can we how starting from this position it is actually one index okay instead of zero indexing it is one indexing so k is equal to zero is acceptable that means one element is acceptable we can remove one element from here so we are returning when is the answer all right so instead of this i should have written k is equal to one and k is equal to 2. so k is equal to 2 is failing k is equal to 1 is accepted that is why we can return k is equal to 1 as the answer i hope you understand this so we are going one by one okay we are checking for k is equal to 1 then we will be checking for k is equal to 2 then k is equal to 3 then k is equal to 4 and as soon as at a particular k we find that p is not a subsequence of s then we are going to stop here and we will return whatever is previous to this okay all right so let us say if we stop at k is equal to 5 we will be returning 4 as the answer now we are going one by one okay this is a kind of a linear search we are linearly searching the solution first of all we tried with one then two then three we are linearly searching the solution starting from one but we can do the same thing using a binary search as well all right so this is how the intuition of binary search comes in like for once you are doing a linear search and then you will see that if you make a binary search okay instead of selecting uh one by one if we some select somewhere in the between and we removed all these elements okay and then we check that if p is a subsequence of s after removing these elements from s if we are getting the answer as yes that p is still a subsequence then we can say okay um we can try removing some more then our s will become mid plus one otherwise our end will become minus one all right so let me just show you the code this is my start this is my end okay this is my mid and this is the condition which i am checking if it is still a subsequence then of course mid is my answer this is not my exact answer but this could be my answer then star is equal to mid plus 1 otherwise n is equal to minus 1 all right and then checking the condition as i told you so first of all i'm putting something i can put anything here maybe a question mark or something maybe a dash or a question mark here so that will denote that this position we cannot use this particular position all right it will denote removed from 0 to k i will remove everything in s okay then we are comparing in a similar way that i should just demonstrated with the help of an example so this is how you compare all right so this is it for the video i hope you like it i hope you understand it and you can code it out by yourself so thanks a lot guys
Maximum Number of Removable Characters
leetflex-banned-accounts
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters from `s` using the **first** `k` indices in `removable`, `p` is still a **subsequence** of `s`. More formally, you will mark the character at `s[removable[i]]` for each `0 <= i < k`, then remove all marked characters and check if `p` is still a subsequence. Return _the **maximum**_ `k` _you can choose such that_ `p` _is still a **subsequence** of_ `s` _after the removals_. 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. **Example 1:** **Input:** s = "abcacb ", p = "ab ", removable = \[3,1,0\] **Output:** 2 **Explanation**: After removing the characters at indices 3 and 1, "a**b**c**a**cb " becomes "accb ". "ab " is a subsequence of "**a**cc**b** ". If we remove the characters at indices 3, 1, and 0, "**ab**c**a**cb " becomes "ccb ", and "ab " is no longer a subsequence. Hence, the maximum k is 2. **Example 2:** **Input:** s = "abcbddddd ", p = "abcd ", removable = \[3,2,1,4,5,6\] **Output:** 1 **Explanation**: After removing the character at index 3, "abc**b**ddddd " becomes "abcddddd ". "abcd " is a subsequence of "**abcd**dddd ". **Example 3:** **Input:** s = "abcab ", p = "abc ", removable = \[0,1,2,3,4\] **Output:** 0 **Explanation**: If you remove the first index in the array removable, "abc " is no longer a subsequence. **Constraints:** * `1 <= p.length <= s.length <= 105` * `0 <= removable.length < s.length` * `0 <= removable[i] < s.length` * `p` is a **subsequence** of `s`. * `s` and `p` both consist of lowercase English letters. * The elements in `removable` are **distinct**.
null
Database
Medium
null
394
Jhaal Hello Viewers Welcome To Your Consideration Question Record Friends In This Question Were Wedding Invitation To Its Subscribe Now To Receive New Updates Subscribe Mode Turn On Vivah Aisi Subscribe Tablet To Candidates Selected In Description When Skin Use Subscribe And Subscribe Channel Subscribe The Students Code-word tha malang staff Students Code-word tha malang staff Students Code-word tha malang staff meeting hai how to time main tera natak an alarm set to old send a 's return got k newly appointed to howrah train builders' newly appointed to howrah train builders' newly appointed to howrah train builders' sign oldy a temporary server error that in the rig ritual should be the waste related on number nine Ho tomorrow morning candy hui support aap character into dustbin profit for the quarter digit to an album add open rocket to send close button to allahabad subscribe kithar hai ko one here vipin always us character is digit with oo main safe hai and instead of this product in Milk down album vid oo the current se FD the number bill ki datt wali hoon to reason number candidate ne nols uber app kyun na ho hain sapoch ye calculated ateek hai next to in the open market ko subscribe button ko subscribe to me negative point 2 nov22 Chief subscribe and subscribe the Video then subscribe to Tags grammar bcd into a temporary ab electronics me plant previous key value me to house number Services suggestion vid oo tomorrow morning and 1000 notes mintu up and temperature dipped into a narrative was interrupted half an hour I want to complete this electronic cigarette, subscribe to that health and boy to that and activist shot dead Nandkumar support, I am slow, this is the cost, slap, submit, happiness and prosperity. Thanks for watching see the question.
Decode String
decode-string
Given an encoded string, return its decoded string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`. The test cases are generated so that the length of the output will never exceed `105`. **Example 1:** **Input:** s = "3\[a\]2\[bc\] " **Output:** "aaabcbc " **Example 2:** **Input:** s = "3\[a2\[c\]\] " **Output:** "accaccacc " **Example 3:** **Input:** s = "2\[abc\]3\[cd\]ef " **Output:** "abcabccdcdcdef " **Constraints:** * `1 <= s.length <= 30` * `s` consists of lowercase English letters, digits, and square brackets `'[]'`. * `s` is guaranteed to be **a valid** input. * All the integers in `s` are in the range `[1, 300]`.
null
String,Stack,Recursion
Medium
471,726,1076
1,582
That welcome back guys loot problem 1582 special position in binary matrix so if you have already subscribe my channel please subscribe my channel subscribe our create list code solution videos in java j2ee technology this website create videos to help people you know in Rahta J2 interview time Mom Please subscribe The Channel That Sort of a Good Videos Regarding Like You Preparing for Java Interview Repair Learning Java Coding Interview This Will Help You Should No Entry No Problem Rose in Two Columns Matrix Amazing and Return Number Special Positions in Matrix Positions Subscribe More Elements In Roy and 40 Hussain Column0 Intact Example Governor Some Example to Reduce Example Over Here and Awards and Discuss How Are Going to Solve This Problem So Amm A Hai So Aditya Input Matrix is ​​Given to Us and Who Have to Find So Aditya Input Matrix is ​​Given to Us and Who Have to Find So Aditya Input Matrix is ​​Given to Us and Who Have to Find Out How Many Special Positions in The matrix late night so special position means in this matrix have to find out number of vansh for example this one where all the elements in others a cigarette one is from 0share and here it's 90 can not be counted as one died because this one is their song With special one hair for example this one special one rate fix hair this knowledge actually column everything is hero except one and five to hind this disease everything is hero except one should be given special show will contain some one special and when you look at this One right aa member only one right vikas this one is not special classes or ok but this year the reservoir in this call vinod special song 2018 special position means little one and on element sex update element is heroine the truth and in the column basically 154 brute Force approach you just get a great the matrix and whenever you see one uses go come into a row and column and find out if all the elements are there and in the row and column times but this account of time consuming effigy of matrix right now you have Lot of world and always you have to go and looked into the complete row and looked into the complete column for example if you're looking for this one you will look into this row and you will look into this column right solves your love for everyone you No How To Do It Say It Is Time Consuming Software Go Into As We Are Going To It Is The Matrix And Win For Create Two Of Your Matrix Point To Solve This Problem By Two One Is Doctors And It Will Be A Great Size Request Number Off daily to for example surat me 10 back distance between clear press karenge ok so aam hai to hai jukham auspicious and this number of like share number and screenshot it is like three basically rs atri and number of columns utari hui create to our later this helping Aa metrics and they are going to straight through each row and population the prometric writes over romantic jewelry for example disavar prometric shul se rot and 2008 is equal to will calculate how many balls are there in districts of that will calculate number of verses in this row One and two right solid is to-do row One and two right solid is to-do row One and two right solid is to-do that Sushil early will calculate how many zero skin raw one so that you can see this two and again will calculate how many than 1000 der in which two index right 34.06 to 13 34.06 to 13 34.06 to 13 2010 and similarly you Will Earn Popular Tower Column Matric Shirt Column So Now Institute Of Provisioning Calculate How Many Say 1000 There In The Column 1 Column 0590 Only 108 Dushman Sui A7 Similarly Column Awal Se Valve 1230 Morning Spent Share And A Column 2 A Column To Hai 10 2018 So Will Just To Hear Someone You Ever Done With Populating Row And Column Matrix Previous Literature Through This Khol Matrix You And You Will Like For Example For Air Show Will Look Into Power Leg Ishwar Disposition Is 0410 So In This Position Will Look Into Do Zero Year And They will check if they remember site civil request number 90 number of columns minus one five number of columns is 3 minus one is two so it's not points 3425 now you will check how many balls are there in column 1 column 000 one so it's not Equal to 8 and equal to number of do - 116 20122 but it's quite number of do - 116 20122 but it's quite number of do - 116 20122 but it's quite boiling not contingent basically night sweats and like water save you soon after this was done too will go to dushwar awadhesh shuddh desi romance position is the one come to right one is X Raw One Is My End To This Is Why Bigg Boss Your Whittaker Look Into The East Way You Can See A Prolific Positive 3 - Column Is Three Point - Voice To Positive 3 - Column Is Three Point - Voice To Positive 3 - Column Is Three Point - Voice To Software Good Care Love You To The Volume Two Columns To Also Hui Have To Right Two is the number of - Vansh Utari - 120 Will Count This number of - Vansh Utari - 120 Will Count This number of - Vansh Utari - 120 Will Count This Vansh Special Position Rights Over Special Position v5 Vivo Fear For This Can Reduce 120 Ma 210 Bhavan His Second True And Viruddh Columbus Girl2 Ko Ma0 Show Will Go Into The Controversy Control Figure Ko Hee Air Tight Day Two Shoulder Good Year But When They Got To The Columns Row And Column End Is Not Free - The Columns Row And Column End Is Not Free - The Columns Row And Column End Is Not Free - Tubelight 20 Raw Iron Minus One Fit You But Not Least One Son Will Account Is Vansh Hongi One Is This One Is Our Special Position In This Matrix and you can see servi and destroy you have all elements zero and in this column so you can see all the elements 800 one has special position this is the way we are going to approach this problem and solution is much better than you are like if you Are doing brute force on Thursday increase element in matrix android first column for everyone should read this explain in solution in hospital method that Ravita little bit of extra storage for this row and column matrix strip spoon batter solution so let me show you here how friend Implemented Gift First Meeting Account Dr To * Return Din Hui What Like And Such Dr To * Return Din Hui What Like And Such Dr To * Return Din Hui What Like And Such Things Number Of Frozen Columns In Matrix And They Created This Romantic Mix It Is Equal To Number Of Rose 11 Equal Matrix Is Number Columns Share And Hui Rassi Operating This Matrix And Vr Populating Romantic Sharif Swain CIA's Amazon 0 Justin Guru Of I Plus Software Positive Dharo Matric Share And In This Quest For Truth In Vwe Polytechnic College Matrix Years For Example Will You Can Reduce 101 Will Be 1205 Against Column0 Likes And 250 Cutting The Calling Matrix When You Reach Care Hui Already Have Proven Column Matrix Ready-to-Use So Will Know Its Purpose That and Wherever Hui's Ready-to-Use So Will Know Its Purpose That and Wherever Hui's Ready-to-Use So Will Know Its Purpose That and Wherever Hui's Rebellion The Matrix and Wherever They Are One Here Will Just Check in Our Rok Slideshow Axis Basically Came and Row Position Rights on Roof Accident Bhusi - Bhusi - Bhusi - 121 Truecaller minus one right column position should be equal to the calling difficult-2 be equal to the calling difficult-2 be equal to the calling difficult-2 number Firoz minus one basically tight remember increment account and the end they are going to return account right shoulder is the logic that they are using two shoulder If problem is common then this point is clear it is also always been on maximum with column -1.4 example2 or blood on maximum with column -1.4 example2 or blood on maximum with column -1.4 example2 or blood hair and you want to check country that number and columns more volume matrix will also be used for this rights will check for this row suvatio total Number of Columns - suvatio total Number of Columns - suvatio total Number of Columns - 1383 Remind Me to the Calling Check Like This Column 1 Column 2 - - - - Total Craft -1.2 Basically Subscription On 234 So That Console Special Positions in Binary Matrix Solution Hui Discussed Here is Much Better Solution The Group Course With Little extra storage and as you can see you are just doing author of name boy dance number of throat and in his number of columns and ear also a boy doing so total time complexity for this solution of birth MB in right short complexities order of fame* In it's a complexities order of fame* In it's a complexities order of fame* In it's a game is number of throat and in is number of columns of the metrics and space complexity care yes will be order of one vikas hui are not using in it's an order of the new year using person storage for this number of rows and columns Aa but this is just like and share maximum you can see like also in comfort online order of phoenix you can calculate relative both are same ho number frozen number columns in this request using this month special choli but which scanner for not much it is not live Without Using Any Special Data Structure Or Anything So And Dissolution Egg Or Solution So Let's Children Work Code And Maturity Spot Setting On The Test Case Status You Want To Use 284 Vacancy Puriya Cutting The Correct Result For Word For These Test Cases Submit 116 Fashion Gold Accepted By It's Good For This Is The Way Can Solve Special Position Reminder Matrix If You Have A Quality subscribe To My Channel Please subscribe To My Channel Now My Channel Like Share And Creating Like Lord Of Good Videos For Java j2ee Interview Material Edit Solution Singh Jhawar Please subscribe thanks for watching a
Special Positions in a Binary Matrix
design-browser-history
Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._ A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**). **Example 1:** **Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\] **Output:** 1 **Explanation:** (1, 2) is a special position because mat\[1\]\[2\] == 1 and all other elements in row 1 and column 2 are 0. **Example 2:** **Input:** mat = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\] **Output:** 3 **Explanation:** (0, 0), (1, 1) and (2, 2) are special positions. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 100` * `mat[i][j]` is either `0` or `1`.
Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ?
Array,Linked List,Stack,Design,Doubly-Linked List,Data Stream
Medium
null
1,732
hello everyone welcome back here is vanamsen and in today's video we are going to tackle interesting problem find the highest altitude we will try to solve it in Rust uh so the task is to find the highest altitude given an RI that represent net gains in altitude between points so let's start our implementation in Rust so let mood Max altitude will be zero and let mutable current altitude B 0 and 4. G in gain eater current altitude plus gain will be current altitude greater than Max altitude so max altitude will be our current altitude and yeah so and finally Max altitude will be returned so it's really easy implementation so let's run it and see if it's working so uh hopefully it does so yeah we have successfully solved this case so we are starting from the sea level so it's zero and then it's minus five one uh minus yeah five zero minus seven so maximum altitude is uh one we have reached uh so yeah and it's uh after the five so then we have like maximum altitude of one and we store uh our maximum altitude in variable and we Traverse it only once so the time complexity is just o n and uh space complexity is just uh o one so it's constant because we have two uh mutable constant and yep uh that's it so now let's run it for unseen test cases to see if it's working as well so yeah we have successfully solved it and our implementation beats 100 of rust implementation so it runtime zero millisecond so it's really efficient and yeah memory a bit six percent uh but as you can see all working as intended so uh yeah I hope you find this uh video useful and uh if you do please uh make it a like and also subscribe for more coding challenges and tutorial uh in Rust and as usual keep practicing and never stop learning happy coding and 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
205
of easy legal question isomorphic strings giving two strings s and t determine if there are subformic and two strings they give you s and t egg and add or can um two strings or isophonic if the characters in s can be replaced to t all occurrence 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 yourself and here is the example s string is act and add and you can replace e with a and if you replace g with d and the things the mapping is already gmat mapped to d right so the next g has to be replaced by d as well that's why here returns true and then if you look at the second example is that the f mapped to b and o mapped to a at the beginning and then the next o should be mapped to a as well right but it tried to map to r so that's why it's not working so it's false and um the next example p-a-p-e-r and you can see 2-p is mapped p-a-p-e-r and you can see 2-p is mapped p-a-p-e-r and you can see 2-p is mapped to t and the rest are mapped to two different characters that's why it returns true and there are some constraints here and um s and t consists of any valid ascii character and you can see this is a question asked by amazon seven times in the last six months although it's an easy question but it's definitely a question worth practicing on and you can see that this question has quite some dislikes because i do feel that the description is a little bit confusing and let's take a look at the example is if e uh like the ag and add if e mapped to uh a and uh g mapped to d right the mapping is there already and the next example is f mapped to b and um o mapped to a and then at this point that we try to check o map to r then it's not working in this case um so you want to make sure the mapping works when you map e to a and g to d and also the mapping should work uh for the uh t character map back to s the asian map to uh e and the d e map to g that should work as well so to solve this kind of question is that if we check just check the unique character if we're thinking about using our um set then we can basically use the set to check the real of the real characters we don't care what exactly it's mapping to but then if we use our set to check the string s and then we can see that uh the length of the set string let me do it this way um so the length of this if we try to get the set of the s string it's eg so basically it's two right and if we try to get the length uh if we put a t in a set and then we try to get the length of the t is two is not three because they're duplicate characters and they should equal to each other right the other thing is that if we um zip so there's a python function and you can zip st together and if i do s and t it the output will basically look like e a g d it's basically zip them together one character from s1 character from t like put them together right if i do a set of this the length will be two as well because it has e a g d and then gd because gdgd are duplicate uh when i put in a set then there will only be one gd so the length will be also be uh two so essentially they should equal together as well so what i'm really looking for is that if the length of if i put all of them in a set it's all um the same length that means that the mapping is correct there are isoformic strings right um if that makes sense to you uh force return zip length oh sorry this should be length of the set so the length of the set of the when i zip them together should equal to the length of the set s string and also the t string let's run it yep um this should be probably the most easiest the code the shortest the code to how you can write this but just in case that if you are asked um this in the interview and the interviewer said oh you're not allowed to use the put in a set and you're not allowed to check the using the length to solve this problem and you have to use something some other method so i'm going to show you how to use how to solve this question by using a hashmap so essentially if you want to use hashmap is that you want to have two hashmap and a one contains the mapping as to um s2t right and then the other hash map i want to store the mapping as to t2s basically like what i uh described earlier so if uh there is so i'm going to go through every single string in every single character in snt right if the charac if any of the character is uh if the character in uh s from the a string is in the mapping but the mapping does not equal to is what the string uh what the character is supposed to map to or the character is uh the t character is inside of the um t mapping but it does not map to the right character as a different character in s1 than our written force in that case otherwise i'm just gonna put a correct mapping what i want to map is for this mapping i want to map the character one basically i want a c1 i'll put c1 in s and um c i'll call the character two a c two in uh as refer to all the character in t and if they the mapping does not exist at all i'm gonna set the entire mapping after i go through all the entire uh character each every single character in s and t if um if uh everything is there then i'm gonna return true it's what i expected right and i'm gonna show you how to do this code in code and you will see this more clearly so i'm gonna have two hash map um two mapping basically s2t and t2s this is how i map i'm gonna map all the characters together and i'm gonna still put uh c1 in c1 is referring to the character in s and c2 is referring to the character uh nt and then s2t is the mapping from s to t and the t2s as the mapping from t2s just like its name and for c1 c2 in zip this is the same python function as t right um i want to zip them together in pairs so basically every single character in c1 and c2 if one thing uh one scenario is that if c1 in s two t so sorry if c the character one is in the s2 t mapping and the s2 ts um c1 if the value is not mapped to 2 c2 so it's supposed to map to c2 but if it's not mapped to c2 i want to return force in this case right there's another scenario is that if c2 in t2s and so basically the second character is in the t2s mapping and the t2s c2 but it's not mapped to c1 if that is the case or it should be all so either one of the case is true then i'm going to return force in this case and if none of this um is now the scenario is like this and they don't exist or they're not there then i'm just gonna ma do the mapping s2 t i'm going to map c1 to c2 right and t2s and i'm going to mapping map character 2 to c1 in this case and eventually after i the for loop go through the everything um then i'm going to return true in this case yep if you think that this is helpful please like my video and subscribe to my channel and i'll see you with more legal questions
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
179
hi i am ayushi rawat and welcome to my channel today we will discuss the september lead code challenge week 4 problem largest number now let's have a look at the problem statement let's see what it says given a list of non-negative integers given a list of non-negative integers given a list of non-negative integers arrange them such that they form the largest number okay now let's have a look at the we have an input which reads 10 comma 2 we have 2 elements here and the output is 2 1 0 okay so basically we have to return the largest number the idea behind is it's like we have to construct the largest number and at the same time we have to ensure that the most significant digits are occupied by the largest digits we cannot just simply arrange it into descending order because in that case we will be returning 1 0 2 because 10 is greater than 2 so we look for different approach here note the result may be large so if we need to return a string instead of an integer ok the next example says we have an input array of 3 30 34 5 and 9 okay and the output here reads 9 5 3 4 3 0 is our output string here let's move forward to the solution it would become more clearer to you once we could so initially i will return an empty string if our length of the array is 0. next i'll run a loop over our length of array now i will run another loop from x plus 1 to length of numbers here now i'll declare two variables here i n j i'll convert nums of x into i and nums of y into j so i'm doing this for each iteration i'll run an if condition checking if int of i plus j is less than j plus i in that case i'll swap the numbers now i'll check the condition if nums of 0 equals to 0 that case will simply return 0. remember we have to return string 0 here now i will declare another variable result here and initialize it with empty string next i'll declare a counter variable and initialize it to 0 now i'll run a while loop for condition until count is less than the length of numbers here i am updating the result variable and at last i increase the counter by one once done i can return the result at last now let's try running a code now let's try submitting it and it's done you can join my discord server and telegram channel for regular updates you can find the code at my github repository link is available in the description box below if you wish to connect with me on other social platforms the link is mentioned in the description box below if you have any queries or suggestions please feel free to ask if you like the video hit the like button and subscribe my channel thank you for watching
Largest Number
largest-number
Given a list of non-negative integers `nums`, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. **Example 1:** **Input:** nums = \[10,2\] **Output:** "210 " **Example 2:** **Input:** nums = \[3,30,34,5,9\] **Output:** "9534330 " **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 109`
null
String,Greedy,Sorting
Medium
2284
160
all right hey what's up guys it's fond and we're going over top interview questions medium set linked list question number three intersection of two linked lists so given the heads of two single linked lists heads a and head b return the node at which these two lists intersect if the two linked lists have no intersection i'll return no so in this case go through a and b and you see that they intersect at c1 right the node c1 over here they intersect at node eight so you just return eight over here they were intersected two over here they don't intersect so you return null and they give you a whole bunch of constraints um about the elements in uh list a and list b yeah so i want to give you guys the first solution that came to mind for me so this solution was a pretty simple one where you use a hash set so you may be thinking bob how are you going to use a hashtag for list nodes because list nodes are defined recursively by defining the next one right so you're thinking how much space would you have to allocate in each position the data structure wouldn't know you can't make like array of list nodes and thing is you can the thing is with java they don't really uh ex they don't really let you discover yourself the concept of point so pointers is basically it's an address to the object so for a hashtag you need to know the size of the object you're storing so if there's the int it's 64 bits and oh 64. all right and if it's char it's eight bits and this basically tells the high set how many spaces should allocate so i have to i think they originally have a side to like 10 but whatever it tells you how much space you should allocate for each integer but if it's a list node it can be defined recursively it could be a huge length you have no idea what how much space you should allocate so most of the time well actually all the time when you have an object java actually converts it to an address when it's using a data structure so even though it says list node here it's actually storing a pointer to a list node so that's why it's really important you should learn concept such as pointers by picking up c or c plus which are also very useful languages so last idea you go through one linked list and store all the pointers that you see all the nodes that you see and go through the second linked list and see if you find any values in the hash set and that's exactly the solution i have over here so over here i go through uh list a and i store all the nodes so i add to a hash set and then i go through list b and check if the highest set contains any of the same nodes so if it does that means there's an intersection right and then you just return the node where you intersect that otherwise you just keep on erroring through and return to otherwise so let's see the situation so over here through a you store it one nine one two four these notes really storing the addresses but who cares and in list b goes through three and then you see two is in this hash set so you can return the uh list node two perfect right so but the follow up is could you write a solution that runs at o in time and only uses all one memory and this is the actual interesting part of the problem otherwise this problem would be pretty trivial so for this problem there's two aspects there's the list a and list b which are the two singly linked lists so the two aspects are the lengths so either they're equal or not equal lengths are not equal lengths and the second one is whether they intersect that's just a yes or no and with this you can get your four cases so the links are equal and they intersect and they don't intersect blanks are not equal on the intersect and they don't intersect and when you're doing these coding problems it's usually hard to think of the solution like right away so it's always good to do examples and with that you can think about solutions along the way so we have four cases let's go through these four cases so if it's the same length and they intersect you can just move the pointers one by one a move b move a and then move b and eventually they'll intersect and once a is equal to b so y a is not equal to b you want to move these pointers up one by one and once they're equal to each other then you can just return that value okay so that's the first thing uh first case with the same length and they intersect so now let's look at the next case same length equal length and they don't intersect so if they're the same length you just move them one by one a moves to a2 b moves to b2 and a and b are list iterators so they're just going through the list they're not actually changing anything in the list which was one of the conditions that they stated that linked list must retain the original structure after the function return so you're just iterating through it you're not actually changing anything and another important thing is that there's no cycle so eventually you'll reach null like in this case so you move one by one and you reach null and null is equal to null in comparison so you can break out this loop and return null that's our second case i don't know why it says three but basically that's pretty simple right you just so far we've just been moving a one by one and b one by one uh together why because they have the same lines so what's actually the hard part about this problem is when they have different lengths so the case i'm gonna go through first is different lengths of known uh intersection so a moves to a2 b moves to b2 a moves a3 b moves to b3 a moves to a4 b moves to null so what we do here uh this is usually this point that we stopped in the last two cases right either they intersect or retail what can we do here to make it so that they reach a similar point because we want to show that there's cases where they do intersect that one will reach null first right so we want to somehow make it go through the same length and then show an intersection so how do we do this we have b go through the list of b and a list of a so if this is four elements so this is five elements it'll go through these four elements and then these five elements so if they're going through the same length and a will go three through these five elements and then these four elements so if a and b are going through the same amount of values right one by one so if they're both going through nine values eventually they'll end up uh at the same point which is an intersection or a null right so when b is equal to null move b to the head of a and then a moves up here then b moves forward a moves to a is equal to now so move a to the head of b and move b forward and now we can stop here so this one through four elements and this one through uh they both went through five elements right but now the distance from null is the same amount which is three and that's perfect because then you can just move them one by one and you'd see that they reached null at the same time and a is equal to b so you can break out so essentially they both went through these one two three four five six seven eight nine values they both run through nine values and reached the end where they got a comparison that they uh they're equal to each other and you break out or turn up so can we extend this idea to different lengths and they do intersect and the answer to that question is yes so over here this has a length of one two three four five six seven so move a to a two move b to b two move a to c1 which is the value they should have intersected at move b to b3 move a to c2 move b to c1 and they both move up one again one side there we go a muslin doll b moves to c3 and same idea we move a to the head of b and then uh we move b to null then a moves forward and b moves to a head of a so what did we essentially do we took the long and linked list and we ignore the first value y we would ignore the first value why because the difference in the length of these two linked lists is one so when a went through like the elements m when a went through m elements it also goes through b goes through n right b goes through n elements but since we're moving them one by one a is also going through m minus a n elements in b a is going through m minus n elements in b so no n minus m n minus and my math so in the end the distance from null for both of them reaches the same why because they're iterating at the same uh pace of one by one and they're going essentially through both linked lists just like the example where they don't intersect we went through all the elements but in this case we're going through both linked lists and this way the difference in their length is made up for in the beginning and you can just move a and b one by one and eventually look at that c1 they both reach c1 at the same time so you gotta really understand why the solution works is because it's going through one linked list and then the other and the difference in light is accounted for by them both moving at the same pace and it going through one then the other and basically vice versa a goes through all of a goes to b goes to all of b goes to a and then eventually even if they didn't reach c1 they'd reach null at the same point and they're both equal to c1 and you can just turn c1 at that point so those are four cases so the solution about is by brian bo cowell hope i'm saying that right i saw on leeco discussion board somewhere it's a really smart solution he was the one who came up with these examples and i'm just explaining it so always like to give credit where credit is due uh so go check him out he's on leeco i think but he doesn't make videos he just made us discussion board solution so now let's talk about complexity so space complexity o of one why because a and b that we had before are just list iterators no matter how long these linked lists are they can be like a hundred elements right you only need one iterator for a and one integrated for b so space is not dependent on the number of elements n or m so list a length is equal to n dot length so the space is not dependent on m or n that's why the space complexity is over one as nrm changes the space doesn't change at all um now let's talk about the time complexity so in the worst case that we saw was case number three where we went through uh two linked lists that had different lengths and they did not intersect that means you went through both uh both iterators had to go through both linked lists so that's all of n plus n so go through all the elements in list a then all the elements in this b and they both reach null at the same time which is simplifies to o of n or o of m whatever they're just multi a n and m uh it's not n squared or anything like that so with that we got the follow-up so with that we got the follow-up so with that we got the follow-up solution and now let's just try coding it up real quick uh so let's graph this little solution soul solutions useless to us now because we got a better one so first things first let's check if head a is equal to no our head b is equal to null because if one of them are equal null you just return all right there's no intersection and we're turning a list note so this note either is the value that you intersect at or null because you haven't found anything so while oh wait first let's make our two iterators oh wait let me make this bigger for you guys it's kind of small there we go so list node a is equal to head a and this is narrator make one for b two and while a is not equal to b what do you want to do if a is equal to null bomb move it to the head of b and otherwise you just want to move it up same idea with b you know i'll just copy the code make my life easier so if b is equal to null you want to move b to head of the day there's actually a way you can do this in one line this whole f casing but um i kind of forgot i don't want to set up the syntax so basically musical to know you want to move it to head of a otherwise you want to move b forward it's just like the four examples that we talked about and in the end this will always result in a case where a is equal to b either if it's the null case or the point where they intersect and over here you want to return a or b you can return either or because they're going to intersect because a is going to be equal to b when this loop finishes right pile air b is equal to null okay so our answer was initially correct let's submit it and see our solution all right that's great our solution was accepted thanks so much for watching if you guys have any recommendations or suggestions leave in the comments um the code is always in the description in the github link so check out look out for that i'll see you guys in the next video and this is a list b iterator uh thanks so much for watching i'll see you guys in the next video
Intersection of Two Linked Lists
intersection-of-two-linked-lists
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`. For example, the following two linked lists begin to intersect at node `c1`: The test cases are generated such that there are no cycles anywhere in the entire linked structure. **Note** that the linked lists must **retain their original structure** after the function returns. **Custom Judge:** The inputs to the **judge** are given as follows (your program is **not** given these inputs): * `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node. * `listA` - The first linked list. * `listB` - The second linked list. * `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node. * `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node. The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**. **Example 1:** **Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3 **Output:** Intersected at '8' **Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. **Example 2:** **Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1 **Output:** Intersected at '2' **Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. **Example 3:** **Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2 **Output:** No intersection **Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. **Constraints:** * The number of nodes of `listA` is in the `m`. * The number of nodes of `listB` is in the `n`. * `1 <= m, n <= 3 * 104` * `1 <= Node.val <= 105` * `0 <= skipA < m` * `0 <= skipB < n` * `intersectVal` is `0` if `listA` and `listB` do not intersect. * `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect. **Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
null
Hash Table,Linked List,Two Pointers
Easy
599
43
hey guys so today for you I have whoops we could problem number 43 which is the multiple and strings question so you're given two strings you're asked to multiply them now obviously you could just convert them both to integers multiplying them convert it back to a string and return it but you're not allowed to do that because that wouldn't be as much fun so in this one you have to look at everything character by character and then you can convert it to an int and all that kind of jazz so in this example I'm going to show you how to multiply one two three times four times six four five six and before we begin um okay so we'll say our first string this one's going to be I and this one is gonna be a J sorry my eye kind of looks like a J but those are cool eyes I can mask so in this question what makes this question interesting is that sometimes you'll get numbers that are bigger than ten so you have to deal with that so for example when we multiply 6 times 3 is our return value or restoring our answer its integer array so when you multiply 6 times 3 you get 18 but you want it to end up looking like 1 and then 8 over here but it's kind of annoying to do that all right away so because you might have to do it sort of a lot so what we can do is we can actually just save that till the end so we can say okay I put an 18 here then put a bunch of other values here and then we can kind of deal with that all in one step at the end so I'll show you how we do that when we get there um one other thing that makes this thing a little bit challenging is where you want to put your number so when you're multiplying ones by the ones place you obviously wanted to go in the ones place which is going to be our last thing in your a when you're multiplying or ones place by the tens place you want it to be in the tens place so that's two away tens times tens is 100 so it's three away and as you can see what I'm kind of getting that is how many away it is from here is um if you add these two together and then you kind of subtract two that's how much it is so if like if you're um so like this is the one place is the ones place one plus ones places to place so I'll just show you the formula so you take your length and then you subtract your um you subtract and on the length of your array is your string length so actually what I could do I set my array dot length equal to my stream one dot length plus my string 2 dot length so we can actually do a little bit of refactoring to make this a little bit easier so this would give us string wand length plus and I know I'm missing the parentheses but I'm trying to keep it smaller - that way - trying to keep it smaller - that way - trying to keep it smaller - that way - string 1 plus I minus 2 dot length plus J 1 so we add someone delete spring 1 and so we can get rid of our string 1 interesting - dot lengths both of them so really just I plus J plus one is where we put it whoops you always learn something when you make a video so it's pretty nice actually and this will only work if you make your total length of your return array equal to UM equal to the sum of the lengths of both of your other arrays so we'll just move this over okay so I plus J plus 1 and we start off on our J is our hopefully you don't run out of battery so our J would start off as like two we started off at the end so whoops isn't I equals 2 and J equals 2 so what we do is we you know create kind of two for loops and we're gonna loop through all of these and then increment this and then loop through them all again and commit that so we say 6 times 3 18 put it here that's about it goes in five times three 15 put it here that's a spotty goes in 4 times 3 12 put it here that's the spot it goes in and then I'll say ok I wasn't really incrementing J but you get the point so now we're gonna multiply 6 by 2 and we're gonna put it here but now when we were doing it we want to see if there's any values here and there's also zeros and all of these about a fold so we're gonna say ok 6 times 2 12 we already have 15 here so say we'll add it and we'll put a 27 and then we'll say 5 times 2 10 we'll add it to whatever's here so we'll say 22 and then we'll say ok 4 times 2 8 wide it to whatever's here and then we increment we're gonna live life on the edge equals zero actually we're not going to live life on the edge hang on sorry I usually live life on the edge but I just made this video and then I found a better way of doing it I'll kind of explain how I was doing it earlier but okay so we um we multiplied a foreigner too so that's 8 and then we okay then RI is zero so multiplier six in r1 and I believe it should go here maybe six or no one so - so it maybe six or no one so - so it maybe six or no one so - so it should go in the three spot so out of here so 28 then our 5 and R 1 so this becomes 13 and then our foreigner once this becomes before so now what we can do is we can create a variable called like extra and what we're going to do is we're going to set it equal to zero and what this variable is going to represent is kind of an extra that we need to add on so you'll see what I mean in a second so say okay 18 equals 18 plus extra so it's still extra and then what we're gonna you know say is extra equals extra divided by or extra equals 18 extra equals this value divided by 10 so our extra will now equal to 1 and then we'll say this number equals this number mod 10 so we'll get rid of the 1 so then we get here so we'll say extra well say this value equals this value plus extra so this is becomes 28 and I shouldn't have deleted the 2 but this becomes 28 and extra becomes extra divided by 10 so extra comes this value divided by 10 so extra becomes 2 and then this value equals this value mod 10 so we get rid of the 2 so then we do the same thing here we add the 2 to this we add extra to it so we say 30 and I'm gonna say extra equals this number divided by 10 so our extra is 3 and then we'll say this number equals this number mod 10 so becomes a zero and we'll say this number equals this number plus extra so 16 um extra equals this number of mod 10 are divided by 10 so we say it 1 we can get rid of the 1 and then we'll say extra equals or this number equals there's no where plus extra so this becomes a 5 and then this 0 is terrible extra equals okay so that's a five extra equals that value divided by ten so extra is now at zero this number equals this number divided by ten but still five will look at this number even though we don't need to we still should actually so uhm this number equals this number plus extra zero and then we'll do some extra calculations but it doesn't matter because we're done then with our string value or when we want to convert this back to a string will clear stringbuilder will loop through it until we find a variable a value that's not zero so we'll loop through it we'll say okay this is the first not zero and then we'll add everything else I on to it so I was talking about what I was doing before so before I kind of understood the good way to do it I was just saying okay I'd put an 18 here and then I'd say I'd kind of create like a while loop and while you have like an extra value um I'll just give you like a little better example I like kind of make more sense so say this is like eight just like eight oh hey we've got a bunch of nines and I realize this probably might be like impossible but like uh my logic was working before as I would say like say um I was adding like say I'm really taking this number and I was like adding like nine to it so I would say like okay instead of just adding 9 to insane putting in 18 here I would say like okay this is 18 and then I would directly like before I had even like finished like everything else like before I went to the next step I would say okay my extra values and is a 1 so I'm gonna put it here and then I'd make this a 10 so then I'd say like okay my extra values of 1 so I'm going to put it here make this a 10 and then like okay my extra values of 1 so I'm gonna put it here and make that a 1 I was doing it kind of like that um now that I think about it probably doesn't make too much of a difference but the way I showed you is a lot simpler to do it in toad than the way I showed you because I think it's impossible to get more than like one extra at a time for that um while loop to go more than maybe one space but I could be wrong so let's see because like when you're comparing these numbers you just have these two values then so like after your first um you could hit all four these values your first time through when um when I equals two these four values do these work at all odd numbers yeah okay so it could be possible and then your first value on your next way through would go into this spot so your first time through can hit the first four numbers then you could hit these numbers so that there could be a lot of like repeating like kind of what I just showed you like tearing over but you don't want to have to do that a lot of times the way I showed you're only gonna have to do that once which is a little bit better um it's the same day go but yeah so to Big O of whatever this number is times just a number so like I J or MN I'll put them with a code in my github in the description also tag delete good problem so thank you guys for watching and I hope you enjoyed live life on the edge
Multiply Strings
multiply-strings
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. **Example 1:** **Input:** num1 = "2", num2 = "3" **Output:** "6" **Example 2:** **Input:** num1 = "123", num2 = "456" **Output:** "56088" **Constraints:** * `1 <= num1.length, num2.length <= 200` * `num1` and `num2` consist of digits only. * Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
null
Math,String,Simulation
Medium
2,66,67,415
4
Hello everyone, I welcome you friends, today we are Mukesh, don't wait so much, we will solve important questions which are very tiffin, really top, its logic may not be understood at once but inside and if you are like job. I have done it when I will tell you, if you do it on pen and paper then you will definitely understand, okay send this question, the biggest specialty is that your tenth class mathematics students will understand how much you have studied and how much you have not studied, okay Hey, let's start the video. The medium is 200 tabs. Okay, after seeing this question, you can easily color it on pen and paper. There is no doubt in this. Thinking about this code and logic is not a little but very difficult. Mothers are normal users. If I talk about it. The recording is also near so don't think about the fennel, it gets a little top, okay this question is a gift whose link I will not be able to give you, I will give you the link of its lead and you will do it yourself, so this homework will be for you only today. That you have to solve the latest question, okay and let's start this question, so now look at what this question is saying, two ad is given, okay and it is defined as too short and dark, we are the players of the Year of Man example taken, friend, I am taking it on zoom from 12345 to 12345 and those two are respective lengths, right, now the media is busy. Understand, first we have to chill because after the march, I will remove the media that will come. He merged both of them and shot the march becoming soft. Okay, now after that, what is the sum of the country's media in the media? In any shot in the dark, if the excellence award is given to you, the middle element will be that media and if A collective Neither we have the media which will mix, what should both of them do, neither we have that media. If we talk about this case, then total we have 11:00 element, which means old audio, so it means that the 11:00 element, which means old audio, so it means that the 11:00 element, which means old audio, so it means that the march which has been sorted comes out and is its middle element. Now let's talk about the second example that in both of them there will be y55 of NRHM and there will be total time element, then we will get two of these, after doing the year of which is the media limit, we will soften, hence the question. That is to match the 200th, soften the bow and then take out the media, then from this, let's go from the media front part plus 3520 7.5 till go from the media front part plus 3520 7.5 till go from the media front part plus 3520 7.5 till now brother, I understood what is media, how to take it out, we revised it while doing so. Everyone creates temporary things while working in school, what will happen to them, so what do we do with the people that we copy them, hey, subscribe to both of them, now let's cut it to copy it, now let's talk about if and Plus and order is the middle element answer which is not there in this case so the average of what is left is going to be cancer so this is the night solution in this but what is the problem that we have to give extra space, we take this and take time in this. Wants to solve the complexity, which is most important for us, this is the meaning of giving this question, the question has not been thought of yet, had to be simplified, country, oh man, had to set these in both, hand over the fast to SEBI and soften it further and media Let's take it out, but there is a point here and it should be solved in terms of time complexity, which is the point of 268. This is the short term alarm that has been set for both, how to take advantage of that thing, so what is the most efficient solution for taking out the media? Now see, now we come to the complexity, now I will tell you what exactly is the information on this, okay, we have to find out the patient IS, now we have to put our brains together, now see what I am telling you is the calculation, I am telling it with the assumption. I am sure that the N will be smaller than us, it will be equal to us. Now look, if you tell me, brother, if it is increased for cases, then the code file will be of, otherwise the function given to you people is tiger, like in this case, the function is given to Okay, so it is that in this, whatever N is, a function has been given from it, wherever you have been given a pointer, you will first check in the code, which is ours, so end dramatic, there is no problem in this, I am telling you in general, you first check. Find out which one is bigger, which one will be bigger is fine, take that too as R Rahman, but consider the one which is smaller as this and then perform your calculations, we will change the place of the point given to the videos, we will find out this but They are assuming that Ranbir is big and considering Ranbir as big. Now see what this is, what I will tell you in this whole calculation, we are creating two sets, one left foot, deep right. Yes, this virtual is saying. Set is actually a set, it is not adding extra space, it is not keeping extra space, but we have such a festival in our mind, what is the answer, we are solving this diagrammatically, let's say one set, we are calling it left, score after the second set. Live Left Right is saying yes, what is the meaning of joining hands, just dividing the two edges A and B equally such that left will be this amount of elements and both of them will have this amount of elements on the right, this is how it should be addressed 5 plus 9 Inch plus 94027, VAT will go to both of them. Now brother, if there is any Saifee element, then Mohit will keep more in the left one. Okay, now how to divide, so we brainstormed, we took out the middle of the first one, so we accepted this remedy. One is fine, put whatever is left behind China in the laptop and find iron and minus one in life, it is fine in life, now we will think about for, now right to recall was done by us, according to China, which organizers so that The element that comes behind it should go to the left and the tiger in front of it should go to the height of the lattice and both the left and right should be in equal number of elements. Okay, so one is equal to plus and minus plus and plus one by two minus. If you do one then it is not very tough. Simple mind, let us apply that both the scooters have taken out the number element - taken out the number element - taken out the number element - why did you add extra? That sexual intercourse follows zero intake and the fiber which is in these tracks - if you have done that then tracks - if you have done that then tracks - if you have done that then we have taken out the number element of that position. Got it, listen, you can distribute Amla, take it to have more life, don't put your mind in it, simple things, the fiber has gone out, now thank you Guru, make a box of underline and make a like box on the right, it's okay. Now in technical life, I should write, Oh idea, from seven to the end minus one, this technique should be taken, I have taken a big selfie, from seven to the end, from the store to the end, I have brought life from zero - from 140 to IT - 110 Now this has life from zero - from 140 to IT - 110 Now this has life from zero - from 140 to IT - 110 Now this has happened, why distribute it now because see, what was the purpose of the attacks, if the left part is shortened then we will terminate people, now I am telling you an example like if you tell the maximum element in the left part, then another 500 to 1000. 1945 Now, if we compare which school is the biggest and smallest among the schools of 500 and 500, then we felt that we will get payment left right toe, we found a point whose left part is smaller. If it is from the right part and both are equal, then it is connected. In the dark, what will be the medium, that it is medium, what kind of point will be there, whose left part will be equal to this point, left for lift is small broadcasted, okay, so this is the reason. This did not happen in this case but if I talk about this case and it is 2728, now the maximum on the left is 128 and height is you minimum chief guest, definitely pay attention to my words, you will get trapped otherwise I will explain in more detail but beware, just focus. Which is the maximum for the laptop? 28 and the height is sure to be the minimum. If we look at both, the laptop has become smaller. Antimetic Light of Baroda. We will terminate the village. Tell me this. Media will come to life. Which will be its maximum element, local life events, minimum element. By adding both of them, because this event is 959 plus party, then positive a number will be the intermediate average in Pali. If it was any other simple, the first subscribe element would be that. We are searching for whose fact is that the ghee spread on both the sides should be equal. Wale is a small light condition, you understand that the one of one position is considered as Nuvvu and Ayurveda which is one minus one of Russia is just the last index of Malia Max but AB is considered as Mintu in AB, White Revolution is just. Accepted the previous one, next to ok, we have written my minimum element of right side of the river is ok and maximum has become maximum element of left side of air ticket, basically what we are doing is making the set. There is one more element of these two in it, okay and then the leftover text will be its maximum, developed will be in small ascending order and the height one will be in the pot in the largest order, then check and this part is this point software. So and so check that Joule Africa will be the maximum element and if the right week was smaller than the minimum element then the condition is not a problem and this is what we are doing in this chapter. We are comparing max to minimum, it is fine, next to. We are comparing the minimum with this one. People will get the media, this is our concept. Now accept that it should be seen in the mirror of this decision, which minion is the minimum, write down which Brahma in the copy and see the maximum Okay, if it is bigger than that, then what will we do in this case, we will shift the fist backwards and not forward. Now this is my wish, I am telling you how to do it. If the maximum is bigger then in this case, then It is going perfect, it is fine but the maximum which is bigger should be increased from mintu to mintu. Why will the film start shifting left? Because we came to know that what we have is right from the number, the address below is right from the number 11. There is a side hotspot, there is no sweater in the set, we will start moving towards this loot, now look at the code that I told you, based on this code, I am telling you exactly how, what to do, absolutely minimum maximum * how, what to do, absolutely minimum maximum * how, what to do, absolutely minimum maximum * Next, if you understand, Now look, let me tell you why the condition doctor put Barrister Three Operator here, you will understand this code of theirs later, wait for more time, the media will take a long time, but keep a little patience, you will understand very well, okay, I have given 305. Okay, the event will be organized in Death One and One Hum 2013. Let's assume that when one plus and one by two is made, that means 182 has come from that formula and plus one by two - 512. This makes it plus one by two - 512. This makes it plus one by two - 512. This makes it three. Now you guys this figure. Look at and find the minimum * maximum next pause the video minimum * maximum next pause the video minimum * maximum next pause the video fennel phone then you will understand I hope you should have solved your answer must have come from min 12235 now in this case we have to compare that next to sorry next one should be small mintu Okay, complete, we do this, which is written in my first place in the adding, maximum should be smaller than minutes and max two is smaller than brahmins, minimum should be this, okay now, which gas grid is happening, you Tell me, the maximum is smaller than Mintu, it is okay, but this type of We will do this, it is doing binary search, it is setting reminders for the whole year and what are the conditions. The laptop should be small and with tight hands, the condition is given by me and if it is not so, then we will shift left and right. When will you set it, when the maximum becomes bigger, from whom, it is not like this with Mintu 123, it will shift to night in sunlight and when you shift to the right, then see in one and if it was dawn, then jobs in, it will come here, the admin's backlink will be -1, it will become in, it will come here, the admin's backlink will be -1, it will become in, it will come here, the admin's backlink will be -1, it will become one plus. If there is one then it should be exactly two, so now we have these people, what will you do again, find out the number * went and what did you do and one number * went and what did you do and one number * went and what did you do and one plus one, definitely watch this in a long time, many people ask right now, look now, it is You guys minute maximum next point phone again this answer must have come to your mind now look in this case the maximum which is bigger is not smaller than mintu which should be smaller and the max one which is max two is smaller than the minimum. Now go, I have got such a condition that the left first week is smaller than the riding hand, so in this case the media will come, can you tell me about the media or its max and its mill 3520 plus bike 220 2.5 max and its mill 3520 plus bike 220 2.5 max and its mill 3520 plus bike 220 2.5 Zeenat Aman from 220 2.5 had a condition put in it. Zeenat Aman from 220 2.5 had a condition put in it. Zeenat Aman from 220 2.5 had a condition put in it. Understand what it is, assume that the value of life is equal to N. Take this from zero to reach. The figure that I am telling you, I had copied and solved it myself, that is why I am able to tell you so many truths. Director, we are like this. Let's learn to front, okay now look, it's from zero to five, okay now whatever their value is, it's 6, now the high velocity part, then there's no one in that contact, but I'm the one who has attacked the same position at the same place, it's minutes. Thirdly, there will be some minimum, otherwise we will put the maximum. It is okay, in the same way, if youth reaches zero, then the minimum is gone, but how will you find the maximum? Iron is of maximum - 1250 - - - - after washing, there is a limit otherwise Iron is of maximum - 1250 - - - - after washing, there is a limit otherwise Iron is of maximum - 1250 - - - - after washing, there is a limit otherwise I am this one. How can we assume that if you are 100 then the maximum that we have is the intention, all this in the media, in any case, what we have is surplus night fall, internet and end max, consider a little top as time, it is very tough, it is not that easy. Now let me code this, then you will understand more batter, one is considered bad, which is okay, zero is okay, one is Edmund, which is N, anyone is putting their top loop till they can one. Advance should be smaller or equal. Okay now the interviewer has now plus that and fun yes bittu enter into what will happen then tell me your white plus one boy two is - I want to okay and remove ainul is - I want to okay and remove ainul is - I want to okay and remove ainul more minimum what will happen you see if minimum Means we guys deep is one thing and min and time are one thing if can be equal means what is max is ok and else there is one no problem int max or if end = 0 ok Then what will we do inch minute end = 0 ok Then what will we do inch minute end = 0 ok Then what will we do inch minute otherwise the area of ​​five one - it is otherwise the area of ​​five one - it is otherwise the area of ​​five one - it is acceptable that these people like mintu and remove that mintu and next toe what do you do, the whole case can be possible but here the iron will come ok quote 1 if one This is to I item or it will be done and it will be done Hey there is also a place for the unemployed person to user guide to ok like this people take out mintu mexico now what condition to put the face which is mexican should be smaller and equal to mintu Okay, at the same time the maths to be done should be small and equal. Okay, if this condition is happening to us then what will we do then we will check it means whether we have got the money or the laptop is small and if both are equal then at this time Do if plus molu agar sure aaya then what will we do dun karega double persons point karne wala thrown to max the mexican hai next do ok plus life in tamil meaning of nuvvu ok bye two ok do this If we give it, then the answer will come to this one that it is pollution, that is why there is this bracket inside at number 1, indicator, ok, mails, and if the order goes, then what will we do, if the gas comes, we will return it, now double yo. Belly ticket double what will you do tell me brother neck fennel max vansh ki and max to know this you will have to do mithun trident instead of solving khokhar this time without doing president there will be a little problem ok be confident take the example which I have got done ok if This did not happen and it is safe that if another such case comes that the maximum becomes bigger in Ubuntu then what will we do? If I tell you that the maximum becomes bigger then we will bake from the left side and shifting towards the left means that If we bring the end part here then the end part which will be end one will go to us, what will we get then let's get one minus one and if that is not the case then we will shift towards the right then we will get brinjal one. Oneplus one dates all, we submit and let's see what the test is, it will be tough, this question will be a practice, it will take compilation air, why did it come brother, that your ok, I have given question mark everywhere, congratulations that is a great one We do the work, we had to prepare for maximum submission, a little question, eight noses have been given in the grand space to which yes is the correct answer, so if you want to do my job well by making him struggle, then I would please heartily request you to ensure a dry run, friend 3 4 Crore listen to me tell the acoustic code to inverter direct I told the commitment that when it is simple two lessons have to be done laptop write-up and till then lessons have to be done laptop write-up and till then lessons have to be done laptop write-up and till then we will do binary search laptop is completely small note 4 light house how to compare and test What is the maximum in the case? Check the driver Anil, he is smaller than Mintu, why are you not chatting with him? Why are you hesitant in taking the maximum to the minimum, because the smaller one will be off hotspot or Bigg Boss already, he is a part of the same and he is sorted. What does this mean? We are checking the special link below. If you liked the video, then I would have liked to know. Vikas has become very complex and you have a little mistake in trusting things. The video is quite good, it is very popular in my house. Good development, very good Arkansas has been told, now please read the video two to three times and you will understand, if you are really new in my channel and want to learn computer programming, then please watch the reference video and feel loved and please subscribe my channel and Share with friends, this is my moral, now it is posted, thanks a lot, see you in the next video.
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
234
how's it going guys sorry if I hurt your ears there I got a new mic recently but yeah we're just gonna be doing another thing if you don't know who I am check the description I do tech encoding stuff on twitch and YouTube and I've been doing all these leak code problems and kind of explaining them so we already did a palindrome integer or something like that or reverse integer something like that so right now we're gonna do is a penalty it's called palindrome linked list that's what this problem is called and I'll leave the link in the description it says given a singly linked list determine if it is a palindrome right so one two is false you know what a palindrome is it's like racecar spelled forward and backwards is racecar so that's a palindrome and you can see one two one is a palindrome you know it's just the same forward as it is backwards so the algorithm to do this is kind of the same as how we would do it and you know another palindrome problem basically what we're gonna do but yeah basically what we're gonna do is we're gonna have two pointers at the head at the beginning one of them is gonna be moving faster than the other so one of them is gonna get to the end by it's gonna be the fast one is gonna get to the end of the list by the time the slow one gets the middle of the list and then we're basically gonna reverse one half of the list the right side of the list and then you know iterate at you know then we're gonna iterate at the end and make sure they're exactly the same I guess I'll explain a little bit better after we write it so I'm gonna write it really quick all right so like I said we're gonna have these pointers these initial pointers one's gonna be call fast one's gonna be called slow we can call we're gonna do slow first right so let's note slow equals head and let's note fast equals head and then one's gonna be going faster than the other right so faster is gonna reach the end of the list first so whenever you're not traversing but you know iterating through or going through a linked list you're gonna want to have you know the current node the whatever node is gonna hit the end first you're usually going to want to have that and your loop that's gonna be your break condition basically so while fast is not equal to null or and fast dot next is not equal to null this is gonna be condition to you know tell us when to stop fast equals fast dot next right because this one's gonna be going double the speed and slow is just gonna be going one at a time right so slow is slow at this the slow pointer is moving one note at a time as we go through the list and linked lists and fast is going to nodes at a time right so you know kind of just to show representation of that if we have you know this is our linked list right these are the nodes 1 2 1 well the node values slow and head both start at 1 but slow is gonna be going to head would be going to this second to when at the you know first iteration and then the you know with the final iteration slow would end up at the second two and you know fast would be null because it would go over 1 and it would end up being off and that would break our loop there so that's pretty much it and then what we're gonna do is we're just going to call this method we're gonna right afterwards called reversed so slow is going to be equal to slow reverse we're gonna set back fast to head so ahead fast really doesn't even need to get to the end because we're just setting it right back to the beginning what slow is gonna do slow is at the middle note of our list by the end of this loop and what slow is gonna do is we're gonna pass in a node and we're gonna reverse all of the notes from halfway to the end of the list so it'll be in reversed order so if you know if the right half of the list was so let's say the list is three to one you know three to one two three right slow would be at one right and we would pass it in and it would reverse it so it would be now three two one so it's just reversing it and then slow is gonna be at three and fast will be at three here and we're gonna iterate we're gonna loop down both of these basically they're basically like sub lists at this point even though they're not but we're gonna iterate until slow gets to the here which would get you know fast to halfway and then we're gonna make sure that you know as fast goes three two one slow also goes three two one and if there's any difference in the elements then we know it's not a palindrome so hopefully that makes sense to you guys I'm trying to get better at explaining these as I do more and more but you know I mean this is only like the tenth one we're doing so maybe but I feel like that makes pretty good sense if you think about what I'm saying here so now that we have the reversed slow so the verse the reversed right half and the regular front half all we're gonna have to do is do well slow is not equal null cuz slow is already at halfway so we just got to make sure that it they both go so slow equals slow down next you know just moving along here like we were doing before now fast is only going one at a time slowest but going one at a time and if there's a difference like I said then it's false and that's the only case where it would be false and if we make it through all of this then it's true it's a palindrome should be obvious at this point why now all we have to do is do public list node reversed it takes in our list node slow right this is where we call reversed with the slow and this will be called you know and then all we have to do is declare a previous node this is you know this is the more important method to kind of figure out here so we're gonna use a previous node in this case to reverse the right half of our linked list and all we have to do now is do make a condition while head is not equal null and traverse because I've been doing a lot of true problems but I think in listen linked lists all it's just called like going through or just iterating through the nodes in the list or something but I guess you could say traverse honestly but so while ahead is not equal now we're just going to be doing have the next node so head dot next in so let's say we pass in three two one like a my example before three would be the head previous would be null and next is our node that we're making is gonna be head dot next so next is going to be two and then we're gonna do head dot next is set to prove so head is three we're gonna set next to null right so it's that's how we're reversing it basically and then all we have to do with then is update preview head and update head to next yeah right and then all we have to do after that is returned priva pre by the end of it is just gonna be the head of the reversed list so yeah I mean that's pretty much it this should uh you know submit fine be false what's wrong should submit fine not a statement out return false sir you know always have a little bit of uh never good anything first try okay there we go fifty eight point seven six percent all right two milliseconds there you go see ya like I said you have a linked list if it's one two three two one that's a palindrome right because I kind of explained it's like how race car backwards is race car you know if you look RAC e CA are one two three you know I mean it's the same thing so you have the head and fast initially at one fast goes double so it gets to the end first and by the time it gets to the end slow is at the middle and then you pass slow into this reversed method it reverses the right half of the linked list and then you just iterate from the beginning in the middle to the end and they should be the same list so hopefully that makes sense to you this is the reverse method maybe look into that a little bit more you know if you really dive into it and go step by step you can see so if it's one two three it should be three two one in the end so you pass in one it's gonna set one's next to null but one's next right now is two so setting it to null makes sense right because it's you know no it would be one then null because you know before that is gonna be too and then it's gonna be three if you go through the rest of it right you know because as you loop through it previous keeps getting set to head so and head necks keeps getting set to previous right that's where the changes are taking place so you know two dot next is getting set to one and then three dot next is getting set to two right cuz previous keeps getting updated ahead look into that a little bit more let me know what you think of my explaining in the comments below I'm really trying to explain these good maybe I could do some white boarding stuff in the future but yeah check me out on Twitter subscribe on YouTube and thank you guys very much you know maybe I'll redo them and I'll have some more videos more leak code the I have all the leak code stuff so you know check it out in the future thank you and see you
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
62
hello everyone welcome to codus camp we are at 17th day of normal eco challenge and the problem we are going to cover in this video is unique paths so we have already solved unique part 2 and 3 in our channel so this is comparatively the basic version of those and here the input given here is m and n which is nothing but uh it represents the size of the grid or matrix and we have to return the path from the top left corner to the bottom right corner that is the number of paths that are possible or number of unique paths that are possible so let's understand this with an example so as per the problem statement our robot is going to start from the top left corner and it has to reach the bottom right corner of the grid so we have to return the number of unique parts we can travel from the top left corner to the bottom right corner so as you all know this is gonna have n number of parts that is you can overlap the visited cells again and again so you can't use a bfs because we usually take bfs technique to solve this kind of matrix problems when it comes to path or number of paths or something but here we cannot use dfs or bfs to solve this because the paths are overriding so you can't have a pointer visited uh to mark the cells we have already visited and only explore the cells uh we did not explore that is how a bfs algorithm works efficiently so if you cannot put a marker that the cells have been already visited then in that case bfs is not going to work though if you try some technique to accomplish it the time complexity is going to go infinite so the best approach here is to use a dynamic programming solution so we have covered enough dynamic programming solutions say that it is a linear dp or two dimensional dp already in our channel but this problem is one of the classic problems where beginners can start with it will really make you understand how to work with or what is dynamic programming and how to approach a two dimensional tp problem by getting into this so let's start so before getting into the solution as i always say dynamic programming is nothing but solving sub problems and from that solution we will solve another level of bigger problem and finally arrive at our bigger solution so for any dynamic programming solution we first have to solve our sub problem or the smallest possible problem and then get started with the higher number so for this uh problem what is the smallest possible problem we could get so let's reduce the grid size let's consider we have only 2 cross 2 grid where the robot is placed in the leftmost cell and star is placed the rightmost so now what are the possible solutions for the robot to reach the start so you can clearly know that robot can travel only towards the right side or downwards so if it is traveling right side and downward it is one path where the robot can travel and the other part is it starts traveling towards down and then reaching towards its right so in this another part so the solution is 2 for this problem so how did we achieve it to reach this particular position we have considered the movement of the robot from upwards and leftwards because the possibility of robot can move towards right and down so for a cell a robot can reach from its top and its left so this is the overall logic so what are the possible ways that are there in the cell towards outside and the left side will be the solution so if you're not understanding that is okay let's get it get into the bigger grid for better understanding so let's consider we are having a two dimensional array dv where each value of this dp array is gonna hold the number of unique paths to reach that particular set so from that solution we're going to build our solution towards the last grid so let's consider and start iterating from zero comma one so now from zero comma one what are the unique parts or how many number of unique paths for the robot to reach this particular position so we obviously can say there is only one way because the robot will move only towards right and down in that case it the cell zero comma one can be reached by the robot only by using one way so our answer is clearly going to be one also move on to the next cell which is this 0 comma 2 so this also we clearly know there is only one path to reach that cell it can be straight because it can move only towards right not upward direction you can say it can go down and go right but it cannot go up this is the wrong way so if the only possible way is to reach that position is by moving towards its right so similarly all the rows in that first column first row would be one only because that is the only possible path to reach that cell similarly going towards down this cells will also have one as the robot can move only towards downward direction to reach those cells so now comes to ourselves one comma one so to this particular cell how many unique paths the robot can reach so the robot can move towards right and then down this is one path and down and then right this is another path so there are two possible ways to reach this particular set so the value at this cell is going to be two because there are two unique parts to reach that particular set so moving towards the cell one comma two so one comma at one comma two what are the possible unique parts so if you start doing it you are going to start from right down and then right that is reaching from this particular cell or right and down or down right and right so there are three possible ways so i'm gonna update three here same way for this cell it is gonna be four possible ways because to this particular cell you might have three possible ways so those three possible ways will also applicable to its right cell because from this cell only you can move but there is another upsell there is one way to reach this cell so from this cell you can go down and reach this cell so there are three plus one four ways so now the formula is pretty simple we are going to add the values at upward cell and left cell and update it here in this cell so 4 plus 1 is going to be 5 plus 1 is going to be 6 and 7 and updating the other cells as well in the similar way it is going to be finally 21 plus 7 is going to be 28. so to reach this particular cell you have 28 unique paths so the solution is pretty simple all you have to do is you have to have a dp array where you're going to update the values of the first column and first row as once and other columns will be calculated based on adding the diagonal values so yes all i'm trying to say here is we always fill in some values in the array and come up with a solution towards the end for any dp problem but there is always a logic behind it if you understand how we are deriving the solution for each sub problem you would probably crack this kind of problems so yes you can find the dp playlist where you can find very similar problems to this and start solving them to get good hand in your dynamic programming skills this algorithm is going to work in big o of m cross en time complexity as well as space complexity so let's go to the code now so as i said we need a two dimensional pp array of size m and n and we are going to update the values of columns and rows to 1. so now let us hydrate the rest of the cells and update them by adding the diagonal values so finally return the last cell of the dp where our solution for a bigger problem is there so yes let's give it a try yes let's submit yeah solution is accepted and we have completed today's problem and that runs in 0 milliseconds thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
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,695
hello everyone and welcome back to another video so today we're going to be solving the lethal question maximum erasure value so in this question we're going to be given an area of positive integers called nums and we want to erase a sub area containing unique elements and the score that you get by erasing the sub area is equal to the sum of its elements so you want to return the maximum score you can get by erasing exactly one sub array so an area b is called to be a sub array of a if it forms a contiguous subsequence so it has to be continuous uh that is uh if it is equal to okay so this condition over here okay so in simple words um so let's say we give it this area four two four five six a sub area could be something like just the number two or we could have something like two four five or we could have two four five six or four two four right so anything which is continuous um is going to be considered as a sub area but there's an additional condition over here that it must only contain unique elements so for example 4 2 would be a valid sub area but 4 2 4 in this case would not be a valid sub area so basically this question all that it's asking us to do is we want to find a sub array with unique elements and whatever sub area we find has to have the largest sum so let's take a quick example at this uh the first one over here so one possible sub area is just the number four and two so that will give us a sum of six so basically we want to look for other sub areas which could possibly have a bigger sum so let's look at uh as an other example so we'd have 2 4 and 5 so that would actually give us a sum of 11 right so that is uh greater than the sum we had before but there could still possibly be a bigger sum so using that method we just keep checking for the largest sub area and in this case it would be 2 4 5 6 and 2 4 5 6 would give us a sum of 17 and that's the largest sum that we can get and that's what we end up outputting the value 17 and the optimal sub area like i showed you is two four five and six so first let's look at a brute force approach of solving this and then we can see how uh we can solve it in a block better in a more efficient manner all right so i'll just go over the brute force solution quickly but let's not spend too much time over it so essentially uh we're gonna have two for loops and each time we're basically gonna look through each and every single possible combination get it some and we're going to store it some somewhere and each time we keep updating the sum value until we get the biggest value and at that point we're just going to turn that okay so what i mean by that is in the beginning we're going to start off with just the uh the value five then we're going to extend this our sub area is now going to be five two then it's going to be five two and one right so we're gonna keep extending the sub array and each time of each iteration we're changing the starting point but right now we're still in this first iteration right uh and then we extend it again and now we're over here but now the problem once we come over here is that we have a two and we have two twos and basically it's not a unique sub area anymore so that's where the problem comes and that means that we go this is not a valid sub area so we're going to stop right so at this point what happens is we just account for everything we had until the values 5 2 and one and this has a sum of eight right we're just going to remember the sum store it somewhere and each time we come across a larger value we would update it so now that we're done with this sub area because we had this uh two here and it doesn't make it unique anymore we go on to the next starting point which is two so and we do the same thing so first we just have the value two then we have two one and each time we're going to compare this sum with the current sum that we have and take the maximum so right now we have a sum of three and then again we have two over here which is incorrect uh in the sense that we don't have it's not unique anymore so we just keep moving on then we go to one then one two five so on and so forth right so each time we keep doing this until we reach the ending and at that point we would have gotten the maximum sum in this place right so let's just see what this looks like in code and it should be a lot easier to understand okay so this is what the brute force approach looks like so over here we have our result and we started off with a value of zero and now we're gonna have our first for loop where we're gonna do for i1 in range length of nums and this is basically going to be each of the starting points so we're going to consider each element as a possible starting point then we're going to have a set over here which keeps track of the numbers that we currently have and this way we only get the unique numbers and then we're going to have a temporary value of 0 and this is the sum that the current or the temporary sum that we have for this specific iteration okay so this for loop gives us the starting point then we have the second for loop here which tells us where this array ends so in the beginning uh we just have the value of i want right then we have i one plus one i one plus two and so on and so forth so each time what we're going to do is we're going to go in this for loop and it starts off at i1 and goes all the way up to the ending so if at any point nums i2 is not in unique what that means is the current number we're on has not been seen yet so in that case that means we can consider it so what we're going to do is we're going to add its value to our temporary running sum and we're also going to add this value to our unique number set so the next time we come across this uh so if this is not the case we're just going to break out of this okay and then finally so these are the two main conditions and we'll just go over this later let's just ignore it for now um and then after this um outside of this uh for loop we're going to check if whatever value the running sum that we had is greater than the current result we're holding right so in the very first iteration is it's time to greater than zero if that's the case our result is now going to hold the value of 10 and each time what's going to happen by doing this is where a result is only going to have the largest value and at the ending we return result okay so knowledge uh now let's just go over the small condition over here so it's pretty simple so essentially what it's doing is um so basically uh over here so what happens is when the starting point becomes two okay uh what we would do is we would first go to two then we would go to four then we would go to five and then we would go to six okay so essentially what happened is we went all the way to the ending from a certain point we went all the way to the ending and that directly means that anything that uh any other sub area that comes after this is always going to be equal to or less than this now the basic intuition is that right now we have 2 4 5 six right so the next starting point will be four we would have four five six then five and six and then six so no matter what it is never going to be greater than the sum of two four five six so if we end up going all the way to the ending what i did is i put a if condition if we go if i2 is equal to the last index then in that case we're directly going to return either the maximum between our result or the temporary value that we have so now this code over here does work but as you can see over here we are our the length of nums could be all the way up to 10 to the power of five so that's really large and in those conditions we will get a time exceeded error so now let's look at a better solution and essentially over here we're having two for loops right but we want to kind of just make this down into one step and to do that we're going to use a two pointer method so let's see what that looks like all right so in our two pointer method of the basic intuition is that we're going to start off with two pointers let's just call it i and j okay and the basic purpose of i is that i is going to represent the starting index from where our sub n starts and j is going to represent the ending index of our sub array so essentially in the beginning our sub area is just going to be uh zero comma zero it says that we would just include the number five in this case so each time j is going to be moving okay so first j would be here then here so each time it moves up one and index right so the only other thing that we're going to change manually is the starting position and we're only going to change that when we reach some sort of condition so essentially it's a window which keeps getting bigger and bigger but if at any point there's some sort of problem so for example if we go to five two one two the problem is the fact that we have a we do not have a unique uh sub array so in that case we would move the i until we get a unique sub array so currently i is over here then if we move i over here we currently have 2 1 2 which is still not unique so we're going to move i again and now we're just going to have 1 and 2 which is unique so now we keep moving j so j would be 5 and then 2 and then again we don't have a we have a problem over here so then we move i again and keep repeating that and while we're doing this each time we're going to get the sum of the current sub area that we're on and update that so if at any point of the result is going to be what we're actually going to end up putting at the ending and each time result is just going to hold the maximum value okay so we're going to have two sums let's just also initialize that so we're going to have a result which is going to be kind of like the thing we end up outputting it's going to be the maximum sum and then we're going to have a current running sum for each of the values so for each of the sub errors as we're iterating through it and finally we're going to have one last thing which is going to be the set that we had earlier and let's just call it unique and this is going to be all of the values that we have currently come across okay perfect okay now let's see how this all works and uh with each other okay so let's start off um i like i said it's going to start off with a value of zero and j keeps iterating so in the beginning zero one two three and so on until the ending okay so let's see what the first iteration looks like so at the first iteration uh we're currently over here with a value of five and what we're doing is we're checking if this value is inside of our unique set and obviously since this is the first value it is not there so then that means that we are going to account for this value and the way we do that is the first thing we want to do is we want to add this to our unique set and so we add it so currently unique has the number five perfect and then we need to account for this value and the way we account for this value is by adding it to our current sum so just to make it more clear a result is going to be zero current is going to be zero at the beginning so we're gonna do zero plus five and that's just going to be 5. so our current sum is 5. now we need to do one more thing we need to update result accordingly so the way we update result is we take the maximum between the current result and the current sum that we have which is five and zero and obviously the bigger value is five the result is now going to be five perfect okay so let's just keep moving on so now what's going to happen is j is going to move on to 2 but remember i is still at zero so the sub area is essentially five and two okay so it's a window that keeps getting bigger so let's now include the two in the sub area and the way we do that is by adding two over here five plus two is seven we also need to add two to unique and uh now we check our result so it's either five or seven we want the bigger one so result is now going to be seven perfect so let me just go through this a little bit faster so now we have one over here uh one is not in unique so we add one to unique and we add one to current and result also gets updated okay so this is where things change so now we have the number two and the number two is already accounted for like we can see that two is in unique so now what exactly is our next step so now we're actually going to go inside of a while loop where we're going to stay in this while loop until 2 isn't unique so essentially we want to get rid of the other two which is inside of the sub area and the way we do that is by moving i so first i is at 0 so now we're going to move i to the next index but before we do that so currently i is here we need to make sure that we're not accounting for the 5 anymore so since we're not accounting for the 5 we're going to do 8 minus five okay so eight minus five is going to be three that's our new current sum since our sub area does not include the number five and another thing that we need to do is uh since five is not part of our sub area we also need to remove it so now we're going to remove five from our unique list a set sorry okay so now the next thing is we iterate i by one so now i is going to be equal to one and we move it to the first index so i is currently at the first index and now we have the value two so in this case uh before we actually go over here and make any changes nums j is still instead of unique and num j is nothing else for the number two so we still go inside of this while loop now we do the same steps basically we don't want to account for the value two anymore so we do three minus two and now our current sum sorry becomes one okay so our current sum is one and now the other thing is this two is not part of unique anymore so we get rid of it over here and now we need to uh and now we iterate i so i is gonna be i plus one which is 2 and now we go on to the second index so basically i is now at the second index and our window currently consists of the values of 1 and 2. and as you can see we do not have the second i anymore so now we continue with our steps which is the same thing we account for this two since we didn't do that yet and we do it the same way we add two over here so one plus two is three and now we add this 2 to the unique list so 2 is now in the unique list and now we check if results have to be 8 or 3 and the result is going to stay as it is since 8 is larger okay so hopefully you understand how this works and i'll try to go through the next few steps a lot more quicker um since there's quite a few numbers here okay perfect so we have one and two in this case so uh j now moves on we have five so this becomes eight unique includes five over here and yeah perfect okay so now we have the number two and we have the same problem which is we have two twos uh since the two is in unique so we do the same steps first we move i uh and actually before doing that we need to account for the one getting removed we do that by subtracting one over here we remove one from unique and we need to uh oh yeah that's it okay and now we iterate i by one so i is now going to be at the third index so it's going to be over here and at the third index we have a value of two so we do the same steps again since the two is still in unique right so we subtract current by uh two making it five we remove the two from unique and then over here of the i value gets incremented by one so i now becomes four okay so if i is at the fourth index and our current sub area consists of the values five and two and we got rid of the other two since it's not in unique so we do the same steps now we're accounting for this two over here we do that by adding it with the current value so five plus 2 is 7 then the unique uh we add that to unique which is 2 over here and that's it right and result states is 8 because 8 is greater than 7. perfect okay so let's just move j again um so now we have 5 2 one so that's a value of eight uh sorry of seven plus one okay so eight uh we need to add the one to unique and that's about it and then we do the same steps again so we come across another two uh so we need to account for the extra two so we do eight minus two uh it's our eight minus five giving us a value of three we remove the five increment the i by one so now i is gonna be right over here at the fifth index now we account for the two since we don't want it either since this two is still in unique um and then over here we get rid of the two over here and uh yeah so that's it so now i gets incremented to the sixth index and so zero one two three four five six we have one and two so now we need to account for this two the way we do that again is by adding that two so we add that two to current making three add it to the unique set and um yeah that's it so uh eight is greater than three so eight stays as the result and finally we move the last thing so j now becomes the very ending and at this point we account for the five so it would be three plus five giving us the current value of sorry eight so we have eight we add five to unique and that's about it so j has got all the way to the ending and that means that we're done and by the ending of this result would have the largest value and if you just look through this we found the largest value quite a few times two times to be specific okay three times actually never mind so we found a value of eight at this sub area of five two one we also found the value eight at the sub area one two and five and we also found it over here at one two five so essentially this method guarantees that you're gonna get the largest value or a sum and the weight works pretty simple too j keeps moving the ending keeps moving and the only thing we're changing is if any condition is met in this case if we have two of if we do not have a unique sub array we're going to move the starting pointer until we get a unique sub area that's exactly what we're doing so now let's see what this looks like in code all right so we're going to start off by defining our variables so first we have our results at zero we're going to have a current sum at zero as well and then we're gonna have our unique set which keeps track of the numbers that are currently in our area and now we're gonna have our two uh in this uh pointers right so we have the pointer i and i starts off at zero and j is going to be the ending pointer except j is gonna be inside of a for loop for so for i sorry for j in range length of none okay so now uh so this j over here gets the ending indices each time so now the first thing we want to do is let's say we do not have a unique value so in that case we're going to go to our unique set over here and where to that we're going to add the current number we're on so the way we do that is we go to nouns and we're going to be adding the number in index j perfect okay and the other thing is we want to account for this number we do that by adding it to our current sum and so curve is a current sum plus equal to nums j alright so we did that and now we do another thing so basically we need to update our result and the way we do that is result is going to be the maximum between the current result value and the current sum that we're keeping track for over here okay now we need to go to the other condition is what is uh what if a nums j is inside of our unique set so in that case we're going to go in a while condition and we're going to stay in this condition sorry by a loop and we're going to stay in this loop as long as nums j is in the unique set okay so as long as nancy is in the unique set we go over here and what are we doing so first we're changing the eye pointer and when we change the eye pointer we need to account for the fact that a current number which i was on is not there anymore and the way we do that is by subtracting that value so current minus equal to nums and we're going to remove it from index i and then another thing we need to do is we need to remove this from the unique set so the way we do that is we do unique and dot remove and we want to give it the value we want to move we want to remove the value nums i perfect and the last thing we want to do is we need to iterate i by one so i plus equal to one so at the end of this we're going to keep going as long as nums j is not in unique and then at that point we're going to exit out and do the same steps over here so by the ending by the time j reaches the very ending we're going to have our results stored in breadth and that's what we end up outputting so hopefully this solution did make sense to you and thanks a lot for watching and do let me know if this video helped you thank you
Maximum Erasure Value
maximum-sum-obtained-of-any-permutation
You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements. Return _the **maximum score** you can get by erasing **exactly one** subarray._ An array `b` is called to be a subarray of `a` if it forms a contiguous subsequence of `a`, that is, if it is equal to `a[l],a[l+1],...,a[r]` for some `(l,r)`. **Example 1:** **Input:** nums = \[4,2,4,5,6\] **Output:** 17 **Explanation:** The optimal subarray here is \[2,4,5,6\]. **Example 2:** **Input:** nums = \[5,2,1,2,5,2,1,2,5\] **Output:** 8 **Explanation:** The optimal subarray here is \[5,2,1\] or \[1,2,5\]. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104`
Indexes with higher frequencies should be bound with larger values
Array,Greedy,Sorting,Prefix Sum
Medium
null
909
hey everyone welcome back and let's write some more neat code today so today let's solve the problems snakes and ladders and this is a pretty challenging problem especially for a medium it's got some good fundamentals to it but there's also some uniqueness to this problem that you can't really get in most problems so we're given an n by n matrix that means it's a square matrix just like this one we see over here it's 6 by 6. each cell is going to be labeled from 1 to n squared is going to be the number of cells of course bait and the first one is going to be at the bottom left that's where the 1 is going to be 2 is going to be next and then 3 then 4 then 5 and 6 right we're going to go to the right in the first row but then we're going to get the 7 right above that and then the 7 the next values are going to be towards the left then it's going to go to the right then it's going to go to the left so basically it's alternating directions the order of the values is what i'm talking about right 7 8 9 it's going to the left then 13 14 15. it's going to the right so we're gonna start at this one and we're allowed to roll a dice and it's a six sided dice so we're either going to roll a value between one through six now we don't actually have to generate a random number so don't worry about that we're going to try every possibility if we roll a 1 that means from this starting position we're going to move one spot that means we're going to move to the 2 spot wherever it happens to be on this grid if we rolled a two we would move two spots forward to the three if we rolled a six we would move six spots forward so we'd move all the way to the seven okay so if this matrix stuff wasn't confusing you enough there's actually even more complexity so we have things called snakes this is a snake and this is a ladder and this problem is based off a board game that i've never really played but i think the ladders are supposed to make you advance forward and the snakes are supposed to make you go backwards but in the context of this problem in the data structure the board itself the 2d matrix the values of the board are going to be mainly negative ones right here you can see the actual values of the board it's mostly negative ones except for positions that have a ladder on them so this 15 corresponds to this position what that means is that in the board there's a 15. that means if we land on this spot then this ladder is going to take us to position 15. so it's kind of like a shortcut so if we actually did make this jump to two that took us one move to do right but in the same move since we landed on a ladder we're going to advance to this 15 spot that doesn't take two moves for us to do the advancement is a part of the same original move similarly if we landed on this snake uh position 17 which corresponds to a value of 13 so if we landed here for whatever reason then on the same move we would end up being pushed back to position 13. now the catch here is if this isn't confusing enough for you that we cannot use two advancements in the same move whether it's a snake or it's a ladder so for example if there was another ladder over here that took us to position you know 28 or something if we uh landed here in one move then we would advance to position 15 within the same move but we can't use a snake or a ladder two moves in a row regardless of what it is basically we're only allowed to use a snake or a ladder once per move so only after we move are we then allowed to use a single ladder but then when we get to the second ladder within the same exact move we're not allowed to use it right within the same move so if we did land on this 15 uh then let's say we got to our second move right then are we allowed to use this ladder no we still can't we have to roll the dice and throw dice means we have to advance between one through six positions okay so i would say probably the hardest thing about this problem is just trying to understand it and let's actually read the rest of this question to make sure that we do the main thing we're actually going to be returning is the minimum number of moves required to reach the last square right so in this case 36 okay so now that we understand the question let's actually try to start with a solution and as always let's start with a brute force approach so initially we're always going to start at the square one and our goal is to get to the n square uh position in the minimum number of moves first thing let's try every possibility right well we know we can move uh between six positions right so from one we can move to two three four five six seven uh but we know that two actually has a ladder on it how are we going to know that because we're going to check the position here right in the board we're going to convert 2 into some coordinate right some row column pair and we're going to use these to index the board and get the value at this position and what value is that going to be well if it was negative 1 then that would mean there's no advancement right basically 3 4 five six seven they all have negative ones in the board you can kind of see it over here even though it's not super clean but they're gonna have negative ones but this two position is gonna have a 15 that means there's an advancement right 15 so basically that means instead of when we land on position 2 we're not really at 2 we're at 15 because we just used the advancement but now the question is how are we going to convert a position like 2 or 9 or you know whatever 28 to a row column pair how are we going to do that well let's just assume for now that we have a helper function to do that because this problem is complicated enough we need to modularize this code so let's not get bogged down on the details we'll work on that implementation last for now let's assume we have one that's working so in our decision tree this 2 will really be a 15. and now let's continue this brute force but as you can tell this decision tree is going to get really huge right because each time each node is going to have six children so i am going to take some you know shortcuts but i'm going to explain the intuition behind it so now let's do three right assuming we were doing the decisions for three we would do okay four five six seven etc but are you noticing anything four five six hey we already have those in our decision tree why would we want to revisit them again and remember we're looking for the shortest path why would we care to reach four five and six after taking two steps even though we reached four five and six by just taking one step so there's no need to revisit any of the positions so how are we going to prevent that let's have a hash set and let's call it visit and let's make sure that we never revisit the same position twice okay so that's one thing that we learned and i'm not really going to draw out the children for these because from this picture and the explanation below you can tell that the uh the shortest path is going to be from 1 to 2 which actually landed us at 15 and then from 15 to 17 which actually lands us at 13 and then from 13 to 14 which actually lands us at uh 35 so you can kind of see the circuit that i'm drawing here and then from 35 we'll take one jump and get to 36. so you can tell okay one move two moves three moves and four moves so that's the path but from this decision tree how can we actually create the algorithm for that well the visit set that we talked about is very important because that will basically limit us for the time complexity being the overall size of the board which is going to be n squared but to actually implement this algorithm it might be possible to do this with a dfs i'm actually not 100 sure but i think it would work as long as you aren't visiting the same position twice but the more natural way to do it is breadth first search and that's usually the algorithm you want to do for shortest paths and let me kind of show you the intuition of why because as we're drawing this decision tree these are the positions we can reach after one move as we continue it suppose from 15 we can uh land at 16 17 and actually 17 will land us at 13 as i mentioned so we can't actually land at 17 but we can also do 18 19 20 and lastly 21 and so these are the positions we can reach in two moves right and the next layer of our graph is going to be all the positions we can reach in three moves etc until we finally reach the last one and so we could possibly create this graph with a dfs approach but it doesn't really make a lot of sense it would be better to reach do this with bfs and then continue that until we finally get 36 to show up in one of these layers and it's possible that i think we might not even have a path to get to that i don't know what that would even look like maybe there's like an infinite number of snakes that just keep taking you backwards and if that is the case uh for the number of moves we're going to return negative one basically indicating that there's no solution but if there is a way in this case there is from uh 15 to 13 and 13 to 14 which will actually lead us to 35 and then from 35 to 36 uh we basically are returning the number of moves in other words the height of this decision tree which in our case is gonna be four and that's uh the same that they had as well and you can read through this explanation if it makes more sense to you but i think that's enough for us to start writing the code but one thing i will revisit is how can we take a value like 9 and then convert it to its row column coordinates first things first let's get the length of this board because we know that's going to come in handy and we know that the board is never going to be empty and let's just define a helper function for now but i'm actually not going to actually write it out so it's going to be int 2 position so basically it's going to take some number like some square whatever the label happens to be in our case it was 1 through 36 and it's going to return some row column coordinates but for now we're not going to implement this let's just assume that it works and then we're actually going to get started on our breadth first search so we're going to create a deck a queue which is usually used for bfs and we're actually going to have a pair of values since we're looking for the shortest path you know one value is going to be what square are we at like that's kind of the position in our case usually with graph algorithms you have a coordinate but like a row column pair but in this case we're just going to use the square itself and the second value is going to be how many moves did it take us to get to this square so initially we're just going to append to our queue one because we know that's the starting position and the number of moves that took us to get there is of course going to be zero and the second data structure we talked about was a set a hash set in this case which is gonna just take care of how many uh which positions have already been visited and then we're gonna get started on the standard algorithm which is bfs but there's gonna be some adjustments we're gonna have to make because of course we're gonna need to convert the square into the actual coordinates as well but as usual with the bfs we're always going to be popping from the left and then up adding to the right side and popping it is going to give us a pair of values the square and the number of moves it took us to get here and then from this square we're gonna do the portion where we roll a dice the value of the dice could be one through six so in python it's going to be a little bit weird of course it's gonna be starting at one but the second value is non-inclusive so we're going to value is non-inclusive so we're going to value is non-inclusive so we're going to put a 7. what this is really doing is i is going through 1 through 6. and then using that i value we can add it to the square that we had which will give us the next square value so pretty simple so far square plus i but now we're actually going to want the coordinates of the next square and you're going to see why we're getting the coordinates in a moment so let's pass the next square in so that will give us the coordinates but what's the point of having the coordinates well if you remember the coordinates are used to get what's the value in the board at that position because remember if the value is negative 1 then we don't really care about it but if it's not negative one that's important because that means we found a shortcut or maybe a snake that's going to take us backwards either way we want to know what if it's not negative one what is the value of that because that's going to be the next square within the same move we made one jump and now we're about to make a second jump because uh you know there's either a snake or a ladder so we're going to reassign the next square to whatever that value in the board happens to be maybe it took us forward maybe it took us backwards and next thing before we even add this next square to the queue we're going to check maybe it's the solution right maybe uh this next square is equal to uh the length squared and if that is the case that means we found our solution and we're going to return the number of moves it took us to get here remember moves was the number of moves it took us to get to this square and then we made one more move to get to the next square so we're going to return moves plus one okay but if we didn't find the solution then we're going to add it to our queue but we don't want to ever revisit the same position twice so let's make sure that this next square is not in our visit hash set and if it's not then we're going to add it to the visit hash set to make sure we never revisited it twice and we're also going to append it to the queue but we know that our q actually has a pair of values which is going to be the square value itself and also the number of moves it took us to get here which is moves plus one okay so assuming that this works we will return the number of moves but let's say it doesn't work then we once we exit the loop they want us to return a default value of negative one i don't even know if that there's an actual test case that covers this there probably is though okay so we've actually pretty much done the algorithm except for the most annoying part which is going to be converting a square to the actual coordinates and to do that i'm actually going to go back to the drawing so the way that this board is actually given to us this is the zeroth row this is the one row this is the two row this is the three row four and the actual columns themselves are actually straightforward zero one two three four five uh but my problem with this is we're starting at the fifth row that's a little bit unintuitive it's basically going to over complicate the calculation in my opinion so wouldn't it be a little bit easier if the way the rows were labeled as 0 1 2 3 4 5 like we're starting at the zeroth row that makes more sense to me and we're trying to get to the last row now you can still do it the other way if you want to it's not a big deal but i'm just going to do it this way i think it's a little bit more simple so the way we're going to do it this way is just basically just taking this board that we're given and reversing it what that's going to do is it's going to reverse each row in the board so that this is going to be the zeroth row okay once we have that how are we going to be able to take one of these values and convert it to this row and this column well one another annoying thing about this is the values start at one in programming we usually start at zero and that makes the calculations work out a little bit better we're gonna whenever we take a value like nine into our function and then convert it to the row column pair we're actually going to take this and subtract 1 from it just to make sure that we're actually starting at 0. so let's say we took a value like 9 and then we subtract 1 from it now we have 8. how can we convert 8 into the row column pair to get the row is actually really easy we just take this value and divide it by the length of the board which in this case is 6. so if we take 8 and divide it by n in this case is six we're going to get one because we're going to round down right and as you can see that does work out in this case now what if we had 12 as the input well we're going to take 12 minus 1 which is 11 divided by 6 that's also going to be 1 so it does work okay but how are we going to calculate the column that's actually going to be really hard and the reason is because it's alternating if it wasn't alternating it would actually be really trivial because for these for the even rows like one through six we can just take the value four and we're always going to subtract one from it so four minus one is going to be three uh and then to calculate the column uh index is just going to be that value which is now 3 modded by 6 and in this case it's going to be 3. and that makes sense right because this is index 0 this is index 1 this is index 2 this is index 3. right so that makes a lot of sense and you know if we jump to the next even row it also makes a lot of sense because uh this row is just going to be 4 plus 12 and then that 12 is just going to get canceled out by this mod operation and then 16 minus 1 is going to be 15 modded by 6 is going to be 3 again so that makes sense right all of these are going to be 3 but the annoying part is uh you know when we make two jumps we're adding 12 that makes sense but when we make one jump we don't really know what we're adding because this is alternating remember we're going this way and then we're going that way so how do we correct that well we're going to check if the row is an odd index we're going to do some special calculation we're still going to say okay with our general calculation where we just take that a value minus one and then mod it by six we're gonna end up saying seven is actually over here but it's not over there we actually want to put it in the correct spot and when we try doing 12 we're going to find that the call the column for 12 is going to be over here but it's not we actually want it to be over here so how are we going to do that well as you can tell we're basically flipping uh these positions right this is going to be flipped with this and then this is going to be flipped with this and it's going to go both ways right so the way to kind of do that uh let's just draw it out zero one two so to actually do that what we're going to do is we're going to take the length let's call that n is j you know just the dimension minus 1 because n is going to be 6 but the max is really a 5. so that's where the minus 1 comes from and then minus whatever that column that we end up calculating so in this case if we got a five if we calculated a five uh we'd say six minus one minus five which is going to put it to be zero meaning this is going to be moved over there if we calculated a zero we'd say okay six minus one minus zero that's going to be five so that's going to take this zero and then put it at this position so that's really the intuition behind it maybe i spent a little bit too much time on this part but now let's just code it up okay so as i mentioned first we're going to calculate the row and that's going to be uh square and we're always going to subtract 1 from the square and then we're going to divide it by whatever the length of the board was which we calculated up here and this is integer division in python that just means it's going to round it down which is exactly what we want to do okay and then we're going to calculate the column we're going to calculate it in the naive way first make sure to subtract one from the square and then just mod it by the length that will work for us as long as the row is not odd if the row is odd and we can figure that out like this so in this case if the row is odd we need to reassign this column and we're going to do it exactly how i said we're going to set a column equal to length minus 1 minus itself okay so that's almost the whole code but one thing i almost forgot is we were actually going to reverse the board because remember we want the zeroth row to actually start at the bottom of the board so just by reversing it we can do that and that's why this function is pretty simple if we didn't do it that way it would just be a little bit more like we'd have more calculations that look like this one and i don't really like explaining how this works now let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient the overall time complexity of this is going to be in the worst case n squared because we could end up visiting every position in the board and the memory complexity is also going to be that because of how the breadth first search is working we could have you know every value be in our queue 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 if you'd like to further support the channel and hopefully i'll see you pretty soon thanks for watching
Snakes and Ladders
stone-game
You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row. You start on square `1` of the board. In each move, starting from square `curr`, do the following: * Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`. * This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board. * If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`. * The game ends when you reach the square `n2`. A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder. * For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`. Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`. **Example 1:** **Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\] **Output:** 4 **Explanation:** In the beginning, you start at square 1 (at row 5, column 0). You decide to move to square 2 and must take the ladder to square 15. You then decide to move to square 17 and must take the snake to square 13. You then decide to move to square 14 and must take the ladder to square 35. You then decide to move to square 36, ending the game. This is the lowest possible number of moves to reach the last square, so return 4. **Example 2:** **Input:** board = \[\[-1,-1\],\[-1,3\]\] **Output:** 1 **Constraints:** * `n == board.length == board[i].length` * `2 <= n <= 20` * `board[i][j]` is either `-1` or in the range `[1, n2]`. * The squares labeled `1` and `n2` do not have any ladders or snakes.
null
Array,Math,Dynamic Programming,Game Theory
Medium
1685,1788,1808,2002,2156
1,394
guys today we're going to be looking at leak code problem 1394 find lucky integer in an array in this problem we are given an array of ins and need to return the largest integer that appears the same number of times in the array as its value for example we looked at the first example here 2 appears in the array twice so we return 2. if we look at the second example we see there are multiple lucky integers as one appears once 2 appears twice and 3 appears 3 times here we would return 3 as it is the largest lucky integer we see that both the length of the array as well as the values in the array will be between 1 and 500 inclusive we return negative one if there are no lucky integers her approach will be to use a hashmap which is a data structure that is very versatile when solving whiteboard questions the benefit of the hashmap is that it is an of one operation to do a retrieval what we will do is loop through the array and maintain an entry in the hashmap for every unique integer we see at the end of the loop we want to have a table of number to frequency where we have each integer that appears in the array as a key and how many times that integer appears in the array as its value after we do this we will be able to go through the hashmap to see which entries have the same value for key and value and out of these entries return the largest first we will need to create our hashmap and initialize our answer variable to negative 1. this will be in case there are no lucky integers in the array next we need to loop through the array and populate our table if there is already an entry in the hash map dot put num map dot getter default num 0 plus 1 will increment the value for that key if there's not that line will add an entry in the table with key equal to num and value equal to 1. a git or default tries to get an entry in the table with the key num if it exists it returns the value for that entry if it doesn't exist it returns zero next we want to loop through each entry in our hash map if the key and value are the same then we want to see if this is the biggest lucky integer we have seen thus far if it is we update answer when we are done with this answer is the largest lucky integer in the array we go ahead and click submit and we see that our submission was successful this approach has of n space complexity because we create a hash map to store our frequency table that will have at maximum in entries the runtime is o n as well because we loop through the input array once and then through the hash map entries once as well and that will do it for today's video so be sure to like and subscribe and let me know down in the comments which problem i should tackle next
Find Lucky Integer in an Array
find-lucky-integer-in-an-array
Given an array of integers `arr`, a **lucky integer** is an integer that has a frequency in the array equal to its value. Return _the largest **lucky integer** in the array_. If there is no **lucky integer** return `-1`. **Example 1:** **Input:** arr = \[2,2,3,4\] **Output:** 2 **Explanation:** The only lucky number in the array is 2 because frequency\[2\] == 2. **Example 2:** **Input:** arr = \[1,2,2,3,3,3\] **Output:** 3 **Explanation:** 1, 2 and 3 are all lucky numbers, return the largest of them. **Example 3:** **Input:** arr = \[2,2,2,3,3\] **Output:** -1 **Explanation:** There are no lucky numbers in the array. **Constraints:** * `1 <= arr.length <= 500` * `1 <= arr[i] <= 500`
null
null
Easy
null
345
hey everyone welcome back and today we'll be doing another lead got three four five reverse Bob balls of a string an easy one given a string as reverse also all now only all the vowels in the string and returning all vowels are a e i o u and they can appear in both cases like you can see from the example and one and two so what we'll be doing is just converting our string to a list and to make things more easier for us and whenever there is a vowel and also making a list and two pointers so whenever there is a vowel at the very left and the very right we will just swap do the swapping otherwise we will yeah increase the pointer at the left if there is no um no vowel at the left or at the very right so that's it now let's code so I will be our and let's make it left so left will be equal to 0 and upper right pointer will be equal to length of s minus 1 and also our bubble Wells list and new type casting our list to I should have name it like what do we name it reverse vowel are we okay and uh we'll be casting our string to it and trying to it and uh we'll be filling our vowels which will be like this a and a e I oh and there is like a double okay so in this case there is like i a e i o u now the upper one now uh in Upper cases uh e I oh EQ so let's now just set them up okay now we are good to go so like okay we are done yes a e i o u so that's it now what we'll be doing is while our left pointer is less than and less than our right pointer if the value at r b at left in vowels left is in vowels yes vowels and also we want to check at RV at the very right in vowels bubbles if yes we will just do the swapping like this at RB and right I'll just write okay and now are we at right shall be equal to right and then left okay now we have to increment our left y1 and decrement our right by -1 -1 -1 and if these both are not the cases then what we will do in the alif case if the uh if not uh RV left in vowels what we will do is just increment our left pointer then because we know that it is not found on the left side so if not r v right in vowels we will increment our decrement our left and after doing this we can just return um uh string by joining it join by RB joins I know it's join our joins I don't know but let's see if this works yeah it works and let's submit it and yeah that's pretty much it
Reverse Vowels of a String
reverse-vowels-of-a-string
Given a string `s`, reverse only all the vowels in the string and return it. The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once. **Example 1:** **Input:** s = "hello" **Output:** "holle" **Example 2:** **Input:** s = "leetcode" **Output:** "leotcede" **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consist of **printable ASCII** characters.
null
Two Pointers,String
Easy
344,1089
86
hey guys how's everything going today let's to take a look at number 86 partitionless we're giving a link list and the value separated such that all nodes less than X come before nodes greater than or equal to X we're giving it less like this one four three two five two and target is history okay so the output should be 1 2 4 3 5 because 1 2 to use some 1 &amp; 3 &amp; 3 4 3 5 because 1 2 to use some 1 &amp; 3 &amp; 3 4 3 5 because 1 2 to use some 1 &amp; 3 &amp; 3 4 3 5 is bigger or equal to 3 so how should we do it I think this is just a pretty straightforward we traverse through the linked list with one pointer and then if it is smaller than it we append to the this half I mean some other half and the bigger or equal one is latter half right and then at last we put them together like PPAP and yeah it should work okay so let's do it let's first create two hats tap enter right so const p1 equals new list node 0 goes to me - it was new this note okay Casta to me - it was new this note okay Casta to me - it was new this note okay Casta P equals head oh yeah okay so while P this is the traversal P equals piece next and the return p1 I think it should be next p1 next equals p2 next right okay we finally we return P what's next and this is when do now for each node if peace value is more than target which is X if it's smarter we put it to p1 right okay now oh I made a mistake start it should be start one this should be start to and let P 1 equals start one at p2 equals start to okay now if this node is smaller than it so we need to append to p1 slack next mm-hmm short P ones next equals E and P and the P which means we already append it to P but now we need to cut it off the chain right we need to cut it off cut off which means P equals P the next so we need to remove this one people's piece next okay p1 next which is now P but next of course me and p1 equals p1 next yeah this should that should do and then if a speaker but the speaker would do the same we put it to Pete could start to yeah copy p2 next equals P copy all equals P 2 and P 2 its to reveal it we view it let's say we make it 1-1 is smarter so here say we make it 1-1 is smarter so here say we make it 1-1 is smarter so here okay p1 is next equals 1 ok P now go to 4 and P 1 which is p1 is next which a new position for one will be Newell and P 1 equals 1 hmm yes you work its we're on the code Oh assignment 2 constant variable ah my bear or Shekar you slit cannot set properly Lu next up nor t1 next if P is more right so I'm sure not oh yeah my bad if it's not yeah it's okay if p1 next is not know I'll end it alright always these educators just to freak me out mm-hm P 1p whoa mm-hm P 1p whoa mm-hm P 1p whoa ah my bad I made a really nasty mistake if p1 I should not do this is not right I should say he wants next should be B to t2 and return start Wanda next yeah oh no start this should be starting one start to next ah it's nasty my bad huh yeah I think we should have to say review more before her we jump to the conclusion time complexity well we Travis all the notes through ones and the cost extra two points so it should be time-space it's constant I should be time-space it's constant I should be time-space it's constant I mean it's nasty to hear because I didn't pay enough attention to so yeah let's be more careful next time submit of the past cool so it's already near time there's nothing more we can improve I think and it's pretty straightforward yeah okay that's all for this one see you next time bye
Partition List
partition-list
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`. You should **preserve** the original relative order of the nodes in each of the two partitions. **Example 1:** **Input:** head = \[1,4,3,2,5,2\], x = 3 **Output:** \[1,2,2,4,3,5\] **Example 2:** **Input:** head = \[2,1\], x = 2 **Output:** \[1,2\] **Constraints:** * The number of nodes in the list is in the range `[0, 200]`. * `-100 <= Node.val <= 100` * `-200 <= x <= 200`
null
Linked List,Two Pointers
Medium
2265
1,277
today's question is count square some matrices with all ones or in other words given this picture how many squares can you find so we're going to solve this with dynamic programming an idea behind dynamic programming is we want to split this question into subproblems and then you know using those subproblems come up with our solution so the subproblem that we're going to ask is if I add you as the last element how many new squares can I form because of you so for example that say we're reading all the way down here and then we're about to read the last element so this element is a 1 so how many new squares can we see because we added this last element well we have this square right here with a size of 3 so we have this one right here and then there's also this 2x2 right here and there's also this one by one so in total we created three new squares by adding this last element now it's actually also the same as the maximum square size that we can form so the number of new squares is equal to the maximum square size and this makes sense because if you can make a square of size 3 by 3 the numbers inside it must hide a square of size 2 by 2 that uses you know the same lower right corners of our new element and also of one by one so three new squares that's also the maximum square size so we can kind of twist this problem into if I add you as a last element what's the maximum square size you can form and the way that we solve this question is our algorithm just becomes asked this problem this subproblem for each element and total up the new squares so let's try again so here is our input and let's see what we'll do so we'll read it so we have 0 you can't create any new squares with 0 and then we create one new square here one new square so one new square one nu square one new square one here and then one here now what about this case with this case we can create a square of size 2 so that means we created a square of size 2 but also a square of size 1 so this will be 2 similarly this will also be 2 this will be 0 this will be 1 this will be 2 so for these two right here and then as we've discussed before this will be 3 now so far I have done it sort of just by you know i observation into how many squares it looks like it can form but how do we programmatically confirm this so the idea is when we're at this point we know that ah so when we're trying to figure this out we know three important things so the first thing we know is that this the element besides us can make a square of size 2 the other thing we know is that the element on top of us can also make a square of size 2 and then lastly the element that is I guess diagonally to the left of us also can make a square of size 2 so this kind of tells us how far we can push each boundary right so this tells us that going up we can go by 2 where we know that it will form a square going to the left we can push by 2 and also because it's a square it's not enough just to have up and left right or else we run into cases like this so we also need to know how far can we push diagonally and that's what this number tells us we know that we can push diagonally here by 2 so if we can push diagonally by 2 by all three sides then that means this we can create a maximum square size of 3 so that will be this one right here this maximum square size of three which means that there's three new squares okay so what if one of them happens to be a different number ring so which one is the most important one so let's say we're trying to figure this out we know this creates a square of size I don't know let's say that say for this creates a square of size two and this creates a square of size three so what gets limited here so we have our four here one two three four we have our three here so it probably looks something like this square of size three and then we also have our square of size two so you can see here the maximum square that we can make with this last element if this was a one is limited by the smallest element so it's limited by the minimum of top left and diagonal neighbor because this means while we can push up this by four and we can push up here by three we can only push that agonal by two this means our biggest square is always going to be limited by the smallest number so in this case the answer here will be three okay so let's see how we can code this out all right so we have our matrix and the idea is that we want to be able to know what are what part left neighbor is left neighbor what are right neighbor is and also what our diagonal neighbor is so that means there is a couple of edge cases that we have to handle in the beginning so one we are sorry not there right so this would be a top neighbor so number one is that for our let me just draw this out if we have something like this one if we're at the top row we don't have any top neighbors so that's handled this edge case separately so for int I equals zero so the zeroth row so I guess I'll use row to be more explicit actually it'll be the column so it will be the earth column co-investing matrix at the zeroth column co-investing matrix at the zeroth column co-investing matrix at the zeroth row dot links if matrix at the zeroth row of this column is equal to one then count plus right guess the biggest square you can make at the zeroth row it's just zero because you don't have a top neighbor to make your square even bigger so this handles are no top neighbor edge case so next let's do the no left neighbor edge case in which case we want to loop through every single row so in true relisting matrix thought length row plus and then if matrix at this row at the 0th column equals one then count plus okay so now we've handled both this case and this case we want to make sure that we don't accidentally double count this one so what we'll do here is we'll start at Row 1 instead of row 0 so we don't double count this first element here so that means at this point we just have to read the rest of our matrix and we can be sure that there is always a left neighbor a top neighbor and a diagonal neighbor so here we'll read rest of our matrix so we'll have four intro equals 1/3 less than matrix lot length plus and 1/3 less than matrix lot length plus and 1/3 less than matrix lot length plus and four and call them equal to zero and call them actually we're at the first column now because we are reading just this so everything that excludes the first row first column less than matrix your darling called plus okay and then what we want to do is we want to get the minimum of our left top and diagonals look at the minimum of left top and diagonal so actually this only makes sense if we had a candidate element that can expand our square account to begin with so only if this is equal to one what we want to do all this calculation so if matrix at row column equals to one let's do all this actually what I'll do here is I'll do not equals to zero and you're going to see why later okay so how do we get the minimum of left top and diagonal we'll have our mid side so the minimum square that we can make is going to be one plus math dot minimum of matrix at row minus one column matrix at row column minus one and then we'll wrap this around with another math common to get the minimum of three elements here which will be matrix at row minus one column minus one fruit diagonal pair okay so this will be our maximum square so this is our squares so the maximum square length is also the number of squares that we can make with this so this will be our squares and then we can do count plus equal the amount of squares that we can make now what we want to do is we want to actually update these values right so when we were reading it we were able to read that this was a four and this was a three so we're going to write in place back to our matrix that at this row and at this column is going to be equal to squares so that's the maximum square that we made that way when we are processing later on the DP we have the correct value here for them to read okay and then at the end we can return squares sorry not squares count let's give this a go ooh let's see what is this error this is saying on line 13 right here oh so this should be a semicolon cool so I'll submit and then we can chat about the spacing runtime complexity okay so for the runtime complexity here we can see that we are just reading every element in our matrix and doing some constant time operations on them so I would say that the runtime here it's going to be oh of M times n so the size of this matrix so rows times columns now for the space here I could be cheeky and say this is constant time because I wrote in place into the matrix that they gave us now however if they don't allow you to write to this matrix you would have to create your own matrix in which case it would also be rows times columns but we can do actually one step better here so you can see at every point we only care about the top neighbor and the left neighbor and the diagonal neighbor so we only cared about what was in the row above us and also what was just previous to us so we can express our space as just the previous row so whatever the size of a row is plus the previous element so it's really just all of rows if you want to get even more creative you can actually test if which length is bigger rows or columns and then optimize your solution for the smaller row or smaller column counts by kind of rotating how you read them read the matrix anyways that's it for today and I'll see you on the next one
Count Square Submatrices with All Ones
largest-multiple-of-three
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3. Total number of squares = 10 + 4 + 1 = **15**. **Example 2:** **Input:** matrix = \[ \[1,0,1\], \[1,1,0\], \[1,1,0\] \] **Output:** 7 **Explanation:** There are **6** squares of side 1. There is **1** square of side 2. Total number of squares = 6 + 1 = **7**. **Constraints:** * `1 <= arr.length <= 300` * `1 <= arr[0].length <= 300` * `0 <= arr[i][j] <= 1`
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Array,Dynamic Programming,Greedy
Hard
null
384
That's Hi Everyone Welcome To My Channel It's All Your Problems Safal And Are Forgiven And Journals Ghritam Safal Are All Competition Are Like A Result Of The Video subscribe to subscribe our Channel And subscribe The Amazing Click on the link for 12345 Safal 100 We Need To Subscribe Mode Off Eid Canteen Factorial These Three Factorial Ways Swayam Six Different Permutations And Return Of The All Subscribe Liquid Original Given Which One To Three For This Channel Subscribe Indian Students Of Very Small Idu Of Subscribe This Video Subscribe Our Channel We All Set To Return To Exit Chinese To Hole Many In A Friend Like Gambhir And Entrance Exam Copy This Know In What We Do Subscribe Elements For This Number Of Units Wikinews Security Very Time Consuming And You Know The Little But Library Of Programming Languages subscribe The Channel and subscribe One Pan Other Is Penderm Plus Itself In Dishas Everywhere Will Have Use This Method Next Sorry Maths 10th Pass Three Number Of Elements Thursday Morning 5.0 Random Numbers Elements Thursday Morning 5.0 Random Numbers Elements Thursday Morning 5.0 Random Numbers From 21 - 1the subscribe Video from From 21 - 1the subscribe Video from From 21 - 1the subscribe Video from Multiply Range and Integral Part of Its Not Vidron From This That Know How To Generate Successful Dresses Safal Araria Visan Size Safal Are Of Science From This And Copy From Original They Know What We Can Do Subscribe And Do Subscribe Tiger Shroff From 0 To Do And Difficult To Start From Death Will Start From - To Start From Death Will Start From - To Start From Death Will Start From - Veer 1000 Will Do Subscribe Copy Paste Original One Two Three Lena Hai 300 Subscribe Doob School Hai And I Will Pass I Number Random Extend Software Passes Through If Hair Soft This Will Generate Random Number Do That Aaj Bill Pass I Editor Sudhir Will Dheriya Nai Between You and I have so let's word is will participate in waiting b n x to avoid we update value soft copy temporary and subscribe from this point to that is the value of the world tour finals original and will vanish from no veer Veer Safal Fraud Net Users Copy from Original Are No What We Do We Need to Subscribe Safal Dot Land Mine Chairman - No Will Generate Random Land Mine Chairman - No Will Generate Random Land Mine Chairman - No Will Generate Random Induction Do A For Right One Shades Will Start Value In Temporary Variable From This successful-fail of Temporary Variable From This successful-fail of Temporary Variable From This successful-fail of next 9 we would not willing to divine journey from this successful of noobs successful subscribe definitely subscribe pims nuvvu subscribe to compile codege ubuntu from minor under 500 to 1000 subscribe apne cancer medical to connect with there is the role answer for Case No I Want To Than Expected Reset Hindi Set Veer Written A Notice Wrong That Show SBI Just Copy Milk This Is The Problem That To You Alone Are A Person Will Die Subscribe The Channel Please subscribe and subscribe the Channel Video Problem Haldi Are Very simple but you can solve problems thank you
Shuffle an Array
shuffle-an-array
Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling. Implement the `Solution` class: * `Solution(int[] nums)` Initializes the object with the integer array `nums`. * `int[] reset()` Resets the array to its original configuration and returns it. * `int[] shuffle()` Returns a random shuffling of the array. **Example 1:** **Input** \[ "Solution ", "shuffle ", "reset ", "shuffle "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\]\] **Output** \[null, \[3, 1, 2\], \[1, 2, 3\], \[1, 3, 2\]\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.shuffle(); // Shuffle the array \[1,2,3\] and return its result. // Any permutation of \[1,2,3\] must be equally likely to be returned. // Example: return \[3, 1, 2\] solution.reset(); // Resets the array back to its original configuration \[1,2,3\]. Return \[1, 2, 3\] solution.shuffle(); // Returns the random shuffling of array \[1,2,3\]. Example: return \[1, 3, 2\] **Constraints:** * `1 <= nums.length <= 50` * `-106 <= nums[i] <= 106` * All the elements of `nums` are **unique**. * At most `104` calls **in total** will be made to `reset` and `shuffle`.
The solution expects that we always use the original array to shuffle() else some of the test cases fail. (Credits; @snehasingh31)
Array,Math,Randomized
Medium
null
1
Hello everyone welcome back my channel Hi I am Sunny and I am a software engineer today in this video we are going to solve a problem from leedkut the name of the problem is tu even and the difficulty level is easy it is easy so let's see the problem statement so Problem statement what is life and are of integers numbers and wait target return d indigent of tu numbers true date give add up tu d target ok means a target value will be given and it are of integers where basically they need tu find tu numbers true Date add them they get this target so yahan pe kya bola u mein assam date h input wood have exactly one solution ok and human note us de se element to kya bol raha hai like jivan this aryan targets what they can suma date par Every life input there bill be only one solution is ok and there is one condition date they can note that element and you can return answer in other order so basically they need to return this so for and every element has an indicator So basically we have to return those indices, whatever value is added to this target, so let us understand it with an example, so here an example is given, Jeevan and Namas are 2750 target value and which is here by adding 2 and 7. Let's get nine right here, brother, the index of you is zero and seven is one, so we have to return this, so I hope the problem statement is quite easy, let's see another example, 324 and the target value of six, so they. No date adding up tu and four bills give you one and its index which is index of 2 one and four index be one tu and here pe one think which you should notice which is the order and the order of indices which you are returning Ho IT Jump B Anything Like You Can Also Return Tu Comma and Zero Comma 1 Thoughts What's the Difference So let's go to iPad and understand how we can solve it, so once here I write the input of the example given. And no they have target 9 and before this, let's check the constraints of the problem statement once more. Okay, so one thing is clear that we will always get a solution for our input. How to get it if we don't get it, then what is the return? Have to do, they have not said but Bill C in D course according to you D problem statement Bill always have one solution Okay and one thing that is there is the constant what is given which is your name length means hey whatever is the input its length four and which Values ​​will be Hey I will have that colored and which Values ​​will be Hey I will have that colored and which Values ​​will be Hey I will have that colored from mines 10 to the power nine and the target value is also colored from - 992 What is value is also colored from - 992 What is value is also colored from - 992 What is positive can you come up with an algorithm date this let's order of n² So let's see basically an Optimus here. Expecting for the solution but bill c's what is our night solution and give ho they can optimize but di i hope contest is clear so life de constant one thing you can see that if and if you come up with de inka Solution This solution I gas will be accepted because here jo max is consistent length of d is this 104 and in n² what will this become 10 tu d power 8 will be right so tha should be acceptable till analysis and crossing tu our nine your jo Time complexity is if you cross 229 then this is mostly not accepted right solution but here on life D can't understand what they can understand and if they all meet night solution which will be of order of n square complexity then also give that bill B able you submit d solution because the max size here is 10 tu power four let se in d how if you are living of 10 tu power four element if you implement the solution then what will be the overall complexity which will be 8 And date should be acceptable tent tu d ninth is your acceptable ok but if this is the constant then that is 5 * 10 then 10 tu di constant then that is 5 * 10 then 10 tu di constant then that is 5 * 10 then 10 tu di power 10 If you want to submit the solution then you will not be able to because it is greater than Tendulkar Otherwise, there will be an optimum solution, okay if we increase this constant a little bit, okay, so I hope the content is also clear, let's quickly jump, you pack, understand the solution, so here the first thing we see is a hey given. What has happened is that the target value is given, so this is the nicest solution which will come to the mind of anyone who is coding with some pen, that we just have to find two such numbers which are not equal to each other, so what do we do here? Could basic pay wood be you user nested on here pay you bill have painter and on every I you bill check on every us by summing nine a raha hai so on example what am I saying that from late they have this you 711 15 So here we are finding pay late i is initially j second element pay so every i bill check but every k after adding that comes to nine so what are we going to do they are bill c 2+79 so this is pay nine a Let's they are bill c 2+79 so this is pay nine a Let's they are bill c 2+79 so this is pay nine a Let's modify it a little bit, just do some iteration, so I do this, from earlier, let's put some random value A here and put 7 here. Okay, now our I which is here, what will happen now, first of all we will check. Will point to 11, tu plus 11 13 is not happening, will increment the check 2 + happening, will increment the check 2 + happening, will increment the check 2 + 15 17 This is the dot 2 + 7 Right tu plus seven 15 17 This is the dot 2 + 7 Right tu plus seven 15 17 This is the dot 2 + 7 Right tu plus seven kiya to nine a gaya so what will we do with this, what is the index of I N J? By storing the value of k we can return this bill be your answer so this is very simple means you put another loop on k every i you are comparing with j ok if in this sequence if there is no match Your value, then you increment i by some increment and move according to it. Okay, so I hope it will be clear. This is a neat solution using n², by doing which you can reach your solution where what we are doing. We are adding each element for each element. If you add it with 7, you will add it with 11, you will add it with 15, you will check the value, it will check whether the target value is there or not, if it is not then we will increment it. We will check by adding each value with seven and then with seven. If this also does not match then we will check by adding the remaining value on the value of 11. Then this is a very clear solution which you must have understood. We see one more thing that they can do, they can optimize, we know n² solution but this is one thing which must be coming in the mind of children, it is very big, we think that we can do it, so here you You will see that to create confusion the sample input given to us was sorted right but if we do 2.2 here then sorted right but if we do 2.2 here then sorted right but if we do 2.2 here then our answer will be what is the right sort for IT? We know that we have a very common approach. Told you, if you don't know then you should take a look at what usually happens in points, you take a painter here and a painter in another, okay what do you do, you add I and John here 2 + 15 What will happen 17 Okay, I am 2 + 15 What will happen 17 Okay, I am 2 + 15 What will happen 17 Okay, I am basically cleaning 2 points and proof and seeing whether it is applicable on this or not, it will come in its one of D solution, basically we are showing the 2.2 approach here where Also, you showing the 2.2 approach here where Also, you showing the 2.2 approach here where Also, you try to analyze whether this problem can be solved by Painter approach or not. Okay, so you usually do quantum numbers. What is our error? It is sorted. Okay, and we add them and see the value. Kya raha pe 15 plus tu kitna a raha 17 vich is greater dan right is greater than our target value so we know that if we point our K in this direction then our overall sum will decrease. Why because on this side the volume is decreasing 15 11 7 and 2 where s If we want some value which we have to increase then we will move i So what will we get here 7 will get 11 will get 15 Right so what will happen from this U BILL ALWAYS CUP IT So now we have 17 A. Let me drag it to see 79 and 17 are greater so what we have to do is we have to decrease this sum value. To decrease it which point do we have to remove? If we move i to ko or k then what will happen next to our i 7 ko point. And what is seven plus 15 becomes 22 which matches it higher right is greater than 17 so we usually we should try to decrease this sum value so for this we have to move K towards left because we know if we K So our next one which will point to this element which is 11 and give them no 2 + 11 is 11 and give them no 2 + 11 is 11 and give them no 2 + 11 is 13 So now we have decreased this but style this no note target value right so forget to decrease this right so on D What we can do is move farz and if you move jo then next jo will come 2 + 7 = 9 no this is matching d come 2 + 7 = 9 no this is matching d come 2 + 7 = 9 no this is matching d target value so this will be our answer but this is true when you arrange it sort it but In the example given in the second example in our how, the Namas there is aam tu comma four and the target value is six. Okay, we basically have to return what index right zero one. In this how we are, you are plus. Four is happening six, so in the answer we were writing, we have to return one comma, we have to return the right index. Now think, this is not already sorted. If we sort it, what will we get? We will have this in sorted form. 2 3 4 Now if you find a solution on this using 2. So our i and k will be 2 + 4 = 6 A and i and k will be 2 + 4 = 6 A and i and k will be 2 + 4 = 6 A and its index will be like this, what will be its index now zero, now you are seeing this is wrong. It will be done brother, the answer coming here was one comma, just because we sorted it, obviously the elements are changing and according to that, if we look at the index, then it is zero, this answer will be in color, then it will be clear from this. What's going on is that we can't do the 2.2 approach here going on is that we can't do the 2.2 approach here going on is that we can't do the 2.2 approach here by shortening our input because we're dealing with this right here, we have to return the indies coming in D and off D and if we move the elements here and there. So the index that comes to us will be wrong. Okay, so here 2.2 approach will not be applicable. 2.2 approach will not be applicable. 2.2 approach will not be applicable. Okay, if we are told that we have to do only the elements, then we do 2.25, do only the elements, then we do 2.25, do only the elements, then we do 2.25, we shorten it, you apply the point. And whatever target value comes after adding the elements, they return the elements right but this is not the ask of the question is that we have to return the index, then now if this is not happening then what can we optimize further? If it is applicable, know if we can give only elements then you can do painter in order of n, we could have done the solution right date bill be one more variation of this problem where on pay you are allowed you return are elements instead of index then in that We could have used it, now let us simply see how we optimize it, there can be a way to optimize it, let me tell you, many people must have done GS also, what do we have to do, what do we do every time? What we are doing is that we basically need two values which by adding this value becomes nine a right so what can we do is we can make a map of it and I will tell you how to do it, first of all we take a map of a team okay There is no value in our map yet, now what we will do is we will do simple hydration on our input ok what we have to do for that we have to run look on one on our input air ok so let's start with the first i first element ok Yes, we will check. What value do we have on I? If you are there, what other value do we need? To achieve 9 - what other value do we need? To achieve 9 - what other value do we need? To achieve 9 - 2 = 7, we need 7. So, check the bill. Seven exists in our 2 = 7, we need 7. So, check the bill. Seven exists in our 2 = 7, we need 7. So, check the bill. Seven exists in our map. Right now, I, you don't. If it doesn't exist then we bill move to our next element we are using a single look where we bill it through d first element in d last element and bill c its complement value exists in the map or not so But the example when they start with D is the first element, our first element is Tu, the complement value we need to achieve nine is seven right because we know that 9 - 2 = 7, if we get seven know that 9 - 2 = 7, if we get seven know that 9 - 2 = 7, if we get seven then we add Karenge tu pe aur nine achiev karenge, but where are we checking this complement value? So who has to say this complement value? We check it once. We basically mince whatever element we are getting from the target value. Two 9 - 2 = 7 so we call this the Two 9 - 2 = 7 so we call this the Two 9 - 2 = 7 so we call this the value of complement. Okay, so now let us see our map is not our map so we will simply move our i to the next element so we store our previous value in the map. We will do it with index, okay, so what will be our value stored here, what will be the element, its index is also indicated, give right zero one two three so I was just pointing to the element, what will we do there, we will take its index and its If we store the value in the map, then the value stored in the map will be tu and its index value is s zero ok no i moves tu d next element which is 7 ok 7 now what will be the complement value of 7 9 - now what will be the complement value of 7 9 - now what will be the complement value of 7 9 - 7 9 - 7 = 2 Now we will check whether you are present 7 9 - 7 = 2 Now we will check whether you are present 7 9 - 7 = 2 Now we will check whether you are present in the map so no way see date you are already present in the map what does it mean that we had previously found you so now we know that if we do 2+7 then we will get nine a know that if we do 2+7 then we will get nine a know that if we do 2+7 then we will get nine a right so Now what can we do, they are already standing, this index is like here is 7, so I can take this index which is one, okay in our answer and we can take an index from the map where you store it, so if you Just get this key value right so if you just get D key you will get its index which is zero so no you can write this next is ok I hope will be clear like you can do on every element which element For this, you do not get the complement value, you will keep inserting it, so let's modify it a bit, here the pay would have been 3 by late, okay it would have been three, if it had been 7 stories, then now we will have more value in your map, more right yours. Aay here pe aata couple met value dekha hai Three ke liye nine ke liye six nahi hai right to wa bill insert three 15 value would be minus six jo ki nahi hai to three aur last mein bill get seven Completion value of this is already present here in the map so we will make its index based on it so I hope you have understood the solution with the help of one and a map we are able to come off the indices right on the right. Number I hope you have understood this in a very simple way and today they are using one single loop they can see the time complexity which will be of the order of N. Okay let's see it once in the code so here is our code so I have written this in Java, you can convert its balance C plus this with Python code but no let's turn on Fox on and they are so they are living this is a method you some which will return the interior and I we know that they Need you return you ints Okay here we are taking in the input parameters and taking the target the first thing we are doing is creating a math and let's we are using one on loop you white red through this are and in this What we are doing is target mines whatever Eric element I am pointing to and I am mining it right so what will it get is the remaining value which you want which is nothing but you are complement value and what we are checking is the map. I have that content means not if not like this line checks if map country note content d remaining value give you simply put this value inside d map with its indices a of i your value will come and i will be your index simply store You are giving if the complement value is not present. If it is present then you simply need to return and new are with current index. Okay and you can return by getting the remaining complement value index in the map. If this formula is over. And you are not able to write all other solutions give you bill always return minus one right so basically this line should not be executed on D problem statement because it said that they bill always have one solution on input so this is Just off the back how where you don't find other player which adds up to your target value so I hope this is clear and so you can see we are just using a single per loop date mains it is order of in time complexity and today they R String N Our Key Value Pairs In N # This Would Be Of Value Pairs In N # This Would Be Of Value Pairs In N # This Would Be Of Order Of In Why Because In D Voice How Let Se If You Need To Add Which D Elements In D Map Right Like It May Be That You Have The Complement Value Which Stage And D last index of D are so how do you bill and up story which is D in mind's one elements of right so let's understand this once let me show the iPad because what am I saying that from late as I have done this Example is shown rate where you have values ​​2 3/11 157 rate where you have values ​​2 3/11 157 rate where you have values ​​2 3/11 157 right and this is 7 and that is right and they are no adding up 7 weeks you bill get well so your look will work it will work for every element right and -1 Till the element and when and in right and -1 Till the element and when and in right and -1 Till the element and when and in that element will come and let your map bill look something like this where you have already stored in mine one elements so that's why I am saying that the space complexity of what will be of the order of n and the time complexity will also be Order of N So Thoughts from this video I hope that you have learned something new from this video, if you have learned then please like the video and share it with your friends and yes follow this series because this is your This is going to help a lot in placements and if you have preparation, other products based on companies where you know that ten rounds are mandatory, this series will also be very helpful, so see you in the next video, till then on my channel. Check the rest of the content and check the shots. Short quick tips which will help in your interviews. So thoughts which buy but no thank you for watching.
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
147
Indian Oil Welcome to Learn Repeat Today's Date of the Number Four Inches The Name of the Problem Is Information Short List Na Chipke Na Problem Solve Problems Sheets for Telling List Using These Short Numbers Graphical Representation of Information Sot and Will Go Through One Example for Intervention Sot And Algorithms Mission Here What Needs To Be Done Instructions For Kids Consuming One Input Element Between Repetition In Growing Every Shot Put Latest Edition Infections And Remove Sworn In For Data File Location And Align With The Shortest Distance Of Set The Repeat Santino Input Element Treatments Kal Her Support Given at Work in the Morning 213 Unexpected Output Tax 1234 A Flat Straight to the Exam From Now Instructions That It's Not in a Position IS Verified with Each Individual Visits left atrium Select 2.5 Visits left atrium Select 2.5 Visits left atrium Select 2.5 100 Persons of INGO Subscribe to the Page if you liked The Amazing Share And subscribe The Amazing Position Naidu's Introduction Leaf Jindal20042003 j2ee That's Right This Oil Compare Per Rebellion Suzy Welcome Hirevoor Fix Per 421 Jaiveer 1020 And Is Sex Less Hair And They Will Be Reset-2 I Think Again Call To The Same Reset-2 I Think Again Call To The Same Reset-2 I Think Again Call To The Same Process Welcome Par This Of The Leaders Are In Jail With The Year - 1615 Welcome Jhal Replace Jail With The Year - 1615 Welcome Jhal Replace Jail With The Year - 1615 Welcome Jhal Replace With 40 And Share And Comment It's Sava Channel Company Jet Management Inches Girta Inko 2001 Shastri Welcome Back Soils Page Samay Laxman Share With Three And A Great They Want And They Will Appear OK Like 21 2012 Increment I And Tourist J2ee And Aapke Sunao Dar S One Ki Reel Hour And 2mi Koma Jaisi Ark Again And The Same Thing Na Phir Kisi Person Laptop Sexual 34 And This Point To The Election Next 10 In Comparison With Jain President Mirwaiz 2018 Ki Agar Nehru Kam Par Jai Vijay - Paan Singh Ki Agar Nehru Kam Par Jai Vijay - Paan Singh Ki Agar Nehru Kam Par Jai Vijay - Paan Singh Yadav MP3 Line Hair To Back To Jaipur Kavya To This Great In The Case Of Solid Object Oil Improvement Of Which Are Considered As One To Three Four Subscribe And Complexity Of Going Through Video then subscribe to The Amazing Tours In Water Tank Refill Hai Agar CBC News Seema Area For Short List Problem Always List Right Letter This Is Last Point To 3.2 1.2 This Letter This Is Last Point To 3.2 1.2 This Letter This Is Last Point To 3.2 1.2 This Includes Hair Printer HP Point * 40 Includes Hair Printer HP Point * 40 Includes Hair Printer HP Point * 40 17.8 Tips Qualities Pages Initially 17.8 Tips Qualities Pages Initially 17.8 Tips Qualities Pages Initially Point * Reference Pimples Arrow's ATM Bindh Point * Reference Pimples Arrow's ATM Bindh Point * Reference Pimples Arrow's ATM Bindh Volume Sauda Years But They Can Have This Point Andhe Left To The Volume Two Points 98 That Potato Which In Water So Initially Mez Pe Channel Its Pointing To Null Its Verdict And Us It In The Place This Point Hair And Teeth Will Point To For It's Something Like This Mist To Remove The Difference Between Her Daughter And What Is The Value Of My Daughter Will b add value to which is not product palace point unclean move to the this particular note beach is basically don't no tight switched from things also held next time semen internal point is dot right any to remove the sun dot Within the previous pause next also pointing to the head light show that is the next year period next point to hand under her 0.25 don't which is best in the 0.25 don't which is best in the 0.25 don't which is best in the temperature of medical too emperor akbar system and stay updated on is so let's sew from here Remote In My Current Point Is The Spirit Members Strands Of Hair To Inform Him From Here Right Now Taking Place At 312 Issue 9 Again 232 This Point Are Placid After Mist Moving To Check Weather This Is The Video then subscribe to subscribe and subscirbe B .Sc subscirbe B .Sc subscirbe B .Sc Half Tri Lottery To Preserve Trees For Rest And For Split Into Na Rat In The Previous Day Due To Head The Postal Test Series For His Another Important You For Watching This Point To The Point At Which Was 10.22 Information Check The Value Is the Was 10.22 Information Check The Value Is the Was 10.22 Information Check The Value Is the sun dot co dot uk subscribe order that ine dalmau fear not want to know check weather were displaceid next9 that is not the for 2515 here are the amazing two daughters from this point to the point to point and click on subscribe Share and subscribe the * Share right but I'm still need a reference to the * Share right but I'm still need a reference to the * Share right but I'm still need a reference to the starting point and so let's take a pun dummy previous something is the world point to the starting point tummy previous a split in to the head which is point into three layer and the same point at me previous is it now in this point into foreign investment into tap plate brother previous month year is so common having a dummy entry painter pooja express one and always at one and always protective three ok self checking addition twist next is Samay Previous Dot Loot Head Solitaire With Same Just Opposite So After 10 I Will Have This Dummy Previous A Split Into One Which Is Point To Which Is Point * Very Special Point Two For Is Point * Very Special Point Two For Is Point * Very Special Point Two For International Mukesh M.A. Previous Steel International Mukesh M.A. Previous Steel International Mukesh M.A. Previous Steel Ponting Care Love One Side Effect Mi Head Points 295 Torch Light Reverse Rules Juice Text Group 1955 Sumit Reverse Water Waste Water In Tis 2015 ODI And Subscribe Button More Directly And Indirectly Return Study Report Subscribe Now To Receive New Updates Reviews And Can Be Return with daughter will start from this particular value will be solar triad to quote 10 111 additional and head national return head is not boiled and the time previously defined in the previous quarter defined that you use oil open till he did not return of superstition and Sacrifice Radhe-Radhe of superstition and Sacrifice Radhe-Radhe of superstition and Sacrifice Radhe-Radhe Gyan Court Held That's Wealth In Resort Previous Contract Temple Faith Do It 108 Business The Correct Position and Exam Start The Point To Right Determination To Give Weather Map Previous Dot Next9 222 Channel And Prevents Heart Webs Her Daughter And Subscribe To 220 Doing This To Make And Butter Previous Point To The Correct Place Today Can Insert You In vain The Place Mukesh Were Doing This Movement Of The Previous Point According To Such Handsfree The Volume To The Correct Place Of The Previous Point Arvind Is Particular List Member Same Thing Delhi Are it something that media them using the same logic to make a word can remove the friends from this particular point and subscribe absolutely return temperatures dropped subscribe point to the temperature liquid so let's check the I reject you updated on a recent arrangement was Passed for the time of this algorithm belief and super because vairagya govinda previous points are liable to find the great place to inside the head members the best way to play the current festival decade subscribe to the Page if you liked The Video then subscribe to the page
Insertion Sort List
insertion-sort-list
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. 3. It repeats until no input elements remain. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Constraints:** * The number of nodes in the list is in the range `[1, 5000]`. * `-5000 <= Node.val <= 5000`
null
Linked List,Sorting
Medium
148,850
61
we have to rotate the list to the right by K places that means and just give an example first therefore k equal to so the last two nodes will get rotated so first five will move to the beginning this first rotation and second rotation k equal to right so the second rotation 4 will get moved to the begin and we have to return this result as like this so here you could see k equal to 4 so initially k equal to for the first rotation 2 is more because right a second annotation from here one is more and set here and for the third rotation you could see Zero is multiple equal to original linked list itself right so there is nothing good length of the liquids for the fourth rotation again the 2 is multiple so one thing what you can observe here is whatever the multiples of linked list you have uh sorry length of the link is you have that will result in the same linked list as a original note list so if k equal to 3 or k equal to 6 k equal to 9 k equal to when everything will result in the whole channel is resulting in the same name because three times so one thing which we need to take care of is a given problem but they are given uh times and that is greater than length or something K modulus so here for modulus 3. in the Give an example that will give you a remainder as one so basically yeah you need to rotate the language only by one square equal to one so K will be equal to K modulus length so you are rotated see you have rotated the link is by one times actually you only have moved to the front position that is only one rotation which you are doing hence to find the length what we need to do yeah we have at first we have to Traverse to the link is here the length will be equal to 5 in this case once you get length of the increase now the current will be pointed over here at the end after finding the length of the necklace so now Point current dot next to the beginning on the left please okay and the point current out next to the beginning of the linked list so current dot next will be equal to head so after pointing this now perform this K will be equal to K modulus length in if in case instead of telling k equal to 2 if they say k equal to 2 L 5 and 10. we need to prior rotate so 12 modulus length will be nothing but 5 that will give you two as the answer k equal to 2 apparently same so now we have k equal to that means the last two notes between you two rotate so in the sense see we have pointed out the last note at the beginning of the implicit rate so now only thing which we need to do the last two notes right this should become head and break down this and ratio point to null that is what we need to do again I'll repeat the last two notes we have to rotate and we have the last pointer pointing to the current or next module to head point the last node but the last two notes four pointed ahead and break this endpoint based on my previous two nine so how do we do this operation if we do this yeah this will result in here one because three is pointing 4 is head increase that there is a line but how do we do this that is a question so for performing this uh we know the last two notes right so K will become length minus k 5 minus K how much clearer so what we do is we move the current pointerly here k equal to three nodes my total length minus the last ones which I need to rotate that is 3 here so until the third mode we will move the current water so once the current water is pointed over here now Point current dot next now Point head should be equal to current dot next so this will become head now I know after pointing headical current nodex no point current on text equal to well got it so the ordering is very important if you initially to current then you cannot do head equal to current on next if you're wanting to another again so head will be current dot mix after doing this no current dot Max will point so that is the head so afterwards n because extra reputation is not required so that's why you do this so two twice we have to do here and accept these two more so till the three nodes length minus these two notes till then you Traverse the current head so that is how we do until K approaches to zero current will be equal to current dot next what we do so initially current will be pointing over here right so k equal to 3 initially so current dot next will Point here so K will become 2 is it zero no again current on Excel Point here and K will be zero this time once K is zero now you go out of this so now Point current not next head will be current or next and current on X will be fine that is how you return the link list so we'll have this node audio the length of the length is zero or one because nothing we have to do any rotation method that will result in same interest so first check if head equal to none or head dot next equal to then what we need to know just return the head otherwise please know current let that behind initially and we will have our founder Helen equal to zero so now uh because in this case I'll take current dot next not equal to that then the loss iteration for this while loop will correctly so at that time it we won't we cannot point is current or next to begin so that is the problem because the link will coordinates is so here until current node next is multiple that means correctly pointing the last node Olympus and you take a length equal to one initially so that's not a problem length and current will be equal to current or next so yeah once you find the lamp now this is a current or next you want to point it to my head speaking of the necklace so you have the pointer being the current has a move to the beginning so now K will be equal to K modulus so this K again will be equal to length minus k so why the K becomes zero so what this will do is until k equal to 0 it will get decrementing K by 1. so what we need to do is current equal to current dot X so what does this K approaches to 0 plus is until K naught equal to zero it is equal to one sentence now at this time Point head will be equal to current dot next and yeah now current dot next will be equal to so at last we need to return the height that is where the starting point of the place we have of the rotating one R is missing yeah it's fine okay if you understood the solution please subscribe to the channel and like the video we'll come up with other videos
Rotate List
rotate-list
Given the `head` of a linked list, rotate the list to the right by `k` places. **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[4,5,1,2,3\] **Example 2:** **Input:** head = \[0,1,2\], k = 4 **Output:** \[2,0,1\] **Constraints:** * The number of nodes in the list is in the range `[0, 500]`. * `-100 <= Node.val <= 100` * `0 <= k <= 2 * 109`
null
Linked List,Two Pointers
Medium
189,725
492
hey everyone welcome back and today we'll be doing another loot code 492 construct the rectangle an easy one a web developer needs to know how to design a web page size so given a specific rectangular web page area your job is now to design a rectangular web page whose length L bits W satisfy the following requirements so the area of the rectangular web page you design must be equal to the area given as targeted area the length should be greater than the width or equal to at least the difference between the length and width should be kept as minimum as possible and return the length and width in an array respectively so for example we are given an area 4 so what we can do is just return four and one where four is the length and let me just like this and this satisfies our condition two conditions but not the third the difference between L and W should be kept as small as possible so the smallest distance will be 2 and the worst case will be 1 and 4 in which we are failing our two conditions which was the lens should be greater than W but it is not the case so we'll be discarding it and what we will be doing is just taking our width and then taking the square root of the area and just using it because obviously our main problem is the weight because we do not want our way to exceed our length and that will be exceeding after that you can say the scare fruit portion and that's it so we'll be starting by making a for a difference followed infinite and now we will make an array of our area and in the second we have one in our like in our example 37 where 37 is the area but 37 is a prime number so we'll be returning one with it and that's it so for width in let's just make it w so it is easier okay so for width in range of from starting from one obviously not starting from 0 and then taking the square root by 0.5 and adding 1 because we do want to 0.5 and adding 1 because we do want to 0.5 and adding 1 because we do want to include that also and now we'll be calculating our length which will be just L and area and W okay so if our length is greater uh first of all checking if it is end because it can be a float and if it is greater than or equal to W and if length minus W is less than Mini which is our minimum difference between these two so that's it and now what we can do is just AR which will be our array in the zeroth index we want to return our length obviously making it end because it can be float so now one and in the one we will just pass the width which is w and updating our mini which will be L minus W and after this we can just return a r so that's it let's see if this works so not this words and let's submit it and that's it
Construct the Rectangle
construct-the-rectangle
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 1. The area of the rectangular web page you designed must equal to the given target area. 2. The width `W` should not be larger than the length `L`, which means `L >= W`. 3. The difference between length `L` and width `W` should be as small as possible. Return _an array `[L, W]` where `L` and `W` are the length and width of the web page you designed in sequence._ **Example 1:** **Input:** area = 4 **Output:** \[2,2\] **Explanation:** The target area is 4, and all the possible ways to construct it are \[1,4\], \[2,2\], \[4,1\]. But according to requirement 2, \[1,4\] is illegal; according to requirement 3, \[4,1\] is not optimal compared to \[2,2\]. So the length L is 2, and the width W is 2. **Example 2:** **Input:** area = 37 **Output:** \[37,1\] **Example 3:** **Input:** area = 122122 **Output:** \[427,286\] **Constraints:** * `1 <= area <= 107`
The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result.
Math
Easy
null
1,498
Hello everyone welcome, we are going to do video number four of my channel's playlist. The name of the question is number of sequences, thoughts, it is the same condition, it is a medium question, liquid is fine, it comes in the category of medium hard, but story points. When you write this and once you understand the question code then you can definitely do it yourself but this question has taught you a lot, you will learn a lot from this question and these questions are very important ok it is given by Amazon and see the input output Let us understand what is the question, see, the question is quite simple, you will be given an interior name and you will be given a target value. Okay, you have to send the number of non empty sub sequence, number of non sequence of true date, each sub sequence. What will be the minimum and maximum element of, will you sum it should be given equal to the target, okay, so first example here, if you look at 3567, the target is nine, then the answer is tax, meaning there are tax subsequences whose minimum and maximum value of If you submit then it will be equal then the life target date is 9 see the example see the solution here first step sequence is showing three is in value maths both three will be the sum of both is six which is equal Tu 9 then the sequence is 3 and in all this sequence minimum is three and maximum is 5 what is the sum of both 8 li give equal tu nine six minimum is three maximum is six three comma 63 + 6 &lt;= 9 comma 63 + 6 &lt;= 9 comma 63 + 6 &lt;= 9 to 4 got now let's see Brother, how will you approach this? Okay, so look friend, the first question that came to my mind was that I can do this by generating as many sub-sequences as there are, generating as many sub-sequences as there are, generating as many sub-sequences as there are, but how do you generate the example? It is okay whether you took this one or not, if you took it, then three A would have gone in your subsequence, if not, then nothing is okay, after that you will come here on i + 1, okay if you press on i + 1, then there will be a condition on this will come here on i + 1, okay if you press on i + 1, then there will be a condition on this will come here on i + 1, okay if you press on i + 1, then there will be a condition on this also that Whether you took it as your own or not, if taken is okay then three will be five and if not taken then three will be okay and here also there will be a condition that if brother is taken then it will be five, if not taken then it will be empty then many such sub-sequences will be formed, isn't it? That many such sub-sequences will be formed, isn't it? That many such sub-sequences will be formed, isn't it? That is, there are two choices at every position, either take it or not, that is, you have power n soi se, it is ok and in every sub sequence, you have to find the minimum and maximum also, then to find that also you will need n, isn't it? So this is a very expensive solution, very hi, okay, so let's see what else can happen, okay, so see, what is the most important thing, first of all, we will understand that brother, if such a solution comes in someone's mind, then how will it come okay? You will understand the intuition, you will understand from scratch, you will build the solution directly, I will not tell you, yes brother, do this, do that, the answer will come, okay, so let's start with this example, so before starting, let's know a few things. I know a little clear cut, we have already seen what that thing is. First of all, let's take an example, mother. This sub sequence is five, seven, okay, what is its minimum, brother, what is its maximum, 7. Mother, let us take this sub sequence, it is something like this. 7 is written first and five is written later, so brother, the minimum of this is also five and the maximum is 7, the minimum of this too was five, the maximum was seven, so there is a slight change, we have to keep the meaning only with minar max, this is right. If you want to find out everything, then in any order, if your input is a mere pea or if there is input in any order, then why am I saying this, I will explain it to you further. Okay, so now let's try to understand it. Look, right now I am here. But I am looking at the starting element, right now it is five, now I have a sub sequence which is the same 5x sub sequence, what is its minimum, five, what is its maximum, five is 10, brother, give me a greater target, right? If it is not feasible, then this will not be my answer. Okay, but can this five be a part of any sub-sequence of five be a part of any sub-sequence of five be a part of any sub-sequence of which it is minimum or it is maximum? Okay, so let's see, like mother. Five has been fixed for now, let's see what other elements can be added. Let's add three. Okay, so till now, what is the minimum? What is the minimum three? What is the maximum? Let us equal you with the target. It can be made with three, it can be made very well, welcome, if so, what is the minimum, what is the maximum, what is 7, 12 brother, if you want to give this grater then leave it, okay dear, then when we saw the elements, seven and six, then that is brother. There is no less, okay, it's fine, tell me one thing, think for yourself, if you take mother, I would have sorted these three elements, okay, that means I would have done something like this, here six is ​​here, seven is here, mother, here six is ​​here, seven is here, mother, then The answer was found, it was very good, this one answer was found, but 5:00, look, it is definitely required, will not be required, why not check further, when answers of 5 and 6 mills are being removed, its value is not getting greater. If there are more big elements after six, then there is no use in taking them. Those with five are fine, so I will break here only, so what will be the benefit if I sort it and do it? If I do the sorting then this one will help me, I just found out help me, this one will help me, I just found out that there is a good five, which is not sitting with the six, so it will not sit from further too, okay, so what does this mean? You can do a complete shot of all and you say, if you are sorting then you are changing the order, then brother, there is no problem in changing the order. Remember by changing the order, we mean and max, okay. Minimum in both of them will be maximum. What is the mean in this? What is the maximum? What is the mean in this? So the max in this is five, that is, if we shorten it, then it can be of some help to our friend. Plus, we will not have any problem, will it help? So what is happening is, look here, eliminate the further elements and there is no issue in our answer too, so let's shorten it i.e. 3567. Okay, so let's shorten it i.e. 3567. Okay, so let's shorten it i.e. 3567. Okay, so let's sort it first. So now see, this arrest of mine is done. Okay, so you remember I was saying again and again that we only mean minimum and maximum, so remember in the beginning, if we take mother, I considered this element as minimum, okay then whatever element is on the right side of it. There can be all maximums, Maa, let's choose three, I made it from five, so it's okay, three is the minimum, and five will be the maximum, okay Maa, let's take five, since I have chosen six, okay, so 3 5 6, so the minimum will be three, that's it. The maximum will be six, okay, so see, by fixing the minimum, I can do the maximum thing differently, okay, so think something like this, look at this, I take the minimum, I have chosen this, okay, here is my point, okay and I am objective maximum value. Chunni, so I have started from the last, okay, I have chosen here from the right, okay, so this is the office, this will be my max, okay, that means, if three, I have taken the minimum three, okay, if it is there, then I can enter any value in between. It does n't matter because the minimum is this and the maximum will be this because this is the right most value. Okay, whatever happens in between, I don't care. Okay, so now look here is my minimum and here is my maximum. So one thing. Now tell me, yes, 3 and 7, which is one, is my subsequence, okay, what is its mean and max, three and 7, what is the sum of both, brother, 10, which is greater than 9, so brother, this cannot be my answer. Meaning, I can directly reject 7, which means I will not take it in seventh. Okay, I can directly reject seven because seven cannot pair with anyone, it cannot pair with three, so it is an obvious thing. If it can be done from five or six, then I can reject it further by taking seven. Even if 7 alone comes in a sub sequence, it will still cross the target because what is 7 + 7, 14 is because what is 7 + 7, 14 is because what is 7 + 7, 14 is fine. So, that's why today I can band together and reject the seven and I will bring the R here. Okay, now pay attention to one thing, it is very important here, what is the L here, no three, I have taken the minimum, okay, so it is possible. I will take six, okay, maybe I will take six, so look here, pay attention, what is the minimum, six, okay, this is greater, give equal, you are sorry, this is mine, it is equal, you are nine, you are very good, okay, give equal. Tu Rahana means this is a valid answer of mine, so tell me one thing once, what choice did I make? 3 choices were based on Na and I made the choice on 6 words. Now tell me one thing, our science is sorted so there is no one in between. Well, I don't care, why don't I care, because brother, by mean and max I mean this and maxi. Okay, so by permuting all the numbers in between, a very large sub sequence will be formed. Okay, what should I say? I am six, understand that, look again here, pay attention that 3, so I have taken it is okay, and this is R, which is six, it is my sitting, it is okay, the pair is sitting, give it equal, you are nine, it is right. It's even, okay, so now there is a spoon between three and six, so now I have many chances. Look, first of all, I either take 5, or I do n't, okay, I either take six, or I don't, okay one. It is okay to do two or three. Understand how the possibilities were created because there are two elements here, so we have fixed 3, there is only one possibility, so we have fixed three, it is okay and where was the right point, brother, here it was at six, right? And I saw that the value on the left point is 3 and the value on the right point, after adding both of them, they get equal to nine, whatever values ​​are there in between, get equal to nine, whatever values ​​are there in between, get equal to nine, whatever values ​​are there in between, I can include them, okay. Because I am getting the mean and max absolutely perfect, it is okay and even if I am late on 3rd, then look at 3 + 3, okay, pay attention here, so what I said here is that I have fixed 3rd, there is a possibility. After that I have a lot of possibilities that I may take five, okay or I may not take five, okay and then there is a possibility even after that I may take six or not six, either way it is possible. So why do they come up with the possibility because there are two elements here, these are the two contents for this three, okay, the three has been fixed and from the two contenders here, this and how many ways to choose these two. What I am getting is the tax method, Na Lia, No Lia and Nai Lia, Okay, Tu Ka Power, Tu Hai Na Tu Ka Power 2, Kya Hai Bhai Tu Hai, Kaise Ka Kaar Ka Hai Na Lia, Here is R and We have fixed how many elements are there and the rest of the elements, children, give them the power of 2 to choose. Okay, so I will do zero induction, zero one, you are three, no, how will they come out, R - L will do no, how will they come out, R - L will do no, how will they come out, R - L will do you ka. Power is whatever value is here so now let's reduce one let's move ahead to dry iron ok let's move to dry re then it will be more clear ok see as soon as I know that ok 3 + 6 whatever that is let's take it I know that ok 3 + 6 whatever that is let's take it I know that ok 3 + 6 whatever that is let's take it equal Tu nine, what does it mean that this R is my correct friend, okay, so I am late, how many elements are there, brother, there are two elements in the middle, okay, so you have done your power, now I can see this much answer. Okay, now let's move ahead. Okay, so look, before moving ahead, see one thing again, what I said, give it to the power of 2, that is, after totaling, I got the answer. Now the answer is fine, which is in which the minimum will be three and the maximum will be this very. Fiber Six can do it, see what all it can do with it, I will also write down which three things, whether I am alone or 3, then it is fixed. You know this, three is fixed, I am including everyone else. If I can, then I have taken the five. Okay, here it is possible that 3 + 6 &lt;= 9. The minimum and maximum have to be equal. &lt;= 9. The minimum and maximum have to be equal. &lt;= 9. The minimum and maximum have to be equal. Here, after fixing my 3, all have been removed. After fixing the three, all have been removed. The bigger of the three is now over. It is done, so what will we do this time, will we make L or increase Al? Let's follow the minimum of Alco and let's see how much answer we get. Okay, it is clear till now because I have removed all three and fixed three. I have taken out all the possibilities. Okay, this one which was 6, will remain fixed now because I considered three as fixed and when R when the index number was on you, I have taken out all the possibilities, so the major ones of three are over, now we will do L plus. So here it is clear that A is clear till here, so let's check that first of all, the element on L is five and the element on R is 6, it becomes 11, isn't it? &gt;= Sorry, we will have to reduce R. So brother, if you do R &lt; after exhausting, there will be more clarity. Okay, now look, pay attention, here is here and here is here. Now look, first let's equate L and see whether these two are valid or not. First, look at the mid marks. That is, if the boundary of Max is giving a valid answer then the answers in between will also remain valid. Whether I take the middle element or not, only then the answer will remain valid because I and Max will be fixed right because I have sorted and R which is Hai is the right most element, so it is obvious that every time it will be bigger. Okay, so first I will see, this R, this L, which is the minimum, together with this R, gives a valid answer, otherwise it will be 2 + 7. This L gives a valid answer, otherwise it will be 2 + 7. This L gives a valid answer, otherwise it will be 2 + 7. This L gives nine. Is &lt; 12 Sorry, our target is 12 or &lt; 12 Sorry, our target is 12 or &lt; 12 Sorry, our target is 12 or less than that Okay, so what does it mean that if I fix the element, okay, then after this I have many options, should I take these three or not? Should I take this or not? So how many elements are there in total? 1 2 3 4 5 How many possible total will be the power of 2? 5 So what will I do here? Science R would do indexing here. I am zero one, you are three four five, if it is ok, then your power, this difference will become five, how much has it become, if it becomes 32, then brother, if I keep this L minimum, if you keep it fixed, then brother, how many positives are 32, the answer is mine, isn't it? So, I have to keep 32 also in the answer and the science is L, after fixing it, I have taken out all the answers, as many possibilities as there were, the power of the answer was ok, so it means it is a big finish, now here L will be plus, okay. Let's see again, what is 3 + 7? okay. Let's see again, what is 3 + 7? okay. Let's see again, what is 3 + 7? Brother, 10, right? 3 + 7 is 10, which means that if we Brother, 10, right? 3 + 7 is 10, which means that if we Brother, 10, right? 3 + 7 is 10, which means that if we take Lee, then we are equal to 12. Okay, what does it mean that if I take fixed mother as minimum, two, now this is the minimum because the left most. Okay, so should I take all the elements on the right side of it, or Na L, or Na Lo, okay, I will enter so many possibilities, how many will be there, R - L, 5 - 4, one, two, how many will be there, R - L, 5 - 4, one, two, how many will be there, R - L, 5 - 4, one, two, three. If everything is fine then your power four is 16 and the possibilities are there, I will print all the positives, otherwise it will be better and clear, but printing means taking time from office. You can think for yourself how many tests can be done and how, which are 16. Which ones can you think to yourself that I have fixed three, okay then should I take these three or not, if I don't take then leave it be, if I take then three will become three, after that I will take another tax. Or no, if I don't take the tax, then three will become three, okay then here I have taken the tax on 33, okay, either it will become 34, or three of three will become three, what will happen here, 3 will become 4, either 33 or If it goes then there are many possibles, if the total is 16, then you can print it and see, but the date is fine till this cute time, it is clear till now, okay, so now look at this question, fix it, I found out all the answers, which were 16, your power. Four is the big end of L, now we will come here, okay, then it will be the same power four of 2, how many elements is there, if I take it as fixed mother, then I am getting three elements, after this I have a choice, okay, so three cups is the power of three date. It will be 8 ad ok so its big is also finished now it will come here 7 4 11 ok this is also smaller than the target Total tu ka power tu means it will be four ad ok if it was fixed then it will move ahead here first 7 * 6 = 13 is will move ahead here first 7 * 6 = 13 is will move ahead here first 7 * 6 = 13 is done, okay, so it is obvious that it is getting bigger, we will have to make it smaller than 12, so we will reduce R, here R will go to A, okay 6 * 6 = 12, okay, 6 = 12. 6 * 6 = 12, okay, 6 = 12. 6 * 6 = 12, okay, 6 = 12. So look, pay attention, Science 12, take this, equal is the target, that is, this is our valid answer A. Right, how many elements are there in total, the difference comes first, R - L 4 - 4 date is one, it is correct, it is the same sub sequence, is valid answer A. Right, how many elements are there in total, the difference comes first, R - L 4 - 4 date is one, it is correct, it is the same sub sequence, is valid answer A. Right, how many elements are there in total, the difference comes first, R - L 4 - 4 date is one, it is correct, it is the same sub sequence, is n't it? That is six of six, okay, what is its minimum, date is 12, okay, it will be one, that is, zero to the power of two, add all these, how much will the dog come, okay, that means, how will you convert it from story point to code, okay, then first write the sorry point. If we take it then look, our story points will be something like this or a little earlier I had said that we will sort it, okay and L will be zero and run will be -1, okay L will be zero and run will be -1, okay L will be zero and run will be -1, okay and what was this third point that brother, if whatever element is in L and If the sum of both the elements in R is equal to the target then it is obvious that whatever elements are there on the left side of the element, it is okay, but the name which is in soft L can be included with them. Do n't do it because when the name is soft, then what is the point of adding the elements to the left of this woman separately and giving them equal, you will make the target, okay, all the elements are there, I have fixed the null and all the elements are there i.e. That and all the elements are there i.e. That and all the elements are there i.e. That I have the possibility in all of them, take it or not, take it, all the elements of your power, i.e. R-Saal, that is what I am elements of your power, i.e. R-Saal, that is what I am elements of your power, i.e. R-Saal, that is what I am adding here, this is the only benefit of correcting it, isn't it? Look, I am saying it again. Look, the only benefit of sorting would be that here there was L and here there was R. Okay, so if you did Science 729, then L is equal to 12. Okay, so I know that brother, this is a small element, it is minimum after joining it. Also, if it is giving an answer smaller than 12, then say this Banda L to Jadeja or this Banda is here, then it will have all the small elements on the left, it is fine and I have all the limits. Two options have to be taken out, so don't use multiple options, there are two options, Lo N Lo, okay, so the thoughts are the same, we are taking out the shortcut market by using your power, R-L and shortcut market by using your power, R-L and shortcut market by using your power, R-L and Science L's major part is over, I have taken it all. Is it here that everyone has been removed from L, so the greatness of L has ended, now we will do L plus, in this way we will do L plus and if L + R is the greater do L plus and if L + R is the greater do L plus and if L + R is the greater target then it is obvious that if this So this is office, we will have to do mines, okay because look here again I am telling you, let's take mother, this would be 10, okay, take this 20 mother, so it is 2022, if that too is added to 20, then we will give a bigger number because it is short, that is. I can't take 20, these other thoughts will mine the same R, let's keep the L here in the nails, I have done it, okay, so this is my solution to the tax point, this will make the whole code. Some extra in the question. Have you given me the thing? First thing, did he say that brother, take the model because the answer can be very big and it will definitely be big because you are adding power, first thing, this is done, second thing, you are taking out power, okay, so power. When it comes to internal, what does it do functionally, what does the calculation do, it is time taking, okay, most probably C plus, so I saw that brother, my time limit was going to be x speed and I am not aware about it. Will give ok so now that means I ca n't get it if I ca n't get it directly, can't do it directly then what can we do for it ok so let's see what we will do now ok so yaar normal when I submitted the timer was going straight ok Now I will show you by doing it, okay, so how to solve that problem, okay, so now if I tell you honestly, it was not my brain, I have learned by seeing the solution myself that you guys can do it with the help of computer. Power and those who do that and do competitive coding will definitely have an idea of ​​the right thing but I was idea of ​​the right thing but I was idea of ​​the right thing but I was doing normal power, so my time you take help is also fine and don't worry if this question seems too much to you, such questions. There are patterns of such questions, there are other similar questions of similar questions, by making this question you will become more expert, don't take tension, ask the request properly, ok then let's see how you can do Pari Computer, it is very simple, friend, you can do it yourself. Think for yourself, think for yourself, this was my life, I was coming here, okay, zero, one, three, four, okay, now think for yourself, friend. 4 - How were four, okay, now think for yourself, friend. 4 - How were four, okay, now think for yourself, friend. 4 - How were you finding this difference? R-L, no, then you were taking power, when and deep. What you finding this difference? R-L, no, then you were taking power, when and deep. What you finding this difference? R-L, no, then you were taking power, when and deep. What were you doing, my friend, what is the maximum value of the cell, what is the power, worst, see how much N is here, five, right, and this has become zero, this has become one, you have become the last one, N - 1, okay so. N - last one, N - 1, okay so. N - last one, N - 1, okay so. N - 1 is R and what is L. If it is zero, then the maximum value is N - 1. Still, I value is N - 1. Still, I value is N - 1. Still, I will take it out by doing maximum. Okay, N is power, your power can be N. See in advance how it will come out. See what size 0123 is. Hey, I am taking it and you know and let's take this mother and name it Power, okay, so and I will define the meaning of Power I know what will be the power I of 2, okay, I am storing power, okay, so see. The obvious thing here is Tukur zero. Do you know what tu power is zero. One is okay. Now look here, what is 2 to power one, 1 - 1. I know that means it is just multiplied by one. 1 - 1. I know that means it is just multiplied by one. Okay. Similarly, here 1 * 2 * 2 * 2 = Okay. Similarly, here 1 * 2 * 2 * 2 = Okay. Similarly, here 1 * 2 * 2 * 2 = 3, you know, there is one in it and you multiply it, okay, it is very simple, I have already figured it out by using computer, so here it will be one, this will be you, this will become four. How much will this become? This will become 8. This will become 16. Okay, so see directly, you can find out. Mother, let's take it. I asked you, brother, please tell me your power of three. So, won't you do anything? Here in this power vector, third. Now tell me the value which will be in the index. Dog, your answer will be eight directly. Okay, so I have to do Pari Computer and I did not think of this on my own. I had to take help myself. Okay, I had to do Pari Computer, so that your solution becomes faster. Okay and science, you are sorting here, there are N people, so your time complexity is increasing. Okay, so let's do the code, we will do this with tax points, what else, the computer guy will take out the power here. Okay, so let's code this, okay, the question is really good okay, but you learn to make such questions, now we are going slowly, okay, as many such questions as you make, you will group them and keep studying the pattern, okay. Those people who have created one question in one go means they have created such questions. First of all, you don't have to worry about the question of making. Okay, let's start, brother, first of all, take out name, dot size and most of all. What was the first point, remember we have to sort and Namas ok what was the first point sorting ok after that let's move on to the second point one more extra what came to mind that brother we will have to do power fairy computer but I am not doing that right now I am going to first see whether the time is being saved by doing the normal power function or not. Okay, so remember Start I &lt;= R. Okay, first let's Start I &lt;= R. Okay, first let's Start I &lt;= R. Okay, first let's find out if the number of L plus R &lt;= target is reached. Those R are happy, doesn't it &lt;= target is reached. Those R are happy, doesn't it &lt;= target is reached. Those R are happy, doesn't it mean that brother R has such a big value even if it is even, if you give equal you are the target, meaning all the elements before R can also take part, okay and everyone has two. There is an option for all the elements, take it or not, if it is okay then the result is equal to you, the result is plus because the head of L is the answer. Look how small a quota it is. Returned the result. Result is equal to zero. Okay, let's run it and see. Let's see it. Great. Submit it. Try and see it gets submitted and see, yes, one more thing, the power calculation that is being done in this line, it is going out of the box, you are seeing this outside D range of representable values ​​on off type in OK. So that's representable values ​​on off type in OK. So that's representable values ​​on off type in OK. So that's why it has been said that this is a very big value, if it is power, then take the model, okay then let's go, okay friend modular kitchen right no and note okay no let's get the value of what can we actually do, our up free computer power of I - 1 i.e. what will be your power i, what will be the power of I - 1 i.e. what will be your power i, what will be the power of I - 1 i.e. what will be your power i, what will be the power i - 1 * 2, ok, power i - 1 * 2, ok, power i - 1 * 2, ok, what else will I do, brother, if I do modulo here and make noise, then my vote tension will be over that brother is doing one seat again and again. Okay, so I think there was an issue of C. There was no issue of time limiting seat. I was getting a show only for one seat. The value was getting very big. Okay, so I figured this out first and Now I have taken the module also, so it can be simplified a lot. Now let's remove it. What will be my result? What is my R-L? There are so many elements. What is my R-L? There are so many elements. What is my R-L? There are so many elements. I also got a lot to learn from this question and I also did a If I could not solve it in the bar, then don't be set, it's okay, I am being optimistic, if you ask such a question in the future, then I will be able to concentrate because I have learned something new, today I have learned something new, okay, I hope I was able to. Help Koi Doubt Hota Hai Resident D Comment Area I Bill Tree Tu Help Your Next Video Thank You
Number of Subsequences That Satisfy the Given Sum Condition
find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree
You are given an array of integers `nums` and an integer `target`. Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[3,5,6,7\], target = 9 **Output:** 4 **Explanation:** There are 4 subsequences that satisfy the condition. \[3\] -> Min value + max value <= target (3 + 3 <= 9) \[3,5\] -> (3 + 5 <= 9) \[3,5,6\] -> (3 + 6 <= 9) \[3,6\] -> (3 + 6 <= 9) **Example 2:** **Input:** nums = \[3,3,6,8\], target = 10 **Output:** 6 **Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers). \[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\] **Example 3:** **Input:** nums = \[2,3,3,4,6,7\], target = 12 **Output:** 61 **Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]). Number of valid subsequences (63 - 2 = 61). **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 106` * `1 <= target <= 106`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
342
hey everybody this is Larry this is day 23 of the Leo day challenge and we didn't do the uh weekly premium Farm yet so let's get it today uh okay today is a kind of a easy one it seems like 242 power of four so good time to take a break uh mentally I mean hopefully um yeah so I mean I don't know is there anything difficult to say uh I me you know there are couple ways you can do it can I solve it without uh loops and recursion right well what does the power four look like right I mean I was going to say something like um you know it's only they're only like 10 numbers right that are within this range of the constraints so depending on so you just check to see whether they are in it so I don't know that would be an interesting way to do it um and I think sometimes you just got to do what it takes of course I mean this one is the easy one I'm using it as an example of just know sometimes you just got to do what you got to do and sometimes they look silly but that's fine who needs four Loops or recursion just why like you know return n in um and there no negative uh oh there is there negative no I mean well there's negative power but there's no negative um uh power of four right so given a positive power so yeah just return one oops 14 16 I don't know what's after that uh 64 I'm going to miss some of course I should just look for a thing there shouldn't be that much more though right that many more oh maybe there AR 10 I was thinking two to the 20 for some reason but it is actually 2 to 31 so there's 15 at least all right I'm going to just Google it but you get the idea of what I was going to uh my God I'm so I say that I mean I'm actually pretty refresh today but I'm yawning for some reason all right I'm not going to actually write it out I mean but you can kind of do that way um it's still that was just the answer if I could solve about loops and recursion uh so technically yes but is there any other uh I'm trying to think whe whether I remember um some crazy wise trick um you know to do it right uh what is a power of four I mean so the power of two we know how or I know how to do this like trick right can we convert a power of two to uh yeah like the power of two you know you can do something like n um and minus one right is equal to zero right um make sure we have the par so if this is true then it's power of two right let's just name it this right can we convert that to a version of that's with four uh H because basically the idea of a power of two is that it look something like this where a power of four is also something like this except so it has to be a power of two first but then it also but it has um even number of zeros behind it right because every you know uh so instead of one or you know multiple of one zeros you can say which is obviously just any number of zeros is even number of zeros now the question is how do I do this in bitwise function or is there a way to do in bitwise functions I mean these are things that I you know generally do not need to do both in competitive or in real life so uh so it is an interesting uh brain teaser of sord even for a easy let me um so I mean the power of two thing is going to be true I mean I don't know if I was going to say like finding the square root if it's a power of two then we can find a square root and then if the square root is a power of two then um then we should be Gucci is that right because Square rooting is just basically dividing the number of zeros by two right so no I mean I don't know if that counts as cheating or whatever but I'm but it is something that's new to me so I'm going to try to see if this works it may not work so yeah uh so if not to return Force right uh return to S2 uh oh um I guess we end it but yeah I mean I think this is fine I mean I'm always worried about folding Point stuff um but in this case if it is a power of two then there only two scenarios right it's either a power of two or a power of four I mean I guess they more numbers but um if it's a power four then it would be uh into anyway perfectly and if not then it wouldn't be so okay so let's give a submit oh no I forgot zero okay well that's annoying why is this zero is yeah I guess I okay fine I actually uh with this bwise function I was just focused on uh positive numbers but I guess the bid wise functions are always a little weird two is what I guess this is where it bit me in that the int part of the thing is not true um cuz the int makes it from 1.414 true um cuz the int makes it from 1.414 true um cuz the int makes it from 1.414 to one and then one is true here okay so a lot of edge cases well maybe not a lot but uh but definitely um yeah okay fine I mean you get something like that right uh yeah oh I didn't add it back in was one zero two it's a lot of silly mistakes uh I don't even know if there silly mistakes but there's a lot of mistakes um but hopefully this is a cool idea I got it one before but I think that's because I try to do something clever cuz I mean come on no I don't think I would have done it that way oh I did do the square with trick before too I thought I was trying to be clever today and I forgot the zero case yep and then I forgot the one case so I did exactly the same thing really last time well this two times ago so I had to add this thing which I did today as well um okay so I guess I made the same mistakes of same edge cases uh three years apart so I don't know but hopefully this is interesting if nothing else uh yeah that's all I have for this one uh I thought I was being smarter or getting smarter uh looks like same level of dumbness so yeah anyway that's all I have for today let me know what you think stay good stay healthy to go mental health I'll see you later take care byebye
Power of Four
power-of-four
Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_. An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`. **Example 1:** **Input:** n = 16 **Output:** true **Example 2:** **Input:** n = 5 **Output:** false **Example 3:** **Input:** n = 1 **Output:** true **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
231,326
1,423
hey everyone welcome back and let's write some more neat code today so today let's solve google's most asked question of 2021 at least according to leak code and actually i think this question is tied for this for the most asked question there's two questions that are asked very frequently and this one is pretty much the most frequently asked one of 2020 and this is maximum points you can obtain from cards and i actually feel surprisingly this is actually a pretty fair question definitely a little bit easier than what you would expect from an actual google interview so there are several cards arranged in a row and each card has an associated number of points with it so basically we're given an array of integers where each integer represents a card's points each card is always going to have a positive value for points and basically we have to choose exactly k cards from this list of cards but the only trick is we can either take we can only choose so for example let's say this is our input array we have to choose cards from the end so we have to choose from the left end or the right end so we're let's say in this example we want three cards we could either choose all three cards from the left none from the right or we could choose two cards from the left one from the right or we could choose one card from the left and two from the right or we could choose no cards from the left and three from the right so those are all the ways that we could possibly do it right because we have to choose exactly k cards every time we want to choose cards such that it maximizes the output and maximizes the sum of the points and then we want to return that sum so at first glance this problem is actually pretty straightforward but let's think of the brute force way to do it so how many different possible ways could we choose cards right basically if we choose x number of cards from the left right for example one is x then how many cards can we choose from the right basically k minus x in this case 3 minus x is going to be 2 so then we could choose 2 from here right and basically we could choose for x right for x which is how many cards we can choose from let's say the left we can either choose zero cards we can choose one card two cards or three cards for each of those uh types of ways we could choose some cards from the right there's gonna be exactly there's gonna be a corresponding value that we can calculate which is how many cards we'll take from the right so how many different ways can we choose cards approximately k plus one or let's just call it k and for each way that we're choosing let's say two from the left one from the right how many total cards are there going to be of course that's always going to be k right k is the number of cards we're allowed to choose so if we were doing this in a brute force way basically the time complexity would be big o of k squared but we know that there might be a more efficient way to do this and it turns out there is it's basically very similar to a sliding window technique so for example let's say our first sliding window was this that tells us basically so we want to arrange our sliding window basically where everything outside of the sliding window in this case we have three elements over here everything outside of the sliding window is going to be the sum right so initially this is the first case our sliding window is all the way to the left and we leave exactly k elements on the right side three elements we take the sum of these three elements and we get 12 right so 12 is the largest we can get so far and now we're gonna shift our sliding window until we reach the end of the input we're gonna keep shifting our sliding window by one position each time until we reach the end so notice how initially we had three values now we only have two values to the right so what we did we initially had 12 as our sum clearly we added this value to our window now right so now we cannot include this in our sum so what we're going to take with our sum is subtract it by 5 but we removed this element from our window right so we want to take all elements that are outside of our window this one element and these two elements and use it in our total sum so we subtract five but we can add one this is going to give us a positive eight so this is definitely not the max before we had a 12 this is less than that so we're not going to update our result but we are going to keep track of this is our current sum because now when we shift our window by one more position now we're at the case where we're choosing one element from the right and two elements from the left so what did we do well we introduced this element to our sum right so we're gonna do a plus two but notice how this six has been added to our window now so therefore it's going to be removed from the sum so what we're now going to say is okay 8 minus 6 plus this 2 which is going to leave us with a sum of 4 and that makes sense right because take a look at all elements outside of the window 1 plus 2 plus one that's obviously four so we're on the right track here and so of course four is not the max so far but we are going to maintain that four because four is the total sum and now we're going to shift our window one more position into the last position right now our window is here so basically we've gotten to the case where we're choosing three elements from the beginning so what we did is we took this element and added it to our window so we're subtracting it from the sum but this element is now no longer a part of the window so this element can actually be added to our sum so 4 minus 1 plus 3 is going to give us a positive 6 is not the maximum right so basically we've done every possible way that we could have shifted our window right this is where our window is now if we shift our window one more time we'll end up like this right this is obviously invalid and we know that's the case because look now we have four elements outside of our window but we always wanted there to be three elements outside of the window because we're always going to be totaling up three elements exactly so now we can basically stop so we'll return 12 as the result that was the largest sum that we were able to get and we were actually able to do this in big o of k time because we initially started our window over here right so we first computed this sum which was size k so that was an o of k operation and then each time we shifted our window you can see that we shifted it one time two times three times until our window was in this position so again we did a k operation so k plus k is going to be the overall time complexity that's obviously going to be big o of k as well so that's the overall time complexity we didn't need any extra memory so the memory complexity is big o of one now let's get into the code and we're basically going to be following exactly what i did in the drawing explanation so the first thing i'm going to do is initialize the left and right pointer the left is of course going to be all the way to the left the right pointer is going to be the length of our input array card points minus k and remember the first thing we wanted to do was get the sum of the last k elements how can we do that well we can just take the sum of the card points array from the index right because that right index is literally just the length minus k so we want the last k elements so we can start at index right go all the way to the end of the card points array and take that sum and that can be our initial total sum so far now i said that this is o of one memory but technically i think python creates a temporary array when you do this sub when you do this like sub listing but we're just going to kind of ignore that because obviously i could do the exact same thing with just a for loop if i really wanted to and i don't think an interviewer would be too nitpicky about that so the next thing we're going to do is initialize our result to whatever this total happens to be this is our on this is our initial result and we're going to look for a result that's even greater than this one if it exists so now is the portion where we're going to be sliding our window so we're going to keep doing that until right is out of bounds so while our right pointer is inbounds we're going to keep incrementing it but before we increment it we want to potentially update the total right so what we want to do to the total is add to the total whatever the left value is in our card points array right because we're always adding the left value and subtracting the right value because the right value is you know that's just kind of how we did it in the drawing picture and that's what makes sense so this is kind of the computation we're going to do we're going to update our total by adding the value on the left index and removing the value on the right index updating our total and potentially if this total is greater than the result we'll end up updating our result variable as well and of course once we're done with that we need to actually perform the slide operation for our window so i'm just going to increment the left pointer and increment the right pointer and of course we're going to keep doing that until we get out of bounds in which case you know this loop is going to run about k times i think k plus 1 exactly something like that and once we're done we know we'll have computed whatever the maximum result was and we can go ahead and return it and as you can see this solution is very efficient it's definitely surprisingly easy for what you would expect from a google coding interview but i'm sure the interviewer would have some additional follow-ups would have some additional follow-ups would have some additional follow-ups for this question and maybe the interviewer is looking for how well can you explain the idea and maybe how clean your code could be so i hope that this video was helpful for you if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Maximum Points You Can Obtain from Cards
maximum-number-of-occurrences-of-a-substring
There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards. Your score is the sum of the points of the cards you have taken. Given the integer array `cardPoints` and the integer `k`, return the _maximum score_ you can obtain. **Example 1:** **Input:** cardPoints = \[1,2,3,4,5,6,1\], k = 3 **Output:** 12 **Explanation:** After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12. **Example 2:** **Input:** cardPoints = \[2,2,2\], k = 2 **Output:** 4 **Explanation:** Regardless of which two cards you take, your score will always be 4. **Example 3:** **Input:** cardPoints = \[9,7,7,9,7,7,9\], k = 7 **Output:** 55 **Explanation:** You have to take all the cards. Your score is the sum of points of all cards. **Constraints:** * `1 <= cardPoints.length <= 105` * `1 <= cardPoints[i] <= 104` * `1 <= k <= cardPoints.length` 1\. The number of unique characters in the substring must not exceed k. 2. The substring must not contain more than one instance of the same character. 3. The length of the substring must not exceed the length of the original string.
Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce.
Hash Table,String,Sliding Window
Medium
null
1,770
hello everyone welcome to goddess camp so today we are at the fifth video of our recursion series in a previous video we have seen what is memoization and how to work with recursion and memorization and we have seen an example of a bonus a series how we work with memorization and recursion to work on the problem so today we are going to see another problem that we are going to solve using recursion technique and memorization let's get into the problem statement here we are going to cover maximum score from performing multiplication operation this problem has been asked in a weekly contest of lead code so the input given here is a two integer array nums and multipliers we have to return the maximum score after performing m operations so the operations we can perform here is choose one integer x from either the start or the end of the given array add multipliers to into x to the score remove x from the terry so let's understand this problem first with an example consider our first element in our multipliers array that is -10 multipliers array that is -10 multipliers array that is -10 so we are checking whether multiplying it with the first number or the last number gives us more value so starting with multiplying minus 10 with minus 5 gonna give us 50 so as we have used -5 gonna give us 50 so as we have used -5 gonna give us 50 so as we have used -5 let's take it off and moving on to a second value minus 5 so let's check multiplying it with minus 3 or 1 is going to give us higher l so let's consider 1 so minus 5 into 1 it's going to give us no minus 5 into minus 3 so minus 5 into minus 3 is going to give us 15 so moving on to a third value 3 so now it's time to multiply it with minus 3 or 1 so multiplying 3 with 1 is actually going to give us more value so 3 into 1 is going to be 3 but this is the wrong step we are taking i'll tell you why later but let's consider we have multiplied it with 1 and moving on to our next element 4 with 7 or -3 next element 4 with 7 or -3 next element 4 with 7 or -3 4 with 7 is going to give us the higher value so we are going to multiply it with 7 so 4 7 is going to be 28 and finally moving on to a 6 multiplying 6 with minus 2 is going to give us higher value so 6 into minus 2 is gonna give us minus 12 so this actually sums up to 84 but if you consider the first and second value as such so instead of this step that is multiplying three with one let's consider we multiply three with minus three so in this case if we multiply three with minus three we're gonna get minus nine so as we have used minus 3 the rest of the values left in nums array is going to be minus 2 7 and 1 so now moving on to our value 4 let's consider we multiply 4 with 1 it is going to give us 4 and finally our 6 so we have used 1 so now we check whether 6 has to be multiplied with minus 2 or minus 7 so 6 with 7 is going to give us higher value so 6 into 7 is going to give us 42 so adding these values plus 15 and 50 is going to give us 1 0 2 so now by just changing one value we have achieved a tower better solution one zero two so checking one and the last value which server is giving higher value every time doesn't give us the optimal or the best solution we needed instead we have to check every possibilities that is if we take this value we have to check both the values and further steps and if it is giving lesser value we have to backtrack to the step and then try different values to come up with a better solution so in order to do that if we get problems like this that is trying out all possible values greedy solutions a recursion are going to help us achieve the solution so here the recurrence relation we found is if we are considering this first number from multiplayer or each number from multiplayer and considering the first value then a rest of the values with rest of the values at nums is going to be added to that value for example if we are considering minus 10 and minus 55 from arrays this is our particular value along with that rest of the values and nums that is from minus 3 to 1 into rest of the values at multiplier that is minus 5 to 6 is gonna perform the operation and add it with the result if not we are going to consider -10 and one similar way the rest of the array from minus five to seven and minus five to six from multipliers is gonna perform all the operation and add with this result so let's see how we're going to code it recursively before applying memoization so as usual we are going to have a helper method which is gonna return the largest value so let's have our nums array a and multiplier array m and the starting and ending index of nums array because if we consider the starting index it is going to be from the second element till end if not it is going to be from the first element to end minus 1 so to indicate the index of where we are considering the array we are going to have in start and end and one more integer which is going to point at the multiplier index so m index so let's start so we are going to start by having values 1 and 2 that is if we are considering the first element from the array that is gonna give us one value if we are going to consider the end element from the array we are that is going to give us the one more value so we have to return the maximum of both the values in that case i am going to have value 1 which is gonna take the current index from multiplier array and multiply it with first the starting index of the nums array and one more integer value which is going to take the same number and multiply it with the ending index value and finally we are going to return max of value 1 comma value 2. so now here as we have multiplied the first number with the starting value the rest of the operations will be from we are going to call the same helper method and pass array nums and multiplier and the starting index set as start plus one and the ending index is going to be same and every time we considered one value our multiplier index is gonna move to the next number so m index plus one so as we have considered the first element we are going to send the rest of the array as a parameter to process the same way with value two i'm going to call the same method with starting at the same point but end is going to decrement by one because if we consider the end element we are going to remove it and consider the index mode one step forward and m index gonna add so now we found the recurrence relation and constructed our code so we have to stop this code by using our base condition so here the base condition is we are going to do the operation or perform the operation m times so m is nothing but the size of the multipliers array so here the m index is going to point at every element in the multiplier if it points at the last element which means we are done performing all the operations and we have to terminate the loop or terminate calling the recursive function so we are checking if my m index is equal to the a multipliers dot length that is every time we are iterating it and if it reaches its length which means we processed every element in the given array so we are going to return simply zero so this will terminate calling the methods again and simply return zero so now from our main method let's call the helper method we are going to pass the nums array multipliers array and the starting index is 0 ending index says nums.length minus 1 ending index says nums.length minus 1 ending index says nums.length minus 1 and the multiplier index also starts from zero so once it reaches the complete length we iterated all the values and it returns zero as our output so let's run this code yes it is running fine and giving us the actual output we needed but if you submit this code it is going to give us time limit exceeded yes time limit exceeded for the input so how do we execute it without time limit exceeding to see that let's understand how the recursive functions are called so our helper method is having the parameters that is starting index of the nums ending index of the nums and the multipliers index so let's consider we are starting from the index 0 and considering the first element and the last element 5 so this further calls the first element and considering the first index if we are considering the first index that is minus 5 the rest of the array is going to be from 1 to 5 so starting index is going to be 1 end index going to be 5 and multiplier index is going to be 0 same way if we consider the last element 1 it is the rest of the array is going to be 0 to 4 so 0 4 and then 0. further this element is going to call if it is considering the first element the index starts from 2 to 5 and then for the first element of the multiplier array if it is considering the last element the index starts from 1 to 4 and then considering the first element same way if it is considering the first element it is going to be 1 2 4 and then for the first element of the multiplier element same way if it is considering the last element the index is going to be 0 to 3 with the first element of the multiplier element further if you call these elements are going to be giving us so this tree goes till the last multiplayer index becomes four that is it start from the zeroth index and one level for uh index one and second level for two and one more index for three and level four for fourth index and it terminates when it reaches the size four so now if you observe the values here 1 4 1 are equal and 1 3 2 are equal and you can find so many values are repeating so this is duplicate of operations as we saw in your in a previous video we are performing extra operations or repeated operations in our solution so to avoid that we are going to implement memoization that is if we see these steps are already defined or performed in our code we are going to store its value and then retrieve it when we needed it again so let's see how we're going to alter our code so in our previous video we implemented fibonacci series memorization using a hash map here also you can use hash map to store the values and retrieve it later just for a change i'm going to implement it using arrays so i'm going to have an array dp which is of size 1000 cross 1000 because here in our description the limit given here is yum can go 10 of size 10 cube so we have declared here the array of size 10 q so now we are going to store the values here that is our tp of m index start is going to be we're going to store the value in our array and then return the value so every time it enters the loop we are going to check first we are going to fill the array with minus one we are going to fill the value with minus 1 so we are going to check if is not equal to minus 1 which means we have updated the value then return the value which is stored already so let's run this code okay let's not try filling the values the default value in ra is gonna be zero so we are going to check if the value is not zero then that is the case we have already filled our array so we are going to return the value so yes let's submit it now so yes now our solution is accepted our previous solution using recursion was not accepted but after implementing memoization it is accepted so hope you're getting how to use memoization when needed that is when we perform duplicate operations memorization comes to help where we store our values and then return it whenever we need to perform it again thanks for watching look for more videos on recursion if you like the video hit like and subscribe thank you
Maximum Score from Performing Multiplication Operations
minimum-deletions-to-make-character-frequencies-unique
You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`. You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will: * Choose one integer `x` from **either the start or the end** of the array `nums`. * Add `multipliers[i] * x` to your score. * Note that `multipliers[0]` corresponds to the first operation, `multipliers[1]` to the second operation, and so on. * Remove `x` from `nums`. Return _the **maximum** score after performing_ `m` _operations._ **Example 1:** **Input:** nums = \[1,2,3\], multipliers = \[3,2,1\] **Output:** 14 **Explanation:** An optimal solution is as follows: - Choose from the end, \[1,2,**3**\], adding 3 \* 3 = 9 to the score. - Choose from the end, \[1,**2**\], adding 2 \* 2 = 4 to the score. - Choose from the end, \[**1**\], adding 1 \* 1 = 1 to the score. The total score is 9 + 4 + 1 = 14. **Example 2:** **Input:** nums = \[-5,-3,-3,-2,7,1\], multipliers = \[-10,-5,3,4,6\] **Output:** 102 **Explanation:** An optimal solution is as follows: - Choose from the start, \[**\-5**,-3,-3,-2,7,1\], adding -5 \* -10 = 50 to the score. - Choose from the start, \[**\-3**,-3,-2,7,1\], adding -3 \* -5 = 15 to the score. - Choose from the start, \[**\-3**,-2,7,1\], adding -3 \* 3 = -9 to the score. - Choose from the end, \[-2,7,**1**\], adding 1 \* 4 = 4 to the score. - Choose from the end, \[-2,**7**\], adding 7 \* 6 = 42 to the score. The total score is 50 + 15 - 9 + 4 + 42 = 102. **Constraints:** * `n == nums.length` * `m == multipliers.length` * `1 <= m <= 300` * `m <= n <= 105` * `-1000 <= nums[i], multipliers[i] <= 1000`
As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before.
String,Greedy,Sorting
Medium
1355,2212
152
Le code problem number 152 maximum product subray so this produ so this problem gives us an integer array called nums and our goal is to find a sub array that has the largest product and return the product itself here it just gives us the information that the answer will fit in a integer right so the way I chose to approach this is while adding up all the products in itself using a iterative method right so I'm only looping through the array once I'll be keeping track of the minimum number and the maximum number we will show you why in a bit but let's move on the result is what we'll be using to return as the answer so in this case um initializing result as the first number is two the current minimum has two as well and so is the current maximum right now we are only iterating through the first number which is two so here I'm starting I at one sking pass the first number and will become three right so n is three 10 Max here is what I'll be using to store the current Max * n because over here I'm current Max * n because over here I'm current Max * n because over here I'm replacing current Max with the max but in my current mean I'll be using current Max the old current Max as well so I need to keep a temporary variable to store the product of current Max * product of current Max * product of current Max * n so 10 Max is equals to 2 * 3 right so n so 10 Max is equals to 2 * 3 right so n so 10 Max is equals to 2 * 3 right so C Max 2 * the N which is three this will C Max 2 * the N which is three this will C Max 2 * the N which is three this will give us five and here I'm calculating current Max again right so current Max is equals to the maximum number of here you can see I'm using two Max functions but since this maximum function is inside of another Max function so technically you can treat it as I'm finding the maximum number of three numbers right so I'm looking at 10 Max of five current Max which was two * n sorry five current Max which was two * n sorry five current Max which was two * n sorry current minimum which is 2 * n current minimum which is 2 * n current minimum which is 2 * n and N itself which is three this become six and from here we know the maximum number of these three is six same thing for current mean minimum of time Max which is five current mean was 2 * 3 and N itself five current mean was 2 * 3 and N itself five current mean was 2 * 3 and N itself which is three so by having the product we know that the minimum of the three products is three only right so basically the minimum is actually just taking the three without multiplying with two to get the sub product right so a number itself can be considered as a subarray as well after that we update the result in this case the result will be the maximum of two with current Max which is six and we know six is bigger than two so we update result to now hold six next we iterate through increment our I and we move on to the next number right next number is -2 so here I'm calculating T Max again -2 so here I'm calculating T Max again -2 so here I'm calculating T Max again right so T Max is equals to the current Max time N2 so this will give us uh2 right yeah so this will give us -2 uh2 right yeah so this will give us -2 uh2 right yeah so this will give us -2 that's our 10 Max current Max I'll be recalculating it to maximum of -12 the current minimum -12 the current minimum -12 the current minimum times -2 with n itself times -2 with n itself times -2 with n itself right so this will give us -62 and from here we -62 and from here we -62 and from here we know the maximum number from uh from having included this sub array it's actually just having -2 -2 -2 only right so that's what happens when we times -2 with this sub array right so we times -2 with this sub array right so we times -2 with this sub array right so the current Max is two right here I'm calculating current mean again so current mean is the minimum of 10 Max 12 current mean times n and n itself this will give us6 12 and two same thing and now the current minimum we know is -12 right which is the we know is -12 right which is the we know is -12 right which is the product of these three numbers which form a sub array okay so here the reason why we need to keep track of the current minimum is let's say this would to be4 instead right so by having current minimum multiplying with the next nend which is4 you will get uh 48 right because negative * negative will get us because negative * negative will get us because negative * negative will get us a positive number so this in itself can be a subarray which will give us a maximum product of 48 right so that's why we need to keep track of the current minimum but in this case since it's a four not a negative4 so unfortunately current minimum W get to shine this for this case up right either way uh once we done with all of this our result we will need to be checked but since current Max is -2 and six is more since current Max is -2 and six is more since current Max is -2 and six is more than2 so we don't need to update result since that is done we increment I to our last number which is four here we calculate time x again which is -2 * 4 is will give us8 right so that's -2 * 4 is will give us8 right so that's -2 * 4 is will give us8 right so that's a product of multiplying -2 and a product of multiplying -2 and a product of multiplying -2 and 4 here I recalculate current Max maximum of 10 Max current minimum times n and n itself right so you can see here if this were to be4 48 will be our maximum number and result will be updated to Max which is 4 but since this was a four so this will actually give us 48 instead so from here we know the maximum number is to just have the four itself and for the current minimum is technically the same thing for itself current minimum will be 48 right so we're waiting for the other negative number but in this case it does not come right it did came in the end either way um four is less than the result we have which is six so the current Max product we have was from 2 * 3 right product we have was from 2 * 3 right product we have was from 2 * 3 right which is six and that's what we will be returning and you see over here it checks out with our answer right so we have the product of six okay this is pretty straightforward that's all I have to share thanks
Maximum Product Subarray
maximum-product-subarray
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,3,-2,4\] **Output:** 6 **Explanation:** \[2,3\] has the largest product 6. **Example 2:** **Input:** nums = \[-2,0,-1\] **Output:** 0 **Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-10 <= nums[i] <= 10` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
null
Array,Dynamic Programming
Medium
53,198,238,628,713
1,629
hello everyone so in this video let us talk about another easy problem from lead code the problem name is slowest key so possible states that you are given a newly designed keypad and you are testing that where a tester passed a sequence of n keys at a particular moment of time so you are given that there are some like keys that the tester presses now you're given a string key pressed of length n so it is given that what keys you pressed and it is of length n and next thing is uh where key pressed of I was the ith key press as a testing sequence okay so these are pressed at the testing sequence and a sorted list release time where release type of I is the time the ith key was released so as you can see that when you are testing this Keys it is given that at which point this particular key is released like it is like not like it is just the key is released so what you can see that if the time starts at zero what you can see is that C is pressed till second nine at second nine c is ready so let's say that you start from 0 you keep on pressing C okay and then you release C at time equal to nine now you start pressing B and you release B at time group 29 so how much time you have been pressing B for 20 seconds from 9 to 29 to 20 seconds even pressing B and from 29 to 49 you'll be pressing C and from 49 to 50 you just for one second you just press D so this is the overall time every key is pressed and the time like release time every key is released okay now what you're given is that uh you just have to find out the key that your the longest duration you pressed a particular key okay that's the thing that you just have to find out and uh if there are multiple keys that you pressed for the same amount of time then you have to print out the key with the lock like so graphically largest value so let's say you print or actually you pressed A and C both let's say five seconds and those are the maximum ones so you will print C you will not print a because C is lexographically more or larger than a okay that's overall idea so it's pretty much simple then you just have to find out a difference between the current value and the previous value that will give you the duration and then you even just find out based on the duration whether the duration is the maximum one that you have seen till now or like this is some random value and then depending upon that you will like maximize your current answer if there are two same value answers then you will take the one that is lexographically largest minimum simple nothing much complicated here as well the only thing I have to understand is that for every element you will match it with the previous element but for the first element it will start from zero okay because as you can see that the first nine it will start from zero you will match it with this element okay because you start from zero and then that you release the first key at time equal to this so either like you can push a zero at the very start of this array or you can initialize a variable last like what is the last time you have like of let's say what is the start time for this particular thing okay so you will initialize the variable that is last equal to zero and then you will compare this current element with last okay so you have started let's say with zero and you have pressed this last key at nine okay or let's say You released it at nine and thus what will happen is that you will just get the answer and every step you will update your last to the current value so now you will start at this point and you will release at this you will start and then you will start at this point release at this so you will like update this value like whatever type of value or like approach you want you can do that so this is total idea that you will make a variable that is last equal to zero this is the length this is the maximum that you have to find out the maximum duration for a key that is pressed this is the capital that you want to find out iterate over all the characters then the whole condition is that you have to maximize so what is the duration of a particular key pressed is the current release time minus the last value because this last Value Store the value uh that is for the last key okay and then you find out the like the difference of them if it is greater than maximum which means that the duration is maximum then the maximum I have seen till now then I will update or that the condition is if this difference is equal to the maximum okay if it is equal to the maximum I have seen But the key that I am pressing is lexographically larger than the maximum key I have seen okay in both of these scenarios what you will do is that you will update your maximum and the key that you have just pressed that is the electrographically largest key and depending upon that is just a simple for Loop and the end you will just return the answer and every time after this if condition you have to update your last because that's just denotes that what is the last key or the last time stamp okay and then you have to compare the current timestamp with the last time step okay and that's it you're just comparing the current timestamp with the last time that's a simple Logic for this problem nothing much complicated here as well it's just a for Loop so o of n tank membership problem so if you still have a dots you can mention in the comment box of this particular problem I will see you in an excellent encoding and bye
Slowest Key
minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits
A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time. You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released. The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**. _Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._ **Example 1:** **Input:** releaseTimes = \[9,29,49,50\], keysPressed = "cbcd " **Output:** "c " **Explanation:** The keypresses were as follows: Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9). Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29). Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49). Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50). The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20. 'c' is lexicographically larger than 'b', so the answer is 'c'. **Example 2:** **Input:** releaseTimes = \[12,23,36,46,62\], keysPressed = "spuda " **Output:** "a " **Explanation:** The keypresses were as follows: Keypress for 's' had a duration of 12. Keypress for 'p' had a duration of 23 - 12 = 11. Keypress for 'u' had a duration of 36 - 23 = 13. Keypress for 'd' had a duration of 46 - 36 = 10. Keypress for 'a' had a duration of 62 - 46 = 16. The longest of these was the keypress for 'a' with duration 16. **Constraints:** * `releaseTimes.length == n` * `keysPressed.length == n` * `2 <= n <= 1000` * `1 <= releaseTimes[i] <= 109` * `releaseTimes[i] < releaseTimes[i+1]` * `keysPressed` contains only lowercase English letters.
We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly.
String,Greedy,Binary Indexed Tree,Segment Tree
Hard
null
26
hey everyone welcome back and let's write some more neat code today so today let's solve the problem remove duplicates from sorted array 2. so we're given an integer array nums that's sorted in non-decreasing order that sorted in non-decreasing order that sorted in non-decreasing order that basically means that it's sorted in increasing order but there could be duplicates so they say non-decreasing duplicates so they say non-decreasing duplicates so they say non-decreasing just to be absolutely correct but maybe an array that looks like this the problem is that we might have a bunch of duplicates as we can see here we have three copies of one we have two copies of two and we have two copies of three but we are only allowed to have at most two copies of any value in this array so we can have two twos two threes and two ones but we can't have three one so we remove it but how do we remove it because we could just pop from the middle of an array but that's not very efficient so instead what we do is just shift the values so what we would actually want to do in this case is remove this too but we'd also remove these two guys and move the two values over here same with these two threes we'd want to remove them from their original positions and then push them over here where the next available slots are so this is what our actual array would look like now when we say remove from here we're not actually deleting that memory or even overwriting the value in this position but we consider it deleted our actual output array will look like this one two three but we need some way to indicate that these are the only real values like this is taking up space but don't consider this as an actual value so what we do is return an integer indicating the size of this portion of the array which this problem refers to as k the convenient thing is that the way we're going to solve this problem we're going to have a pointer I think it's going to be called I but it might be called something else but at some point that pointer is going to be all the way over here and the way that indexes work they start at 0 1 2 all the way up until 6 in this position and look at that the size of this array happens to be six so wherever we leave off at the end of the array is also going to be the length of this portion so that's exactly what we can return whatever value this pointer lies on and it's possible that maybe we end up going out of bounds like our eye pointer over here is actually out of bounds that's also going to work so that's what we're looking to do now how exactly can we solve it that's the tricky part I'll show you a valid way but first let's go over the thought process so let's take a look at a slightly different example I basically just added another two over here so now the values that we're going to remove is this and this but if you try to solve this problem like the first version of this remove duplicates from sorted array what you would do is have two pointers let's call them a left pointer and a right pointer initially they're gonna both start here and we're gonna take the right pointer and increment it any time we see a value like in this case the right pointer okay we see one then the right pointer is over here another one that's fine we can have up to two of them but now over here we see a third one so what we would do here is we'd say the left pointer is going to be incremented because we have a one here we're allowed to have that so we move the left pointer over here and we move the right pointer as well the right pointer is going to tell us what value we're looking at and I'll show you what the left pointer is going to tell us here we have another one but that's okay we've only seen two so far because this array is sorted all duplicates are going to be adjacent to each other just like the first variation of this problem but now we shift the right and left pointer again now over here we see the third one that's not good so what we're gonna do at this point is not shift the left pointer we're gonna leave it here what the left pointer tells us is that every value before this point is our array so far like this is our array so far with the duplicates removed we've seen these three values but we know this doesn't count so this is our array so far the first two values that's why we're going to leave the left pointer here and we also know that this is the spot next time we see a value we're going to push this over here and actually that was the spot the entire time when the left and right pointer started over here and we saw that this is not a duplicate so far what we would actually have done is taken the value at the right index and moved it to the left index now in this case it didn't really do anything because both of the pointers are over here so we didn't swap anything and here we didn't swap anything when the left and right pointers are here and over here when the left and right pointers are here we didn't swap anything but we just left the left pointer over here and now we're Shifting the right pointer over here now we see that we have a two value this is not a duplicate so we're going to push it to the index over here so we're going to overwrite the value here we're going to put 2 over here and now our left pointer from here is going to be shifted to be over here and our right pointer which was here is now going to be shifted by one again over here now this is kind of the problem with this approach and I'll show you how to fix it in just a second but now notice how there's four twos in our array so over here now we're going to say well this is only the second two we have seen so far but how are we actually going to determine that like how are we going to know if there are more than two copies of this value the easiest way to do it would be to compare this value to the previous value and the previous value before that which would tell us that this is the third two in a row so what we would say now is we're not going to take this value and move it to the left position we're actually just going to skip this value leaving our left pointer here and taking our right pointer now and incrementing it over here but do you kind of see the problem with this approach now we're going to get to this two do the same thing there are multiple copies of it consecutively so we skip this one and we move our right pointer over here to the 3 over here now we see this three does not have duplicates so we're going to move it to the position with our left pointer but we're going to end up over writing this guy we need two twos we're not allowed to have three of them consecutively but we can have a couple in a row but we're going to end up over writing this one so that's kind of a problem with this approach the solution is actually really simple especially when we're going to look at the code but in terms of drawing it out the main thing is just that when we get to a value we're just going to count how many there are like we're gonna have a nested Loop which is going to bring our pointer over here our right pointer and I'm just going to keep counting how many of these twos there are and by the time we get to the end of it let's say our left pointer is still over here but by the time we get to the end of that streak we counted three twos so we only want two of them so what we do is take the first two and then shift them over by one we've moved this one into the left position so put the two over here and then take our left pointer and shift it by one over here then we take this two and put it in the left position and then we take our left pointer and once again shift it over here but we've already added two twos over here so now we're done then we take our right pointer increment it just by one because we're at the end of this streak now we want to get to this streak so just to clean this up a little bit right pointers over here and now we do the same thing here there's two of these we're gonna count them our right pointer is going to end over here yes we have two of them and we're going to start pushing both of these at the point where our left pointer starts so we would put the three here and then put another three over here and then our left pointer would be over here by the end of it so I'm gonna just draw that out our left pointer is here and at this point our right pointer would be incremented by one again now we're out of bounds so we would return this value if I didn't make it clear at the beginning all we're returning is this integer value K which in our case is going to be zero one two three four five six is going to be what we're returning because there are six values in this array we're doing everything in place so we don't have to worry about additional data structures but as you can see this is definitely the correct array with no more than two copies of a single value and we did it in linear time even though we have nested Loops you can see the two pointers we had left and right both of them are going to iterate through the entire array at most once we're not you know doing it a variable number of times so the time complexity is going to be 2 times n which we know reduces to B Big O of n there's no extra memory that we're using so the memory complexity is constant so now let's code this up so I'm going to have a left and right pointer both initialized at the beginning of the array and then just like in the drawing I'm going to have a right pointer that will iterate through the entire length of the array and then we want to count how long the current streak is so what we're gonna do is first set the count equal to one because whatever number we're at right now at index R is going to be a new number and we want to compare it to the next value in the sequence so nums at index R plus one while this is true then we want to increment the right pointer and for convenience we'll increment the count as well having extra variable for the count makes things a bit easier but there's a couple catches with this what if R plus 1 isn't even in bounds well then we wouldn't be able to increment this so let's add a guard here while R plus 1 is less than the length of the array and this is true we're going to increment by one so now we have the count of this streak it could have two values in it could have more than two values like three or four or it might even just have a single value it won't have less than that but it might have a single value we want to do at most two copies of this value so what we do is take the minimum of 2 and the current count so if the count is greater than 2 we're only going to get two copies of it but if the count is one then we're only going to get one copy of it we're going to take the minimum of these two values and that's how many times we're going to iterate through this and for every iteration we're going to take the value at the right index and put it in the left position and don't forget to increment the left pointer every time we do that now regardless of how many times we do this we know the right pointer is going to end at the ending of the streak and we want to increment at least one more time to get to the beginning of the next streak on the next iteration of the outer loop after that's done we will have the left pointer will be in the position that we need to return for reasons that we talked about earlier so all we have to do is turn the left pointer now let's run this to make sure that it works and as you can see yes it does it's pretty efficient though leak code is random with the run times if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatco.io it has a interviews check out neatco.io it has a interviews check out neatco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**. Then return _the number of unique elements in_ `nums`. Consider the number of unique elements of `nums` be `k`, to get accepted, you need to do the following things: * Change the array `nums` such that the first `k` elements of `nums` contain the unique elements in the order they were present in `nums` initially. The remaining elements of `nums` are not important as well as the size of `nums`. * Return `k`. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int\[\] expectedNums = \[...\]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** 2, nums = \[1,2,\_\] **Explanation:** Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,0,1,1,1,2,2,3,3,4\] **Output:** 5, nums = \[0,1,2,3,4,\_,\_,\_,\_,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `1 <= nums.length <= 3 * 104` * `-100 <= nums[i] <= 100` * `nums` is sorted in **non-decreasing** order.
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
Array,Two Pointers
Easy
27,80
1,814
Hello everyone welcome to my channel code story with mike so today we are going to do video number nine of our hash map hash set playlist okay lead code number 1814 is actually quite easy and a little bit I will tell you a suggestion and a pattern It is fine for this type of questions. Mostly in all such problems, you should do this thing which I will tell you today. It is fine but it is medium but I found it quite easy and you will also find it easy. I am 100% sure. The you will also find it easy. I am 100% sure. The you will also find it easy. I am 100% sure. The name of the question is Count Nice. Pairs in n Hey, it's okay and this has been asked by Ajan, let's see what the question is, it says that you have been given a Hey names in which there will be only non-negative integer numbers, does which there will be only non-negative integer numbers, does which there will be only non-negative integer numbers, does n't it mean from row to 1 2 3 and so on let us define. What does Revex mean? Reverse of an integer. Let's say 1 is 2 3 then its rev will be 321. If 1 is 0 then its rev will be 21 because what is the reverse of 1 0 to 1 and what is this integer actually? is 20 Okay A pair of incest images is nice When will you call any pair of images nice When it is Okay Aa and J should be greater than zero and Namaste should be less than T length Okay and Aa and J should be And the most important condition is this, okay pay attention to this, the whole numbers of aa plus reverse of numbers of j are looking at this is j, this is I, numbers of aa plus reverse of numbers of j must be equal to numbers of j plus reverse of numbers. Of i is ok return the number of sa number of nice pairs of andes ok since that number can be too large return it modelo ok we will remove it in modelo but this is important ok so first of all let's see the example numbers is 42 1117 So there is only one pair here, sorry, actually there are two pairs here, if you pay attention, there is a pair of 40 and 97, if you look, then look at 42 plus reverse of 97, how much will it be, 42 plus 97 reverse of 79, okay, it will be 121, similarly. Now what we do is 97 plus reverse of 42, we take out 97 p 24. Look at this, 121 has come, so you have got one pair, now let's see which is the second pair, first let me erase it, so you have got one pair, right, you have got this 42. 97 This is the first pair. Second pair, do you know which one is 11 1? Look, pay attention. 11 plus reverse offv, how much has come? Look, 12 has come. 1 ps reverse off 11, how much has come, 12 has come. Both are equal. 12 is equal, so two pairs. This is how I got the answer, we have two, so look, for such questions, a suggestion is very important and I am telling you a pattern, whenever you see a problem containing something like this, look, plus something of which is equal to something. Of j plus something of aa here is late, this makes khichdi. To confuse a little bit, look at this I is equal to i is equal to on the left hand side. Here I and J are mixed, here I is also and J is also. Khichdi has been made and look at the right hand side also, J and I have been mixed so that confusion is created. Do you always know what to do in such a side? Bring the things with I at one place and the things with J at one place. Isn't it? Bring the index people to one place J Bring the index people to one place A I have also commented in the lead code, a person has also told the same thing that always do not re-group in such questions and not re-group in such questions and not re-group in such questions and I have commented in that person's comment. You have also given a very good suggestion because recently I had got a question done in the playlist of DP Conception Questions, recently in which I had applied the same mind and had rearranged it, things get simplified a lot by rearranging them. Always try to re-group to re-group to re-group and Things on the other side, bring the I here and bring the J here, so let's say, if I bring the I people here, then yes, they will go in minus. Those people are okay, so I will remove them from here. If there was a plus, it would be a minus here. If there was a minus, it would be a plus here. Here, the i things came here. Similarly, here, if the j things came here, then in the minus, if j came, then the j things were at one place. The i things were at one place. Do and then see if it makes things easy for you, it is always okay to try, it is not that every problem will be solved, 100% problems will be solved but it will 100% problems will be solved but it will 100% problems will be solved but it will definitely make it easier for you and you must try, it is the same thing to do. I tried something in this problem also, you may remember that in the question it is given, Nums of i plus reverse Nums of j is equal to it Nums of j plus reverse of Nums of aa Look, we have made Khichdi here, both aa and j. In the left hand side and here too, J and I, both in the left hand side, in the right hand side, I have mixed the meaning of Aa and J. What did I say, bring the I's to one place, bring the J's to one place, so this is what I can see. You bring it here and this one that looks like J, bring it here and see what will happen Nums of A minus reverse of Nums of A is it Nums J minus reverse of Nums of J Okay, so look at this, there is a slight simplification. That's enough for us now, let's see how, yes, we have given this constraint. Now let's see an example. Okay, let's assume that this is your example. So pay attention to it once. We know what we will do. Look at the numbers of a minus reverse of. Nums of I for example now it is 13 ma 13 it is 13 minus reverse of 13 immediately remove 13 my 31 ok how much will come I think - 18 will come my 31 ok how much will come I think - 18 will come my 31 ok how much will come I think - 18 will come ok so in the same way I am all the numbers of aa minus reverse of numbers of aa I will remove it and see what will come 13 - 31 - 188 10 - 19 35 see what will come 13 - 31 - 188 10 - 19 35 see what will come 13 - 31 - 188 10 - 19 35 - 53 - 18 24 - 42 76 - 67 So what I have - 53 - 18 24 - 42 76 - 67 So what I have - 53 - 18 24 - 42 76 - 67 So what I have removed is Nums of Aa Minus Reverse of Nums Aa I have removed it ok now see the question has changed a lot. It has become very easy for you, it just tells you that the value of numers of i minus reverse of numers i is okay, is that value also there? Hey, we have numers of j minus reverse of numers h. Look, numers of i. Minus reverse of nums aa, this is the value of i that I had calculated and somewhere else there is a value like this where if I had done nums of j minus reverse of nums j, then exactly nums of aa was equal to minus reverse of nums aa. Yes, look here. But it is -1, here too, it -1, here too, it -1, here too, it is cleared till here, so see, a pair can be formed here, 01 2 3 4, so see, a pair of 0 Katu can be formed, see, it is Rotu, right, it is 18 equal because it was 13 and this is 35. So both of them have satisfied this condition, right? And look, if we changed the equation, the problem became easier. Now it is fine, so 02, 03 and 23 are three pairs, I got them from here, I am fine and look, I got four pairs. Ts y, our output is four, there are four such pairs which will follow this property. Okay, look, if we changed the equation, then how easy it has become for us. The problem is how easy it has become. Nums of aa minus reverses of Nams. We have already done this. Removed and seeing if there is any other element that follows this property nums of j minus reverse of nums j and that is exactly equal to what nums of aa minus reverse of nums aa k Okay so it became very simple and this So there is nothing, so you just have to count, like -1 is there, count, like -1 is there, count, like -1 is there, look here, now look, it has become very simple, let's accept the problem, now the layers here are -1, have accept the problem, now the layers here are -1, have accept the problem, now the layers here are -1, have you seen till now, what have you not seen, no problem, store it in the map. That I have seen minus Sara once, okay now I have come here, now there is nothing, now it has become a question of counting, I have not seen even nine nines, I have stored nine in the map, this is my map, such questions. You must have made it many times. 18 has come. -1 has come. Have I seen -18 -1 has come. Have I seen -18 -1 has come. Have I seen -18 in the past? Yes, I have seen -18 in the past. So in the past? Yes, I have seen -18 in the past. So in the past? Yes, I have seen -18 in the past. So how much will I add to my result? -What is the how much will I add to my result? -What is the how much will I add to my result? -What is the frequency of 18? There is one, now one is added. I have seen only one in the past, so it will form a pair with that one, okay, so one pair has been found, now its frequency will have to be increased because now it is two, minus 18, I have seen it twice, okay. Now come here -1 is seen it twice, okay. Now come here -1 is seen it twice, okay. Now come here -1 is seen again, so I will look, I will ask, brother, have we seen -1 in the map, then I will say yes, we seen -1 in the map, then I will say yes, we seen -1 in the map, then I will say yes, we have seen two minus 18, so this one and the eight is 18. It can make a pair with these two. If there is then two pairs will be formed, my two pair is possible isn't it -18 will pair with this pair is possible isn't it -18 will pair with this pair is possible isn't it -18 will pair with this and will pair with this, meaning there are two frequencies, then two pairs will be formed, then it becomes 1 + 2, after that it comes to nine, so this is + 2, after that it comes to nine, so this is + 2, after that it comes to nine, so this is nine, let's see the map. Yes, we have seen in the past, we have seen one in the map, okay, don't forget to update its frequency here, three and here, nine, I have seen once, then one more pair will be formed, and I have updated the frequency of nine to two, now further. It has increased, it has gone out of bounds, this is our answer, think about how simple it has become, it is okay, that is very important, the suggestion I have given you is a very useful suggestion, it is okay and I had solved a problem, I think Lead Code 2926 There was a number like this, it was a very good problem and I solved it in the same way, brother, its concept was different but by rearranging it became easier for me. It is okay to solve it a little, here by rearranging it. So the whole problem is over, it has become so easy that it is nothing, it has become a question of counting, isn't it, and here, if you pay attention, the constraints of the problem have been given too much, I think the power of 10 is something like this. Okay, so it's obvious that the quadratic solution will not work for you. Okay, the sk solution will not work at all. sk, why am I saying this because what would have been a brute force approach is that you would have written a for loop taking out all the possible pairs. Write a for loop of 'j' Write a for loop of 'j' Write a for loop of 'j' is fine, then inside that you would check that sums of a plus reverse of sums of a is equal to sums of j minus reverse of n, meaning whatever equation is there, you would try to follow it. I had given the equation here, it is okay and if we had applied double force for loop to find all the pairs then it is obvious that it would have gone quadratic which is not acceptable, the constraint is very high but look here, we do not have to do much, that's it. We are simply counting through the map, so if we write the story to code and will do its time completion is important, what to convert the numbers aa into two numbers of aa minus the reverse of numbers off. Come, now you tell me that you have to reverse an integer, for that you must have already known. I am pretty sure that how to reverse that function, I will also show you while coding, okay, you must know this either in childhood or in school or college. I did not know how to write a function to reverse an integer. I get asked this question many times, maybe even in interviews sometimes. Okay, it is quite easy, but our first step was to divide the number aa into the number i minus. Converted to reverse i, here's what I did, converted here, after that what I said, we will store the map, okay, we will create a map, after that what will we do i = 0 i &lt; n i + what will we do i = 0 i &lt; n i + what will we do i = 0 i &lt; n i + go to each element when we have this Converted, we will go to that list and check that we will keep adding it to the result. Result I is equal to Result Plus. Have we seen this name of I in the map in the past? If we have seen it in the past, then whatever is its frequency should be added to the result. If you have n't seen it, then yes here the zero value will come automatically. Okay, in C Plus, we will take the power of Model 10 from 9 P. It is given in the question, just write it and don't forget to update the frequency here. Names Off. I said that the numbers of Aa, now I have seen it once more, it is correct to do the numbers of Aa plus, and what to return in the last, the result has to be done till now, it is clear, now let's try to understand the time complex, it is important to pay attention. Give some minute things here, I am going to discuss, pay attention to this for loop, it seems to be off, but inside reverse is also being called. Okay, so see, it depends on the interviewer. If you explain to the interviewer like this, say that if If I include the time complexity of the reverse function in the calculation of time complexity, then I will tell you what will be its time complexity. When you have to find the reverse of any number, what do you do? Let us assume that it is 321. You go to each of its digits. Okay, you go to one, then to two, then 1 * 10 + 2, then you Okay, you go to one, then to two, then 1 * 10 + 2, then you Okay, you go to one, then to two, then 1 * 10 + 2, then you go to th. 12 * 10 + 3 123, so you go to th. 12 * 10 + 3 123, so you go to th. 12 * 10 + 3 123, so you go to one digit each, right? If any number, any integer, know how many digits it can have, the total log off of whatever number is yours to the base 10 is so proportional, the number of digits of any integer is so much, it is proportional. Okay, so this is also logarithmic, then okay, how much will be the time complexity, n * n, so how much will be the time complexity, n * n, so how much will be the time complexity, n * n, so this for loop is taken and its logarithmic will be something, isn't it log off, whatever number you send, okay, whatever is the max. Its value will be of n in log of num but many times I notice that in the lead code they ignore it because of the very small value and consider it as a constant but I do not want to consider it as a constant, full details in the interview. I will give that brother, that's why I have taken the log here and you should also do the same, do not assume yourself to be a constant, tell the interviewer that this is actually time complex and if it is a very small value then you can ignore it. That's it. Its time complexity and one more for loop in the last you will write this is very simple o if n is then o is offv operation, all these are removing numbers of i from the map then it looks like offv because I will take an unordered map. In c+ p, the because I will take an unordered map. In c+ p, the because I will take an unordered map. In c+ p, the operation of unordered map is done in o ofv, so it is done in o of n, okay, it was quite simple, let's code quickly and finish it, so let's code quickly, exactly as we have learned, the same question. It is good and such questions are generally asked in the interview. We already calculate the power of int m = 1e as 9 + 7 already calculate the power of int m = 1e as 9 + 7 already calculate the power of int m = 1e as 9 + 7 because we have been asked to do the mode with this. Now let us start here. What did I say first? It was said that we take the map and keep it because we have to count and take out n = we have to count and take out n = we have to count and take out n = numbers dot size. We took out this from the undead map. What was the first step, convert numbers of aa minus reverse of numbers of aa. For eta = 0 i For eta = 0 i For eta = 0 i e &lt; n i+ p then numbers of i will be e &lt; n i+ p then numbers of i will be e &lt; n i+ p then numbers of i will be numbers of aa minus reverse numbers of aa ok, we will write a separate function named reverse, ok till this point is clear. Gone after that when we reverse converted the numbers i into numbers i minus reverse i then we just have to calculate our count result is equal to 0 okay for int i = 0 a i take n+ p okay for int i = 0 a i take n+ p okay for int i = 0 a i take n+ p okay so what do I have to do the result is Equal to Result Plus Have I seen this Namsai in the past? If I have, then calculate its count. Only so many pairs can be formed. Okay, and module m had to be done. And since I have seen Namsai I, then its frequency. From aa to plus we have to return the result in the last. Okay, now let's do reverse here int rev int nam int answer t 0 while nam will keep finding its reverse as long as it is greater than zero. So remember how to find it. They were the first to take out reminders, I remember I think I had done this in school sometime, took out the moist percentile 10 reminder, then the answer which is your answer is equal to the answer in 10 plus which you have just got the reminder, okay and the moist e is equal to two. Nam ba return 10 in the last, the answer is ok, you can do reversal in a more short way but this clean code is as good as it is, I like it, let's run it and see, hopefully all the test cases should pass, after that we will Submit and see if we are able to pass all the cases I hope I was able to help any doubt you have in the comment section come here to help you out see us in next video thank you
Count Nice Pairs in an Array
jump-game-vi
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])` Return _the number of nice pairs of indices_. Since that number can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[42,11,1,97\] **Output:** 2 **Explanation:** The two pairs are: - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. **Example 2:** **Input:** nums = \[13,10,35,24,76\] **Output:** 4 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109`
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value in the heap is out of bounds of the current index, remove it and keep checking.
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
Medium
239,2001
32
hello guys welcome to algorithms made easy my name is radha graval and today we will be discussing the question longest valid parenthesis in this question we are given a string containing just the characters that is open in closed parenthesis and we need to find the length of the longest well-formed parenthesis longest well-formed parenthesis longest well-formed parenthesis substring in the first example we can see that the longest substring is of length 2 so that's why we output 2. in the example 2 the longest substring is of length 4 so we return 4 and as in example 3 no string is present we output 0. given the constraint with the problem before moving ahead with this problem i would like to bring your attention to one of the previous problem that we have solved on lead code itself the name of that problem was valid parentheses and this problem is an extension to that problem only so before moving any further i would suggest you to please watch that video as that way it will be easy for you to solve this problem so you can find that video on youtube by searching valid parentheses algorithms made easy this is the video the link is at the top also and in the description below so before jumping on to the optimized approaches we'll first discuss the brute force approach as we know that a longest valid parenthesis will be of at least length two so we can have a two for loop first starting from up to zero to length of the string and the second loop starting from plus two index till the end of the string while we increment this index two times rather than only one time and each of these substring between the first index and the second index we will be finding if this is a valid string or not we can use the code that we have implemented in this previous problem that is valid paranthesis but as we will be using around three loops for that the time complexity will be higher that is n cube well the space complexity will be of n as we will be using a stack coming back to the second approach as we know that in most of these valid parentheses related problems we use stack in order to solve the problem and hence now we will be discussing an approach which uses stack to solve this problem so let's see that with the help of an example so suppose this is the string given to us and as we know that we will be using a stack and we have depicted this string in a form of an array so that way it will be easier at the start of the program will first put in -1 into the stack so there's a put in -1 into the stack so there's a put in -1 into the stack so there's a reason that we have put in -1 into the reason that we have put in -1 into the reason that we have put in -1 into the stack and we will discuss that once we have seen how this approach works in this approach what we are currently doing is for every closed bracket we need to pop the element from the stack and for every open bracket we need to push an element into the stack now in the previous problem that is valid paranthesis we were pushing directly the parentheses as there were three kind of parenthesis in that particular problem but in this problem there is only one kind of paranthesis and as we need to find a length we need the index of the parenthesis so that we can find the length of the longest valid parenthesis so now we will start looping from the zeroth index and we pick that value as this value is a closed parenthesis we know that we need to pop the value from the stack so we will pop this value from the stack and now the stack becomes empty now we cannot let the stack remain empty if the stack is empty we need to push the index of this closed parenthesis into the stack and we will do just that now there is the other case when the stack is not empty and we'll discuss this now we come across an open parenthesis as the next index so we will push that value into the stack and now we move again to the second index and this time we find that it's a closed parenthesis as it is a closed parenthesis we need to pop a value from the stack but this time the stack is not empty as the stack is not empty we know that there must be some length of string wherein the parenthesis has matched so now we need to find the length of the string the length of this string will be nothing but the current index minus the index at the top currently the index at the top is 0 and the current index that we are working is 2. so the length of this string becomes 2 minus 0 which is 2. we'll continue to do these steps till the end of the string and the maximum length is what our answer really is so now it's time to code this particular approach so as discuss we need a stack of integers and we'll put minus 1 at the start of the program now we need to loop from i 0 till the length of this string so the character is now if this character is an open bracket that means we need to simply push the index into the stack so here also it will be a push now as only two types of characters are allowed in the else part we know that it is a closed bracket so we need to first pop the value from the stack and now we need to check if the stack is empty or not if the stack is empty we need to push the current index into the stack otherwise we need to find the length and we discuss that the length will be nothing but the current index minus the value at the top of the stack and now we need to take the max of it so we'll define a max variable which will initially be 0 and we'll take the max of it at the end we need to simply return this max so let's try to run this code so it ran successfully let's submit this so it got submitted successfully the time complexity is of n and the space complexity is also of n now this approach takes an extra space to hold the values into the stack what if there is an approach wherein we do not need an extra space so let's see that with the help of an example so suppose this is the string given to us we have depicted it as an array now there is one thing that we can see and make out from this string or any valid parenthesis string has these conditions satisfied that is the number of open parenthesis should be equals to the number of closed parenthesis in a valid string no matter from which direction we find it so if we try to find from the start the number of open parenthesis and the number of closed parenthesis and at any given index if the two are equal that means the string is valid up till here now there is a catch in that particular statement when we are going from the start of the string till the end if we encounter more number of closed parenthesis than the number of open parenthesis then we are sure that no string can be valid up till this index as we have encountered more number of close paranthesis and the vice versa case can be said when we are traversing the string from the end to the start of the string in this case if we encounter more number of open parenthesis as compared to close paranthesis we are sure that there cannot be a valid string up till this index so now it's time to code this approach and we will discuss that while we code it so let's take two variable one is open which hold the count of the open parenthesis and other close which hold the count of the closed paranthesis first we will go from 0 to n and then we go from n to 0 so we'll have a loop wherein we have this i variable going from string dot length we'll take the character now if the character is open we increment the open else we are sure that it is a closed parenthesis so we increment the close now if anywhere the open is equals to close let me assure that string is valid now how do you find the length of the string is nothing but the addition of open plus close or we can say two times of open or two times of close whichever way you like you can use that so the length of the string will now become open plus close now this is a case which we discussed that if the number of close parenthesis is greater than the open then we are sure that this string is not a valid string up till this index so in this case we need to simply make the two variables re-initialize to zero the two variables re-initialize to zero the two variables re-initialize to zero now as we are finding the length we need to take the max length of it which is the answer that we need so the max will initially be 0 and at each step we will be finding the max of it so this completes while we are going from the start of the string till the end now we need to go in the reverse direction so before going into the reverse direction we need to first reinitialize this open close variable now we'll loop from string.length we can copy paste this string.length we can copy paste this string.length we can copy paste this whole code now we can simply paste it so if it is open we are incrementing open if it is close we are incrementing close if both are equal we are finding the length and finding the max of it now here we need to check if the number of open parenthesis is greater than the number of closed parenthesis then we reinitialize these variables and at the end we need to simply return the max let's try to run this code so it ran successfully let's submit this so it got submitted successfully the time complexity in this case is of n while the space complexity is of one there is a third approach to this problem using dynamic programming so we'll see that so in the solution it is given how we can solve this problem using dynamic programming you can take help from this we'll discuss how this approach is working so it says that we have a dp array of the length of the string initially all the values in this dp array is are 0 and each value in this string signifies maximum length of valid string present up till that particular index we are sure that for an open paranthesis the value will always be 0 as no valid string will end with an open parenthesis we only need to work on this dp array when the parenthesis is a closed parenthesis so if the character is a closed parenthesis we need to check so there can be a case when the character next to this character is an open parenthesis which is like this case in this case the dp of i will be nothing but the value of dp of i minus 2 plus 2 because this string is already a valid parenthesis we need to just check if any valid string is present we need to add that value into this closed parenthesis value also now what if the value present next to this character is also and closed parenthesis in this case we need to find where does the open paranthesis of this particular close paranthesis lie and that index will be nothing but i minus dp of i minus 1 so we check that if the value present at this particular index is the open parenthesis or not if that is an open parenthesis we again do the same thing that we did over here that is adding the dp of i minus 1 and the value present before this open parenthesis and then adding the two for this particular open and close parenthesis here is a graphical representation of that particular approach that they are using and as a code this might look a little complex at first but once you are able to grasp how they are approaching the problem it will be much more easier and useful in other problems too the time complexity in the space complexity in this case are both of n so do try to understand this code and the working of this approach and let us know if you have any questions or concerns thanks for watching the video see you in the next one
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_. **Example 1:** **Input:** s = "(() " **Output:** 2 **Explanation:** The longest valid parentheses substring is "() ". **Example 2:** **Input:** s = ")()()) " **Output:** 4 **Explanation:** The longest valid parentheses substring is "()() ". **Example 3:** **Input:** s = " " **Output:** 0 **Constraints:** * `0 <= s.length <= 3 * 104` * `s[i]` is `'('`, or `')'`.
null
String,Dynamic Programming,Stack
Hard
20
1,314
hey what's up guys this is sean here again so let's take a look at another lead called problem today number 1314 matrix block sum given like a m times m by n matrix and an integer k return a matrix answer where each answer each element in this answer is the sum of all elements uh in the matrix where the uh where the r is within the range from i minus k to i plus k and the first same thing for the call for the column c with is visiting the range of j minus k to j plus k and r and c is a valid position in the matrix so a few examples here right so we have one two three four five six seven eight nine right basically we have seven sorry we have one two three four five six 7 8 9. so what does this mean right so how do we get 12 here basically no so these things this condition tells us you know basically we're trying to get a sum within the range of the range is the radius of k from the current ing so for example you know since the range is one right so it means that you know from zero the range is from one so which means the dot the range for the row is from zero to one because the uh the zero minus one is uh zero minus one is minus one it's not in the matrix here that's why for this in the zero the range the value for the answer is 0 is the sum of this okay where that's why we have 12 here okay so same thing for 2 here right so for number two here you know since the row range is still up to here but the column wise since we have one three that's why for number two here the range is like this okay that's how we get 21 here right and then so on and so forth right basically at each of the lo look at each of the location here we'll try to expand the range by k actually by k to the left side and by k to the right side if we if the we're reaching the border of course we'll stop there otherwise that's basically the logic here and since we're trying to get the sum offer in the 2d matrix so a common way of solving this problem is doing a presump right because that will give us a 01 time to calculate uh a part a sum within a 2d array otherwise you know the brutal force ways for each of the location i and j will calculate the answers right by using this uh formula that will be uh too slow so the way to solve this problem is that first we'll create like a pre-sum we'll create like a pre-sum we'll create like a pre-sum a 2d prism array here okay and once we have a 2d prism right at each of the i and j here we'll try to use this k right to get us the uh the top left corner and then the bottom right corner because you know i we can the only way we can solve we can get the pre-sum for this we can get the pre-sum for this we can get the pre-sum for this range for this right for this rectangle is if we know the uh basically the ending point and the starting point as long as we have the ending point and starting point for this for the current for the range of the current i and j we can just use that the presump to calculate the uh this range the answer i mean this is within this range so how do we calculate that right i mean so it's pretty straightforward right so for those who are not quite familiar with how this 2d prism works right let's say we have a 1 here okay and uh let's say we're trying to calculate the range of this one right let's say we're trying to calculate the sum of this rectangle so how can we calculate it assuming given this pre 2d pre-sum it assuming given this pre 2d pre-sum it assuming given this pre 2d pre-sum list so the way it works is that you know we have if we have a pre-sum if we have a pre-sum if we have a pre-sum at this location okay so this pre-sum at this location okay so this pre-sum at this location okay so this pre-sum which basically is summarize everything in this 2d or 2d matrix here right and then we have a start we have ending point so let's see the sorry this is the ending point and this is starting point is eight it's the top left corner if we have those two locations so the way we are calculating the presump for this is so not prism to the sum of this rectangle is that let's say we have this uh i and j here okay and then we have a ii and j and jj here so the way it works is the uh we are going to calculate the pre-sum we're using the calculate the pre-sum we're using the calculate the pre-sum we're using the pre-sum of the uh pre-sum of the uh pre-sum of the uh of this part we're gonna subtract the prism for this part first also we're going to subtract the prism of this part next so the presump for the top part is the pre-sum of what the top part is the pre-sum of what the top part is the pre-sum of what the pre-sum of the uh pre-sum of the uh pre-sum of the uh of i minus 1 and j right so if we use these values uh look for the values look for the presump by using this value that's gonna that's the sum of the top part and the same thing for this left for the left sum here right for the left sum is uh we have a we have i and then here right so we have i and then j minus one okay so after subtracting those two sections and as you guys can see we are subtracting this sections twice right which means that we have to add this section back so after subtracting this one and this one will be we subtract and then we're adding this writing this i and the minus 1 and j minus 1 back that's how we calculate the uh the total for this part okay cool yeah that's basically the idea after uh building this presump and the way we're building the prism is similar like how we calculate the uh how we calculate the sum by using this summer presump it's similar like we're doing we plus this we plus i minus one j and we plus the i j should j minus one and then we will also subtract that subtract the i minus one and j minus one similar idea here okay cool so i mean with that we can start coding and as you guys can see here since we'll be using the i minus one j minus one also the i minus one j minus one and when we uh when we define this like pre-sum location pre-sum location pre-sum location pre-sum array here let's see we have our pre-sum array here let's see we have our pre-sum array here let's see we have our m here and the length of the mat and then we have n equals to the length of the matte zero okay so when we define the prism here we can either define the same size of the m and n or we do a m plus one and n plus one so we can either do like a n and for range m so if we're defining this presump the same size of the simon n so which means that when we do a i minus one and the j minus 1 we have to do a special handling when the i and j are equal to 0 we have to uh handle that i mean separately right or another way is that we can do a padding right which means we're going to add like 0 on the left and on the top so that i mean later on when we use the i and i minus 1 j minus 1 we can simply uh ignore that because we have already handled that by adding a 0 by padding 0's right to this pre-sum by padding 0's right to this pre-sum by padding 0's right to this pre-sum array here and that's what we're going to do here because that will make the uh the code simpler later on so now the first step is to build the 2d presump right so for i in range one plus m and for j in range one two and n plus one okay because the other zero is our padding that's why we have to start from one okay and then like i said the pre-sum pre-sum pre-sum of i the price of i j equals to the mat first we get the current values which is i minus one j minus 1 right again since we are starting from the 1 here not 0 that's why we need to do i minus 1 j minus 1. and then we plus the pre sum i minus 1 j we plus the pre-sum the plus the pre-sum the plus the pre-sum of the i and j minus one okay similar like the uh when we use this presump since we are adding this i minus one j minus 1 twice we have to subtract that once okay right and j minus 1. cool yep sorry yeah and that's how we build the 2d prism so now since now we have the 2d prism we can just populate our final answer here so since the final answer is uh it's also like a 2d array here that's why i'm going to initialize it with m and n okay arrange m here so four i in range one two and plus one right similar like how we build the two d is presume above right for j in range one two and plus one so here you know at each of the i and j here we're trying to find uh let's say we have a i and j we're trying to find that the top left corner right we're trying to find this is the coordinates and the bottom right corner we're trying to find those two coordinates and but we cannot go out of the border of the 2d matrix that's why when we find that you know first let's try to find the uh the ending point right i call it ending point so for ending point i here we're going to do a minimum of m of i plus k right because the m is the it's a border right it's the biggest that the i can get that's why you know if the i plus k is greater than m then it means that okay it's out of the boundary so we have to go back to that about to that boundary of the of with this amp here right same thing for the uh for the j right we also need to do a minimum of n of j plus k right so that's how we find the coordinates of the ending point and the same thing for the starting point okay so for the max for the starting point we have to do a max of one right so i minus k so and so for this one i one is the lowest number we can go right same thing for the start of j of a max of one to the i j minus k right so with those like the uh the starting coordinates and the ending coordinates we can simply just uh populate the answer here so here again so we're using like a since we're using like a one based inj so when we populate the answers we have to do a zero-based uh conversion here right zero-based uh conversion here right zero-based uh conversion here right so we have a pre-sum of the what of the end i so and nj right so that's the uh the starting point and then we'll subtract the uh the pre-sum of the uh the pre-sum of the uh the pre-sum of the uh of the start right the start i minus one and then the end i sorry the nj also the pre-sum subtract the pre-sum also the pre-sum subtract the pre-sum also the pre-sum subtract the pre-sum of the end i and start j minus one okay and then in the end we simply add that double subtracted session back okay start i minus one and then start j minus one okay and then we just simply return the answer cool all right run the code okay accept it submit all right cool so it's success yeah i think that's it you know it's pretty it's a very straightforward like 2d prism a little bit of variations the only difference that you have to use this k to find how i mean to help us find the uh the range of the sum and after that it's just building this 2d pre-sum location and how 2d pre-sum location and how 2d pre-sum location and how can we use that to find the uh the sum of a splits of a specific range yeah and for the time space complexity right so the space complexity is m times n right that's a space and the time complexity is of course the time is also of m times in right this is pretty straightforward cool yeah i think that's it for this problem how to stop here okay thank you so much for you guys to watch this video stay tuned uh see you guys soon bye-bye
Matrix Block Sum
matrix-block-sum
Given a `m x n` matrix `mat` and an integer `k`, return _a matrix_ `answer` _where each_ `answer[i][j]` _is the sum of all elements_ `mat[r][c]` _for_: * `i - k <= r <= i + k,` * `j - k <= c <= j + k`, and * `(r, c)` is a valid position in the matrix. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 1 **Output:** \[\[12,21,16\],\[27,45,33\],\[24,39,28\]\] **Example 2:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 2 **Output:** \[\[45,45,45\],\[45,45,45\],\[45,45,45\]\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n, k <= 100` * `1 <= mat[i][j] <= 100`
null
null
Medium
null
1,176
and if it is a crime that is called the performance plan, this problem is simple, well, it is the level to solve it in the most appropriate way, a method called windows is still used, what this problem is about is an arrangement with the calories consumed by a person during each day, for example, taking this example, this person consumed on the first day one calorie, two calories, and on the fourth day four calories, and without a doubt a Kant value, this value here is a period of time, it is the number of days that this cycle will take. Let's say for example the example is not a day in the example two of those days etcetera and this will give us two values ​​that are and this will give us two values ​​that are and this will give us two values ​​that are called lower which is a threshold what they are giving a 3 hot value a lower suit and a work value What it is about is that we are going to be dividing the information into these periods, for example, if here it is worth 1, then the maximum is each period will be one day. If validated here, then we have to add two calories, so that's how it is and two days and if it were three then the first period is this the second period is this the third project is this and not like that then what it is about is that we count in each of the periods and this being said is very important Being they put each period in bold, it is not that, for example, if it costs, yes, if our period is worth two days, it is a period from 1 to 2, the other from 3 to 4 and the 5 nominated, it is not the first period, it is 12, the second period is 23 the third period is 34 then 45 and then that is the key to the problem outside of there the problem is very simple since we have the amount of calories stored per day we must simply evaluate these rules are very simple where if the caloric content is less than this threshold then we are going to lose a point and if it is greater we are going to gain a point and he wants it we have to return that amount of points that this person obtained in our days so good to do it then there are good windows and going through as if it were to treat a window that we are sliding I am going through the rule in this way adding and subtracting the extremes so as not to have to sweep each one is if we analyze like this we will have to sweep many times the algorithm sorry for the arrangement but by haiti pnh window methods we will simply be adding the new value and subtracting the value of the previous one not so first we are going to put our viable where we are going to return the result as always after it is probably called heat and green which is initially worth zero and then we are going to start integrating our arrangement for that to use two alert centers and the raids we are both going to start at zero and it makes it be while wright is less than or equal that is important that it is equal to heat and 2 and we are going to increase right then well at what moment we are going to go we are going to evaluate this to see if we add to subtract the points at the moment in which the distance between the iron is here then the condition test is going to be that yes r - l is equal here we are going to evaluate the r - l is equal here we are going to evaluate the r - l is equal here we are going to evaluate the points but then We are going to just count the calories here we are going to count the calories for example suppose we have this arrangement and it is 2 the first one the smokes are worth zero so brothers the and zero and here it is worth two so we continue adding we already have one calorie per day well The second one is still worth it, but r is already worth it's worth 1 so and so let's assume the heat and then the next one is worth this one, it's worth 2 l it's worth 0 so we're here and we evaluate the points and calories per day, it's more true less than the lower then we lose points if heat is losing it is more than operating we gain points and writing the important ones in the next iteration we have to remove the previous ball because it is lighting windows so gray color we are going to subtract l whatever we have in that increase in l we are going to add whatever we have right now in r and we are going to increase the if you notice it is only increased when we enter here because we move our windows and now what is going to happen final at the end the last arrangement this like we put that always when r is equal to heat and dot the cndh account here to evaluate is going to give us the points but if we don't put it here so that it stops this is going to give us a king index auto pound exception so yes you are equal to heat east lake we left here and I think this helped work and it works for a change because calories ah of course this doesn't even exist and it works this two they all work and they all work it's a more or less good answer they tell us it's the solution
Diet Plan Performance
design-a-leaderboard
A dieter consumes `calories[i]` calories on the `i`\-th day. Given an integer `k`, for **every** consecutive sequence of `k` days (`calories[i], calories[i+1], ..., calories[i+k-1]` for all `0 <= i <= n-k`), they look at _T_, the total calories consumed during that sequence of `k` days (`calories[i] + calories[i+1] + ... + calories[i+k-1]`): * If `T < lower`, they performed poorly on their diet and lose 1 point; * If `T > upper`, they performed well on their diet and gain 1 point; * Otherwise, they performed normally and there is no change in points. Initially, the dieter has zero points. Return the total number of points the dieter has after dieting for `calories.length` days. Note that the total points can be negative. **Example 1:** **Input:** calories = \[1,2,3,4,5\], k = 1, lower = 3, upper = 3 **Output:** 0 **Explanation**: Since k = 1, we consider each element of the array separately and compare it to lower and upper. calories\[0\] and calories\[1\] are less than lower so 2 points are lost. calories\[3\] and calories\[4\] are greater than upper so 2 points are gained. **Example 2:** **Input:** calories = \[3,2\], k = 2, lower = 0, upper = 1 **Output:** 1 **Explanation**: Since k = 2, we consider subarrays of length 2. calories\[0\] + calories\[1\] > upper so 1 point is gained. **Example 3:** **Input:** calories = \[6,5,0,0\], k = 2, lower = 1, upper = 5 **Output:** 0 **Explanation**: calories\[0\] + calories\[1\] > upper so 1 point is gained. lower <= calories\[1\] + calories\[2\] <= upper so no change in points. calories\[2\] + calories\[3\] < lower so 1 point is lost. **Constraints:** * `1 <= k <= calories.length <= 10^5` * `0 <= calories[i] <= 20000` * `0 <= lower <= upper`
What data structure can we use to keep the players' data? Keep a map (dictionary) of player scores. For each top(K) function call, find the maximum K scores and add them.
Hash Table,Design,Sorting
Medium
null
54
Hello everyone welcome back my channel is am sunny and i am software engineer today in this video we are going to solve another problem for our daily challenge series so today's problem is spiral matrix lead code 54 today in this video In this we will learn how to approach a problem, we will try to achieve its basic intuitive solution and in this we will also understand its time and space complexity. Okay, so let's look at the problem statement. Here is the life and macros. And the matrix returns which is D elements of D matrix in spiral order okay what it means is that a 2d matrix is ​​given means is that a 2d matrix is ​​given means is that a 2d matrix is ​​given where there are some interior values ​​and we have to where there are some interior values ​​and we have to where there are some interior values ​​and we have to print all these numbers in spiral order what is spiral order basically you start With d first element you drive towards left when you rich you d last element first ok give you dr give you left and again so basically spiral circle you can say right so to understand this let us look at example one Here we are given a 2d matrix, basically it is a matrix of three crossed three where 123456789 wait values ​​are given and 123456789 wait values ​​are given and 123456789 wait values ​​are given and basically we have to print all these values ​​in inner spiral order form so values ​​in inner spiral order form so values ​​in inner spiral order form so what happens is basically that date you have to print something. Like you want three six nine eight seven four five so what is happening is it is basically forming a leg spiral circle so to understand it in a more buttery way once we go to our iPad so like you are here You can see that here I have made a matrix which is a five cross four matrix, okay in this we have a value of 120, so what it is saying is that basically we will be given this matrix as input and basically we have to travel this matrix in such a way that We will print all these values in a spiral form or in a spiral order, so what is happening for this particular matrix is ​​our what is happening for this particular matrix is ​​our what is happening for this particular matrix is ​​our output is one basically one two three four five then we will do 10 15 29 17 16 and the rest is this thing which Left Right Top Dr is visible. I am telling you that basically when we are implementing the solution then we are going to definitely read all these things so I hope you have actually understood this problem. We are basically nothing in a spiral form. To print the values, basically write the numbers and ignore the rest of the things shown here for now, this is basically the part of the solution which I will tell you can write in the YouTube solution, so at that time you will have to do this solution and If ever in future you get this problem statement then you will be able to solve it easily. Okay, so the thing to understand here is basically the problem is right here, there is no algorithm based on it. If you look properly then this Simple, we have to do a driver cell technique through which we can print the data in this form and write it, so what to do for that, we have to see a simple observation, here you can see what we are doing. Bill always start with D first element right which is the left most value. If you travel right from here then when will be the spiral form. In the first row you will fabricate from left to right then instead of starting from D second row what will we do which is where and happened. On the first row, Dr will go from there, okay, from there Dr will go, then where we complete at the bottom, from there we will go left again, give right again to the bill, okay, then from here the order will repeat again that way from left to right. Give right tu bottom give bottom right tu bottom left give left tu ok now in this way basically here we are getting more and more, at this point you are understanding that we just have to follow a pattern where we To achieve a spiral form, right, so what I did for this is that generally you can take variable right because we basically have to track, we will do this with the driver, to achieve the spiral form, they can take help. Of four variables, one will be left, second will be right, top one will be bottom, okay left will be pointing to its left most element, right will be pointing to its right most element, okay top one will be pointing to the first row and The one at the bottom must be doing the last stop point. Okay, so what was our size from the bottom, right five cross four. How in this, so what will be our left here, that will be zero because that is the left most element. That is zero, then what will be your right, what will be the right, whatever be the number of columns - 1 If it whatever be the number of columns - 1 If it whatever be the number of columns - 1 If it is zero based indexing, right then for now I am four mother late, right would be four, it is okay because if this is zero based then zero. One, three, four, then your right variable will be four, okay, then what will be our top will also be our zero, okay, what will be the bottom, number of rules is five, meaning index will be 4, so according to that, the value of left will be zero, the value of right will be There will be four because zero one to three four is ok and the value of top will be zero and the value of bottom will be zero one to three so this we will make three ok so this will be the initial configuration ok now what to do, just here is a simple logic. That whenever you are traveling late, they start with left, right, so here what we are doing is, when they start with left, we will drive the entire row till what till right, so basically we have become a driver once. So we have to update this variable in a way so that we know which row or which value we have already printed, so whenever we start from left, we start from right, we start from first row. From late we did 1 2 3 4 5 left then right we put a loop on one left then right we did driver and next what we have to do is to print this last pen top then bottom right so what can we do for that simply We know that we have completed this row, so who was pointing to this row, who was topping, right, Vanshiyu and Dan with D first row, what can we do, we can increment this top painter, they can become top. You are the next row right, so what will happen to us after first determination, the value of our top is updated, it is bill start pitting, you are the next row, okay, so now our top is pointing to this row, okay now we know. That is, they are already coming right, which means we are left and right, we have traveled, the next direction is ours, top and bottom right here, if you see, I have made a matrix of one direction, where zero is where these ISPs come. One more variable will have to be taken, direction variable which will be zero, one to three values, which means if it is zero, then you will go left, you will go right, if one, then you are top, you are bottom, then you are right, then you are left, and if three, then you are bottom, up, then right now we are ours. The first direction which started was from zero, we have done left and right, now next we will do one top and bottom driver, right then we will do this top and bottom travis, then we will get the volume of the pen, right so what can we do? We can simply set up a follow up where we will travel from top to bottom. Where the right pen is pointing to which the pen is pointing, it is right from the bill, so we can write something like this, matrix of right = right of ours, we will matrix of right = right of ours, we will matrix of right = right of ours, we will remain like this constant and the bill that has come to us will move, you are top, you are bottom. Okay, we will understand this code when we see it but for now let us understand that we only have to do this top two bottom driver. Next so once you do top two bottom drivers then what you can do. Now you know that You have also successfully locked this pen, that is, after printing it, you will decrement your write variable, so the date, which will be your write value in the next iteration, will be pointing to it, okay because we know that we have already done the driver. If so, you will update the right, bill is simply decrement, ok, similar, now the next direction will be right, you left, we will right, you left, the driver will right, to whom is our right pointing, this pen is pointing and let us know. How right you left then it will point in this direction and our bottom row which is basically the date bill remains constant so here again what can we write this to the matrix that our bottom row will remain constant but ours here I move from right, you go left, right is pointing my pen, from here till here we will go right, so this is also simple, this has to be written as normal follow up, you will understand this from the code, so I am visible in the code also but For now, I hope you have understood that once you leave the driver, then how will we know that this row has also been printed, so now what will we do, we will also update the value of the bottom, so the next one will be in the address. Bottom bill point tu de previous light you have to decrement you have to right because the bottom will go upwards so now this bottom is pointing to this row okay so again bill do d se think once you are here Meaning, now you have to go to the bottom, now where is our bottom is this one and top is this one, you are pitting this one, so basically we have to go from 11 to 6, right, so now what will we do with our when loop will run, it will give this value. Will print this value and once this value is printed, it means that this is also completed, so whenever your row is getting completed, which one will you update, right variable to left, bill get updated, next column, right. So what is happening with this, now it is pointing this pen, okay so I hope you understand, according to whatever I am doing with the row or pen driver, we are updating the left right top bottom. So that cry or pen does not get printed again, right, now our left is finding it, right is pointing to this, bottom is top, right is next, once 0 1 2 3 our donation is done, then we If we go back to 0 then it means we have to do left then right and what is left then right? Left is pointing to this, right then we will travel from here to here. Right then according to this when you do private People will have to write where the top will be constant which is this D roll number and your pen which is this I which goes from left to right date mains 729 so now we will print this also so once you have printed this then what will be the update for you. What has to be done is that now this top has become top bill and after updating it, you will point to the next one, then top is also now pointing to this, okay now what to do, we know that our donation has been done, okay they know. That this 789 has also been donated, now we have to do 14 bins right and our top has already been updated and is here, which is doing this line and this row for days right, so now what is our next direction, top and bottom? First, top and bottom will come, our top is pointing to whom, it is pointing to this row and the bottom is also pointing to this, so when you run our only one fruit look, what will happen now our top and bottom will be printed right top. It is pointing to this row, the bottom is also pointing to this row, it means only this value will be printed on your right, because you are going from top to bottom, then this value is also printed. As soon as this value is printed, you will print it on the right. By updating the dog, by updating the right, what will happen because this is our particular pen, then it will become Dr. Right, if this is donated, then the right bill gets updated, then the right is updated, next it will be doing one, the next pen will be fine, so now. What will happen now, our right one is pointing to this, okay, what is the next direction, right, then left, now then left, right, then left, now right is pointing to this, left is pointing to this, so we have to go, right, then left, this is 13 and 12. When you are done, now you will write a loop on the next joe where your roll number is bill remains constant bottom, this top can be taken by anyone but here what is there, you have to go right, you have to go left, between 13 and 12 so in this iteration your joe is Follow up will be that it will print 13 and 12 and accordingly you bill update. Once this is done then you can push your variables according i.e. you can push your variables according i.e. you can push your variables according i.e. you can update then what will be the termination condition until your top piece is equal to bottom. This entire iteration will run until it crosses the top and bottom so I hope it is clear to you, this is getting a little complicated but if you are driving it yourself then thanks Bill Wickham More Clear Okay so basic The idea is the same that you travel, you just have to update which row of cup n track according to that, then update your left right top bottom, then this is the first row from the slide, you printed it and then you did the last one. I did the pen, then did the last row, then again pen, so I hope the idea is clear to you, it might be a little complicated right now, but if you watch this video again and try to do a gradient, these variables It will be clear to you and when I show the code, other things will also become clear, so it is simple, we are not doing anything in this, we are basically tracking whatever opinion pen we are printing using these variables right left top. Dr. Okay, you normally update it, so we should not print that row or pen again. Okay, so let's look at the code once so that it seems a little simple to you. When you look at the code, once we Let's go to the Lit-Code website, once we Let's go to the Lit-Code website, once we Let's go to the Lit-Code website, so this is our code, you can see here, by ordering a spiral, there is a method which is taking an input parameter, basically you are doing a, here I have taken out the hairs of the row and the pen. Okay, then what am I doing? As we saw on the iPad, you have to take variables from top, bottom, left, right, so this is basically initialized to zero, bottom to row - 1, left to zero bottom to row - 1, left to zero bottom to row - 1, left to zero and right to pen minus one. So today they know this is zero based indexing so we will have to do -1. Okay, so the next thing here is so we will have to do -1. Okay, so the next thing here is so we will have to do -1. Okay, so the next thing here is we have to take the wait list because we are not printing here, we basically have to return the elements in this spiral order. Okay, so this is the string D result on this and give a direction variable, I have taken zero, so I had shown on the right type that we are basically 0123 direction, so let me show once more that if you look at it on iPad, then this matrix here. Zero means left, right one means top, bottom means right, left three means bottom, we will follow this in the code also, so if you see the code yourself, what to do here, write your code. Take Antil Topi, equal to bottom and left, take this, equal to right, I gas, this second condition is not important, try it once, apart from this, I gas will also work, so here, as I had shown, the direction is taken on the iPad, the initial direction. It will be zero, okay and if our Wiley loop runs then how long will the loop run till the time your hat is equal to bottom and left is equal to right so our first check will be basically if direction is zero then where will we go left you Right right was shown in one go. Done zero meant that we have left then right, so in the code also we will go left then right and whatever value we get, we will store it in our result and oh. Okay, so what happens here. Your row number will remain constant. Right, this is how our top was which was denoting the first row right, then that will be our constant. Rest I will move from left to right. Okay, so what will happen to this, first tu's head elements. You store people and what will you do after that once that row has done its travels, you simply increment the dog so date it points you d next row is ok and it will not go to LCM so at a time only one block will be executed then next Which direction will be basically you bill just add up one tu date direction so date zero plus one becomes one and more mode 4q date this late your matrix is ​​very big okay and your matrix is ​​very big okay and your matrix is ​​very big okay and your which direction is every time you have tu en revolve around 0 1 2 3 Right, directions can be done only by you, right, so be the bill, you cup track of date, so this is the method, you just do an increment plus one and give you modified by four because only then that will be your conference in zero one two three, right So if the direction of the date on this is not more than the tax, then now the next direction you will get will be equal to one. Right, if your direction = 1, then like I your direction = 1, then like I your direction = 1, then like I showed on iPad, moving from top to bottom is fine, then on this How come, basically the row number which is yours will go from top to bottom and the pen which is your date bill remains constant which is your right point, the right variable is pointing right, so once this is completed follow the steps. That your last pen is 'Date Bill Get steps. That your last pen is 'Date Bill Get steps. That your last pen is 'Date Bill Get Stored' is fine and once that pen is Stored' is fine and once that pen is Stored' is fine and once that pen is executed then it is simply update this pen write minus decrement because you write this basically D last pen write then you decrement it dog is fine. When your direction is 'Tu' is fine. When your direction is 'Tu' is fine. When your direction is 'Tu' then I had shown in 'Direction Tu' that you need to move from then I had shown in 'Direction Tu' that you need to move from then I had shown in 'Direction Tu' that you need to move from right to left, it is okay, what will happen in this way, you simply go private from right to left, you store all the values and then your bottom is basically bottom is what bottom is d last so let's understand it once more look at the iPad start with d first row ok give last pen give last row first pen write again you start with d second row second last pen second Last row and give D second pen right then it will go right in this way what is the meaning of direction tu left then right tu left you travel you basically bottom which is value bottom which is variable so what will it do it will update you You will have to do once your donation with D last row is okay same direction when three will be you just need you driver from bottom to top right which is D first column and first column is bin pointed by left variable so you have to increment that so I hope It is clear, you try this code to map what I told in the demo and do one more droid by yourself, you will find it very easy, there is nothing complicated, just you have to understand this code, basically in your mind, you have to do which variable. What is the significance and you should be able to write your own. Okay, so I hope you have understood. Now let us see a little time complexity here. Time complexity is nothing for us. This iteration of yours will execute only one block. Write your own. The look that will happen will run only once, so in this if you see they are on the silly driver H element like your matrix is ​​macros n give time matrix is ​​macros n give time matrix is ​​macros n give time complexity you are order of max n only okay because you are only traversing each value once. Yes, it's ok and space complexity is also constant because we are not adding any extra space for such solution, only so list they are using string D result, so it will not be considered by ISP in complexity so I hope you have understood and or n The next video will be a variant of this, we will see it, so before date you have you need to understand this problem a little better so that you can understand the next video, then I would suggest that you drive it a little more, if you do not understand then this Watch the video again you bill get you understand ok so that's all the dates for today which is about this video I hope you will get some new learning today and see you again in some next video if you liked this video then please like this video Like it and share it with your friends and if you have any doubt then please comment, ok then let's meet in the next video, thank you for watching.
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
35
hello everyone welcome back here is vanamsen uh with another interesting coding problem today we will crack the search and search position Challenge and we will be doing it in JavaScript uh so let's get started all right so before we start coding and implementing our strategy let's understand the problem we are given a sorted array of distinct integer and Target value and our task is to return the index if the target is found and if not we return the index where it would be if it were inserted in order and to make it more challenging our solution should be a runtime complexity of all log n so all again The Sweet Spot this mean we need to Leverage The Power of binary search because we have information that our array is already sorted so we are going to start by defining our function so it's predefined a search insert it accepts an array of number and a target number and next we set our pointer so left and right and the start a and the end of the array so they will help us slice our search space in half in each iteration so that's why log n so now it comes the while loop and the core of our binary Series so uh in while loop we will calculate the mid index and then check a free possible uh statements if the target is at the mid we found our mid position if it's greater or if it's smaller so let me implement it and I will explain everything right away so left will be zero right will be num left so ending position -1 and while loop left -1 and while loop left -1 and while loop left is less than right and let middle be math lore between left plus right divided by two so middle element and if equals Target we return middle position else if Nam meet less than Target so Target is greater so then left will be mid plus one narrowing space and else it's opposite so right will be mid minus one and finally we return the left position okay so let's run it to see if it's working or a given test case uh so yeah everything's work perfect so notice how we are changing our left and right pointer base on the comparison with the target so this is the Crux of the binary search algorithm so uh yeah we're moving to Mid plus 1 or mid minus one depending uh and uh also it's left or right uh pointer so finally uh if we exit the loop it means the target is not in the array because we didn't return mid point so but remember we don't return -1 so we return the left pointer return -1 so we return the left pointer return -1 so we return the left pointer indicating there uh where the target would fit in the sources array so uh there we have it now let's test this function and see how it works for unsynthesis cases as well so I'm running hit first run for this JavaScript code and yep we beat 51 with respect to runtime and also 50 with respect to memory so all good and our function works like charm I hope this tutorial was clear and you have learned something new today and remember coding is all about practice so don't just avoid the video code along and after you are done play around with the code understand it challenge it and prove it so and that's it for today's session if you found this video helpful smash the like button and share it with your follow coders friends also don't forget to subscribe and ring the bell so you don't miss out on our future coding adventure and tutorials until next time keep learning and happy coding
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
307
all right let's follow the range some query immutable so you are given the array numbers and you have to handle the multiple queries of the following type so you either update it and you either calculate the sum between the range based on the left and right and then there are three functions you need to write so one is what constructor the other one is update i mean and the last one is some range right so just reopen it and then if you just create an array something like this like if you say in array sound and then you basically use a prefix sound to actually do this is fine but the problem is the constraint is what is too complex and then you will not be able to solve it and then you'll get your e right away so again go on a gift for ditch so there's a segment three idea so in this idea it's pretty simple you will definitely need to know this is an array right so i build a tree based on my in array and then for the parent is actually the sum of the children so one plus three is actually equal to four and this is for zero and one index and this is a value five so four plus five equal to nine this is between zero to zero and two index and then so on right so you'll definitely know the idea so uh you basically need to create a tree node right true enough class and then you will need to have what the sum for the variable and then the left and right for the range and also the pointer uh we pull on point your children right so i'm going to say class trino and i need to say any sound in that circle some left and then right uh in this case i'm not going to use left and right because i will say my pointer three no left and right here so this will be what starting and ending starting this and ending next okay this is much more easier for you to read it so for every single time when i can solve a tree nor i will assign an index and then the index is going to be based on uh based on my value right that's my input if i assign the index if i assign an index in the date right this is going to be zero so i will assign star equal to zero and then if i assign a link that's right over here this is gonna be zero and two so this is based on my uh just based on my function oh how hard i assign right so is a star stop store it's actually going to start and then these are any google end all right the trigger is pretty simple and i just have to create a three note root and then i need to just assign the root equal to what the pure tree i need to pass in the what uh i need to pass in passing my norms and passing my index there so index is based on zero to one number length minus time all right so again uh you need a helper function called beauty and then the type is trino right so if the star is what is greater than n you just it's pretty return known this is not doable right all right so uh back to the normal case i need to create a tree node if i create a if i want to create in the tree right so actually no you know equal to nu3 you know and the range is starting n i don't care which one is which one i am assigning because i when i'm passing the value between zero five right zero five with the uh with the in array i need to know this is definitely a range between zero five so i will assign it right away the problem is i need to assign what i need to assign the sum later right i need to calculate all of the possible value all the way to the bottom and then recursive recursively going back i need to say i need to find out what is my chosen value and if i know my christian value i will know i will be able to know my parent value right so i will just keep updating my uh the song for the three notes when i call it back so what if is the root uh if the stop sorry if the star is actually put in which is the leaf right i would just assign you know the sum equal to uh nonsense star and then i will just return again else right so if i have the array like really long so when i assign the first if statement this is the base case uh sorry this is the leaf case so what happens if the tree knows not the leaf right so i need to say equal to one star plus n minus star divided by two so this is a happy you need to uh you need to have it right when you're doing the binary search uh you would be able to know this should be uh this should be avoid the uh stack overflow and something else like if the value is negative then you will get a wrong answer for sure and i know the tree doesn't have the negative value because i assign a zero to the positive number so what if the value is negative a different question right you will definitely want to avoid this stack overflow or all of index uh stuff so you just keep the happy habit right over here and then i need to assign my left based on my index so i'm going to say field tree right here tree and this person announced i need to pass in the star i need to pass in the mid only and then know that right it's going to be about 3 again that's enough plus a mid plus one causing the approximation right so the reason why i use plus mid plus one this is because i want to assign my next value the next value after the mid to the right side and then the mid should be on my left all right so at the end now i know this is not the least so i need to say another sum to the left or something plus another record and then i would return no right okay if you return null over here and then return over here you can probably return no over here right all right so this is pretty much the built-in idea using a recursion solution built-in idea using a recursion solution built-in idea using a recursion solution so this is pretty much like merge sort right but think about this like they are probably similar but not exact exactly the same and a full update right for the update it's easier than some range be honest so i'm still going to what i'm still going to uh ask a helper function this is because i need to pass in the tree no root and then i need to what i need to call the helper function all right so for the update if the tree trinom is actually equal to the leaf right left ruler sorry rudolph star is actually going to end this is the leaf right so i will just update mine about so now all right so this is index right again i just want to point out again this is what zero this is one this is two so when i say root of left equal to root right uh root of star equal to root of n sorry root of star equal to root.n root of star equal to root.n root of star equal to root.n i know this is a leaf and i need to update this to what to probably 20 something and then when i uh recursively going back to the top i need to update my parent this should be 24 right and then it should be what 51 all right so this is it right i don't have to change the index uh the index is still two but i need to change the value right for the tree node and then this is it right so again uh if you want to find out uh the index you are looking for the tree so from the top right from the top you need to know you either going left or you either going right this will help you to save a lot of time using log band solution without traversing from the left to right this is all of them if you're using logan right this is much more efficient so i will be able to know if my min is actually equal to the root of star plus so again for every single note i feel in the build tree function i already assign my what my start and then my end right and this is it right so let me come back here so now i need to know if the index is less than equal to a min this is on the left side right so i will say update with the left comma again for the right index well okay there is something wrong update router right in this valve then i need to update my what my sum right so root of sum is actually equal to the left sound so this is it and then i need to write my sum range function so subprint function is pretty much the same i need to pass in the root i need the person left i need the customer right all right so uh where uh what else so i need to create a helper function for the ins right and if this is the case i'm going to return right in some range between all right so let me scroll down a little bit all right so if i know the sum range all right i'm going to just give you them just give an example if i want to know what is the range between 0 2 i will just go on my left and i know this is my value i'm sorry this is my range for the value right so i will return nine right away and this is easy and for more simple one just go on the leaf so i want to say i want to know the what is the value between two and then you will say okay this is uh this is fine this is easy as well then what happens if you want to find out what the value between two four so what does twofold so the two four is actually this is index two this is index three this is index four right i want to know the value the sum for these three values but this is a tree right and then for every single tree you know the range for zero two and then you need to what you need to get rid of this so you want to say i only want this and then when you traversing to the top right you need to what you need to avoid others index value right and here we go so let me stop coding so again uh for the best case if a star is actually to the left and also right uh sorry people who write then your return is and what else nothing else so i can say what i can i have to find out the midpoint if i want to know which side of the tree i'm looking at it's either left or either right so i'm saying equal one without star plus so if i know the index and there are four different scenarios right this is me so what so that's the first scenario if the left is right over here this is another one if the right is right over here this is the third one if the right is right over here this is the fourth one right so i will be able to know which one i should be able to find so uh for the right which is less than equal to for the right which is less angle to the mid this one is referring to what this one right so this is on the left side of the tree so i will say go back again if the left is greater than the min which is this one right then this is when going right all right so these are supposed to be what these are supposed to be the base case so imagine here so this is zero five right and then you want to find out zero one and then one is less than one uh less than a minute the main is what five divided by two which is two so you will know the entire searching is on my left side and exactly going to be a similar stuff for the right if the min is less than l the entire thing is going on my right and this is easy but what if you want to say you want to find out the range between um sorry the range between two four right this is hard so you want to know what is the range between here and again you need to you only need to go up two and then three four in the in this side of the tree right so for the two on the left side for the three and four index on the right side only right so uh from here i need to say if the right is less simple to the mid this is easy just go on and from my left and this is left hand right and then again else if the left is what greater than mean this is on my right side all right so everything else should be hard right should be hard and i will have to say return some range i was just looking for the value itself so look at that left comma me plus some range right let me plus one comma and then it should be n right and then the n should be right if i am correct right and then this is going to be pretty much it right so hopefully i don't make a mistake but this is supposed to be the solution all right i pass the test again so let's talk about the timing space all right full of photo full of space for the space is really uh really simple so you are building a tree right so this is so tricky and then the represent the length of the array so this is what one two three four five six and then how many know you have one two three four five six seven eight nine ten eleven right so i mean again this is gonna be based on how you build a tree be honest you probably will build a binary for tree or a balance tree right it doesn't matter depending on how you build it right so again i was i will not say this is supposed to be a complex solution for the space i would say it's all of them represent them then of the array and then the time for the bill tree i would say it's all the fun right even though that you have a parent and then you're just constructing the sum of the value between your left and right but it doesn't matter i'm going to set all of them for the time for the build tree and for the update this is going to be logged in right you cut into the half every single time using the mid and this is the open and then for the sum range this is going to be logan for the time right you don't allocate any space in this two function so this is a solution and i know this is kind of long and this question is supposed to be difficult and i will see you next time so if you feel this is helpful subscribe like and i will 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
1,833
just completed this challenge it is passing with very good performance the challenge is Lee code 1833 maximum ice cream bars this is a labeled medium question I don't think that's appropriate I think this is an easy question I solved it very quickly just like less than five minutes and here's how easy it is I'm going to show you how easy it is so if you feel dumb now and you can't solve it you probably won't feel dumb after you've learned how to do it because you'll see you just missed something easy it is a sweltering summer day and a boy wants to buy some ice cream bars at the store there are n ice cream bars you're given an array costs of length n okay there's no end property on this array this is just dumb description here where costs I is the price of the ice cream bar and coins the boy initially has coins to spend and he wants to buy as many ice cream bars as possible return the maximum number of ice cream bars the boy can buy with coins so each ice cream bar has a cost and this is how many coins it costs first one costs one three two four and one coins respectively the boy has seven coins how many coins or how many ice cream bars can he buy with those coins well if you start that he goes one three and two that would be six and then he would get to four and then we'd be all done but then he could have bought this one over here uh so obviously the easiest way to solve this problem at least obvious to me is we want to buy the cheapest ice cream bars first I mean just from a logical consumer perspective would you rather buy something that costs more or you're going to run out of money or would you rather buy something that's cheaper and you can have more money to either save or buy more ice cream bars or whatever it is that you're buying in this case ice cream bars so we're going to sort the input array obviously and to do that um well we're going to create a un32 array and we're going to sort it we could use a sort function but I'm using the uh typed arrays which has the built-in typed arrays which has the built-in typed arrays which has the built-in numeric sort functions you don't need a sort function I don't know which is faster but uh probably this one because I'm basically kicking everybody else's ass on performance on this lead code example and that's nothing really to brag about because it's such an easy question that it's not that big of a deal so we start out we sort the array we create declare the bars to be zero there has been no bars purchased uh we create a for Loop for price of prices and we see if the price is greater than the coins like let's say the price is five and we only have four coins then we're done we break and then we return the number of bars however if we continue then we subtract the price from the number of coins the boy has we subtract price from coins and then we increase the number of bars that is the transaction and it could have written a function perform transaction but it's so trivial in two lines of code that I figured it was just fine to leave it like that could have created an identifier um you know is unaffordable right but that's how it is that's as simple as that and this is the performance I got on it as you saw in the beginning and we'll go back to uh here 98.33 on speed and 100 on memory 98.33 on speed and 100 on memory 98.33 on speed and 100 on memory performance kicking all the other JavaScript Solutions ass and like I said it's an easy question I mean we got this in like 10 lines of code including the curly braces it's nothing I don't know why they labeled it medium I think leak code is getting soft as they add more and more questions this is an easy question um if it helps somebody great I'm sure there's somebody out there who doesn't know how to do this so don't feel dumb if you didn't know how to do it uh instead now you know how to do it's not that hard right all right
Maximum Ice Cream Bars
find-the-highest-altitude
It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible. **Note:** The boy can buy the ice cream bars in any order. Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._ You must solve the problem by counting sort. **Example 1:** **Input:** costs = \[1,3,2,4,1\], coins = 7 **Output:** 4 **Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7. **Example 2:** **Input:** costs = \[10,6,8,7,7,8\], coins = 5 **Output:** 0 **Explanation:** The boy cannot afford any of the ice cream bars. **Example 3:** **Input:** costs = \[1,6,3,1,2,5\], coins = 20 **Output:** 6 **Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18. **Constraints:** * `costs.length == n` * `1 <= n <= 105` * `1 <= costs[i] <= 105` * `1 <= coins <= 108`
Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array
Array,Prefix Sum
Easy
null
796
on everyone so today we're looking at lead code number 796 it is a question called rotate string and so here we're giving two strings a and b and we want to see if we rotate if string b is a rotation of string a so here we have input a b c d e and we can see string b is c d e a b but if we start here at this index 3 we can see that a b c d e is in fact a rotated version of a okay here in example 2 we don't have a rotation we have a b c d e and we have a b c e d so that's going to return false a and b will have a length at most of 100 okay so there is two ways we can go about this there is an intuitive approach that's more of a brute force way of solving this and there is a trick way of doing this that's much more efficient so we'll go over both ways to kind of look at this in the conceptual so if we do the brute force how would we go about this okay we have a b c d e and then c d e a b well one way we could do this is let's say we have an i pointer here and we have a j pointer over here okay and we iterate the j index until we have a match at i and j okay so j will come over here and then we can use the modulo operator to go and get all the strings of starting at j at the length of this string right over here so the length of this is one two three four five we can take we can create a new substring that's going to be a we'll increment j this will be b we'll use the mod operator so j will come back to c j will come to d and j will come to e and then we can check are these two strings equal okay so that's one way we could do it the only problem is that would be very expensive time wise because technically there could be a match at every single one of these strings and then we have to do a whole iteration to find the substring on each one of those so our worst case time complexity would be o of n squared for this particular solution okay and then our space complexity is also going to it's going to be o of n because we're going to have to create a new string actually it would be o of n squared because technically we would have to create a new string on each one of these matches so our space complexity would be of n squared so it's not good but it works and it's the intuitive way to kind of think about this problem now we can come up with a more efficient way of doing this let's take a look at that okay and this is kind of using a trick and it's good to kind of just think about this if you just think about this a little bit deeper you can probably understand that this is one way of doing this that might make more sense so let's say we have this input string right here abcde and we concatenate it so we just create a double version of this a b input string a and stick it together so for example we would have a b c d e plus a b c d e okay so now we have created a double version of our a string we've basically done a plus a is going to equal a okay and so now we can see that no matter what the rotation is going to be of string b here it's going to be in string a at some point okay so here we have c d e a b we can see that it is right here c d e a b i'll use a different color here it is a match right there okay and that's just a linear time operation we can do we can use a javascript um includes method that does this for us that abstracts out any coding we can just do this with a one line shot but if you want to do it by hand you can use a sliding window approach to kind of find this substring in a linear way so using this strategy what would be our time and space complexity well our time complexity would be linear because we're going to have to do one scan through the array and we're going to also have to create this substring or not the substring but this double string here and that's going to also be a linear operation so our time complexity here is going to be o of n and what about space well we do have to create new space relative to the size of the a input so our space complexity is also going to be of n which is pretty good which is not bad okay so let's jump in the code i'm not going to do the brute force solution we'll just do this more efficient solution here and so first thing we want to do is we just want to check their base case is uh if a dot length does not equal b dot length we want to return false okay and if a dot length if they're both empty strings um equals 0 and b dot length equals zero so if both the strings are empty we want to return true okay and now all we have to do is uh concat a so a is going to equal a plus a and now we just return a dot includes b okay so let's go ahead and run this and we're good okay so very easy to solve if we kind of know this trick and it's not too hard to come up with it if we just kind of slow down look at these two strings write it out you could probably come up with this in an interview but if you are familiar with this it'll definitely you'll definitely remember it okay so that is lead code number 796 rotate string i hope you enjoyed it and i will see you all on the next one
Rotate String
reaching-points
Given two strings `s` and `goal`, return `true` _if and only if_ `s` _can become_ `goal` _after some number of **shifts** on_ `s`. A **shift** on `s` consists of moving the leftmost character of `s` to the rightmost position. * For example, if `s = "abcde "`, then it will be `"bcdea "` after one shift. **Example 1:** **Input:** s = "abcde", goal = "cdeab" **Output:** true **Example 2:** **Input:** s = "abcde", goal = "abced" **Output:** false **Constraints:** * `1 <= s.length, goal.length <= 100` * `s` and `goal` consist of lowercase English letters.
null
Math
Hard
null
122
one welcome to my channel so before starting this video um i would really appreciate if you can help subscribe this channel to help me grow and then let's get started so um for this video i'm going to cover two things the first one is um the solution uh for this specific question and the second one is how we are going to behave in a real inter in a real code interview so let's get started so remember in the real quick interview the first step is always try to understand the question if there is anything unclear please ask some questions to the interviewer so don't be shy and also at the same time think about some ash cases so let's uh resolve this problem you're given an array prices for which the ice element is the price of a given stock on the i so find the maximum profit you can achieve you may complete as many transactions as you can so you may als you may not engage in multiple transactions simultaneously which means you must sell the stock before you buy the game so this means you cannot hold more than one stock on the same day so let's see for the first example we have this array which each of the number represents the stock price on the corresponding day and the maximum profit we could get by achieving multiple transactions is seven so this is an explanation um let's see the constraints so the constraint says that the prices uh array input array is not going to be empty it's between 1 to 30 k so each of the prices between 0 to 10k so the next step is about finding solution in this part you're going to think about the solution discuss the idea with your interviewer and also do some run time space analysis to help you understand whether the current solution is the best after you get an agreement with your interviewer you can start to do some coding work and in the coding part uh take care about the correctness the speed and also the readability so let's go through this piece of code together so if um the price is important its lens is smaller than two that means we cannot achieve any uh profit so we are just going to return zero otherwise we are just going to apply a greedy strategy so we have the initialize the total profit at zero which is going to be returned finally and for each of the day if the previous day has a smaller price then we are going to uh just uh plus the day for the price to the total profit otherwise if the current day has a smaller price than the previous day then we are just going to continue and finally we just going to return the total profit the runtime is going to be 11 and is a length of the input array and remember after you're done with coding always remember to do some testing if it's a runnable platform feel free to set up some test cases run through it um otherwise you will need to go through some simple uh examples uh and explain how this piece of code is gonna work manually and at the same time do some sanity check fix some bugs that could potentially affect the correctness of the code so that's it for this uh this video if you like it please help us help subscribe this channel i'll see you next time thanks for watching
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day. On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**. Find and return _the **maximum** profit you can achieve_. **Example 1:** **Input:** prices = \[7,1,5,3,6,4\] **Output:** 7 **Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. **Constraints:** * `1 <= prices.length <= 3 * 104` * `0 <= prices[i] <= 104`
null
Array,Dynamic Programming,Greedy
Medium
121,123,188,309,714
1,583
when I was in college I was really struggling with programming I tried code forces code shift and even that tracking the coding interview I never felt ready for interviews I knew I needed to get better but I didn't know how that all changed in 2017 when I came across lead code I instantly fell in love with its clean and user friendly interface and more importantly the problems were actually relevant to the real world interviews it not only had me improve my coding and problem solving abilities but also let me create voting interviews at Big tech companies like Amazon Google and Microsoft in the past previous I have worked for more than 1500 lead code problems mainly because I didn't have anything else to do and I felt really excited whenever my Solutions were accepted even for the easy problems I thought more problems I saw the better are my chances of cracking interviews however that was Far From Reality you don't need to solve these many problems in this video I will talk about three mistakes I made and the lessons I learned so that you don't fall into the same traps and increase your chances of cracking these interviews my first mistake not understanding fundamentals for some of the topics I directly jump into solving problems without understanding how it works this is a big mistake before you dive into lead code make sure you have a basic understanding of fundamental data structures and algorithms for example you know how to implement basic binary substitute algorithms like search insert and delete before tackling any problems related to it without that Foundation is like trying to build a bridge on a river of clouds make sure you are good with basic data structures like arrays linked lists Stacks queues hashmaps binary trees priority Kings grabs and new algorithms like sorting binary research 3D algorithm recursion dynamic programming DFS and BFF you don't need to study any advanced data structures in the beginning for two reasons first they will eat a lot of your time and second they rarely ask in the interview you can use websites like Geeks for gigs or watch tutorials on YouTube to learn basic fundamentals you will find links to my favorite resources below so how many problems to solve lead code problems come in three flavors easy medium and hard some folks say you only need to solve 75 or 100 problems but honestly it depends on your coding experience but in general I would say around 300 high quality problems is a good number if you are a newbie like I was in the beginning you need to solve more problems if you are new to a topic start with easy problems and gradually move towards medium and hard problems it's like learning to walk before you run here is my secret sauce out of all the problems you solve make it 50 medium 30 percent easy and 20 hard if your salt and time when looking for a curated distort problems I highly recommend solving lead code top interview questions and 100 most liked questions so how to go about solving a problem first try to understand the problem write it on a paper visualize it in your head run through few input and output examples think and write your Solution on paper after you think your solution will work run it on lead code and compare your performance with others follow good coding practices believe me naming a variable I during your interview is not going to win you any points on the contrary it can actually harm you if you don't follow good recording practices during the interview don't display bit too much time on a single problem if you're unable to solve the problem within an hour then look at the hints and the solutions go to the discuss section and see like what other solution people have posted this brings me to the second mistake that I made not utilizing lead for discus section in the initial days after solving a problem I moved on to the next one hoping that I have submitted an optimal solution and it's good enough for interviews but that was a huge mistake after you tackle a problem read the official need code solution go to the discuss section and try to understand top ported Solutions you can even contribute your own solution if you think your solution is unique stay organized if you really want to get the most out of lead code is staying organized this key for that I recommend developing the system When I Was preparing for interviews I utilized notion to create a list of problems with their links difficulty levels status and notes if I couldn't solve a problem in one attempt I would change the status to revise so that I can come back to it later I also linked all the useful articles from the lead code discuss section on the page along with my personal notes I have provided a notion template Below in the description which I use during my own preparation feel free to duplicate it and add your own problems according to your needs so now let me talk about the last mistake that I made not doing lead quote contest for the first periods I ignored lead code contest and only focused on solving problems whenever I felt like it but it was a bad idea and after realizing it I started doing contests regularly during my preparation I strongly advise participating in lead code contest and also virtual contest if you happen to miss any because it helps you practice in a timed environment after you have solved enough problem and gain confidence start timing yourself during your practice sessions this will help you maintain focus and prepare you under time constant which is how the actual interview happens so are you prepared how can you tell if you are ready for the interview if you can consistently solve lead code medium problems within 25 minutes and 3 out of 4 problems in the lead code contest you are in a good spot for most coding interviews remember it's not about how many problems you solve it's about how good you are at solving any new problem that's why lead code contests are very useful because they help you evaluate where you are in your interview preparation Journey do you need any other platform apart from lead code for practicing questions in my experience the answer is no and don't trust to get lead code premium they start with 200 to 300 problems and then decide if you really need it one good use of rate code premium is when you want to solve company-wise problem but want to solve company-wise problem but want to solve company-wise problem but that is not needed in the beginning I hope it was useful you can find all the links Below in the description if you have any questions or you want me to make a list of my favorite lead code problems let me know in the comment section have you say good luck for your interviews bye
Count Unhappy Friends
paint-house-iii
You are given a list of `preferences` for `n` friends, where `n` is always **even**. For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from `0` to `n-1`. All the friends are divided into pairs. The pairings are given in a list `pairs`, where `pairs[i] = [xi, yi]` denotes `xi` is paired with `yi` and `yi` is paired with `xi`. However, this pairing may cause some of the friends to be unhappy. A friend `x` is unhappy if `x` is paired with `y` and there exists a friend `u` who is paired with `v` but: * `x` prefers `u` over `y`, and * `u` prefers `x` over `v`. Return _the number of unhappy friends_. **Example 1:** **Input:** n = 4, preferences = \[\[1, 2, 3\], \[3, 2, 0\], \[3, 1, 0\], \[1, 2, 0\]\], pairs = \[\[0, 1\], \[2, 3\]\] **Output:** 2 **Explanation:** Friend 1 is unhappy because: - 1 is paired with 0 but prefers 3 over 0, and - 3 prefers 1 over 2. Friend 3 is unhappy because: - 3 is paired with 2 but prefers 1 over 2, and - 1 prefers 3 over 0. Friends 0 and 2 are happy. **Example 2:** **Input:** n = 2, preferences = \[\[1\], \[0\]\], pairs = \[\[1, 0\]\] **Output:** 0 **Explanation:** Both friends 0 and 1 are happy. **Example 3:** **Input:** n = 4, preferences = \[\[1, 3, 2\], \[2, 3, 0\], \[1, 3, 0\], \[0, 2, 1\]\], pairs = \[\[1, 3\], \[0, 2\]\] **Output:** 4 **Constraints:** * `2 <= n <= 500` * `n` is even. * `preferences.length == n` * `preferences[i].length == n - 1` * `0 <= preferences[i][j] <= n - 1` * `preferences[i]` does not contain `i`. * All values in `preferences[i]` are unique. * `pairs.length == n/2` * `pairs[i].length == 2` * `xi != yi` * `0 <= xi, yi <= n - 1` * Each person is contained in **exactly one** pair.
Use Dynamic programming. Define dp[i][j][k] as the minimum cost where we have k neighborhoods in the first i houses and the i-th house is painted with the color j.
Array,Dynamic Programming
Hard
null
412
so this is a pretty easy question nice warm-up to if you guys haven't done lead warm-up to if you guys haven't done lead warm-up to if you guys haven't done lead code before it's very basic and it does it and it involves just a simple data structure that you probably use in your day-to-day basis as probably use in your day-to-day basis as probably use in your day-to-day basis as a developer rather than just kind of talking about stacks and cues and trees and all that stuff that most people don't use so The Prompt is given an integer return string array that is one index where the answers divisible by three and five uh put in Fizz and Buzz into your array if the answer is only divisible by three put in Fizz and if the answer will still only divisible by five put in but and if there is no you know and if the number isn't divisible by any of those numbers just toss in the number into your array so as you can see here for imports n equals three so we're gonna go start from one two and three so hence though one is not divisible by three or five two is not divisible by three or five but three is divisible by three which is why we added a three here so how do we want to get this started uh I guess all in all is we don't really want to over complicate this thing it's as easy as it sounds I'm sure you guys are pretty familiar with uh modules or modes a little bit so first thing first is we got to do is we're going to be using a list data structure that is going to be of type string answer is equals to news oh arraylist switching from a normal keyboard back to a Mac keyboard as always a little bit difficult because keys are a little bit uh differently spread apart so how are we gonna guess get our get all the way up to our end Mount we're going to start with a simple for Loop so forward into I is equal to one because we are starting at one base so I'm going to change that to number it's much easier to follow so a lot of is less than or equal to our n we're going to continue through this for Loop and then from here it's where we're going to do the actual calculation so like how can we decide whether a number is divisible by three and five so I'm gonna do it by simply creating two booleans because that'll be very easy to follow rather than doing the calculation with n in the FL statement because that's where we're going to walk into so I'll just show you that on the ones we get there so if it is divisible by three and let's copy that just change that to five so what we're going to do here is simply just take our n number so FR num and then number n is module three if that number is equivalent to zero that means that well that number is divisible by three and now we just want to do the same thing four and modulo five and if that's the invisible or if the remainder is zero and then the number is divisible by five so boom now we have done the main calculation that we need we've checked that this number is divisible by three and if the number is divisible by five so let me just update that to be correct two a lot of people like to do this problem um while doing the calculations inside the if else statement via false clause but I feel like they can get a little bit lessy I'm messy so I prefer to just kind of make two Boolean variables that hold the value for whatever and we're num n that we're at it's cleaner it's easier to follow rather than just kind of doing all this calculations in if else statements so now pretty much just follow exactly right here if I don't know or yes ifs is divisible by three and is divisible bye let's see let's just do that it's my spelling there we go if that a little bit because since if the remainder is zero then it's true is what's stored in here if the remainder is not zero then we'll get to false of sort here so now we know that with both of them header theoretically if both of them were to check this off they both would be true so all we need to do is simply is do a answer Dot fizz Buzz and you and that's about it you've pretty much just completed the hardest portion of the problem because now the rest is just plug and play else if possible by I believe it's divisible by three do this answer dot add Fizz and the reason we chose an array list as our data structure our choice is it simply it's because it's simple to write uh it's Dynamic we don't know how big and is and it's very easy to just add um elements to it so very easy to add elements to it's very quick it's honestly the best time complexity we're gonna get out of all the other data structures now the real data structure can make this go any faster so but we'll go into time complexity and at the end of this so now we do our final statement so now here's where we get a little bit more intricate so we have to answer dot add an integer dot two string of our num so if you want to transform our integer because we are working with integers up here into this string because we have of type strings over here let's close that off go outside of our little for Loop and just return our answer array and I believe that should be good to go we'll see first time to charm memory limit exceeded let's see what we did wrong here if num is less than equal to n right not bad or int num is equal to one no it's less than or equal to n plus is still four by three if there's this by three and he's two square five if else is by three by five four and numbers third two one and almost less than or equal to n plus oh there it is n plus yep that could uh cause an error right there so almost Flawless for the first video but there you go that's our response that we wanted one two three fifth Buzz one two Fizz four Buzz because that would be five and this is I believe would be 15. yep 14 15. so works perfectly so tank complexity sound complexities are a big thing that you probably gonna have to pick up an understanding nowadays especially with today's market of you know just the competition that there is so they're really going to start grilling you probably and my guess is everything that they can uh the tank complexity for this algorithms or event as we do need to go from one two n here so let's record our time complexity Big O of n and since we do have like I said go to one to n here one for Loop hence the n and the space complexity is Big O of one because we're not using really any extra space that is not included in the result so the only extra space I've used is the result itself so I hope you guys uh could follow all that uh it's a pretty simple warm-up problem uh it's a pretty simple warm-up problem uh it's a pretty simple warm-up problem you know it's not using complex data structures but it'll teach you a little bit of how the instruction can be used that you know most people don't use complex a sources and then day-to-day complex a sources and then day-to-day complex a sources and then day-to-day work but this is a nice intro and how and utilize those so hope you guys enjoyed the video and be on the lookout for another one peace
Fizz Buzz
fizz-buzz
Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_: * `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`. * `answer[i] == "Fizz "` if `i` is divisible by `3`. * `answer[i] == "Buzz "` if `i` is divisible by `5`. * `answer[i] == i` (as a string) if none of the above conditions are true. **Example 1:** **Input:** n = 3 **Output:** \["1","2","Fizz"\] **Example 2:** **Input:** n = 5 **Output:** \["1","2","Fizz","4","Buzz"\] **Example 3:** **Input:** n = 15 **Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\] **Constraints:** * `1 <= n <= 104`
null
Math,String,Simulation
Easy
1316
142
so hello guys so today we are going to see the related questions okay so you are watching programming shift only on YouTube and we are going to see the you can say 142 questions of the lead code that is a linked list cycle to and uh I think you already knows what the link is cycle right so we'll check the link list uh cycle okay so let's read the question given the head of the linked list and return the node where the cycle begins okay so we have to return the node from where the cycle begin okay and if there is no cycle we have to return null okay so there is a cycle in a linked list if there is some node in the linked list right that can be reached Again by continuously following the next point and internally pos position is to denote the index of the node and that tells the next pointer is connected to zero index it's uh minus one if there is no cycle okay and note that POS is not a passed as a parameter okay and do not modify the linked list okay so as you can see that in the example one what we have to do we have given 3 2 0 and minus 4 okay so what is happening when we are each node is connected with the other node okay like this in the arrow you can see so the last node that we have is four is it is connected to the two right and that's why it is making cycle here okay so this is the node we have to return because this node ah this node starts making the cycle you can say ok so as you can see we have given this head and this is the position from where ah the Tails connect right you can say tails connect okay so it is saying that the output tells connect to the node index one and there is a cycle in the linked list where the Tails connect to the second node okay next understand this one so ah we have given one and two so it is saying that position zero and this is 0 and this is one right so we can say position uh zero the Tails connect to index 0 right and this is a cycle in the linked list tells connect to the first node similarly if I have only one right and there is minus one right so it's saying no cycle and there is no cycle in the link list you can say so we have to find actually the ah cycle you can say the cycle is there or not right oh we are we have a okay yeah it is saying we have to return the node right and we are the cycle begins or not right okay that's all so let's understand the approach right before that this question is very important because question has been asked in the top companies right product based company and so we can say that ah you should focus on this question the question we have is uh hash table linked list and two pointer algorithm right we can apply there similar question you may have uh solved this like a linked list cycle and find the duplicate these two questions already we have in the on the uh export Honda you can watch these questions okay so approaches that we will solve in this video is has stable right and another part of this video If you like this video you can ping me in the comment box then well I will upload the other part of this question there is a float wrist and here approach right so let's understand this approach why we are uh using this approach right and uh what is the benefit of the has stable approach okay so our approach is uh we keep track of the node that we have seen already in the set and we Traverse the list and we will return the first duplicate node Okay so ah purpose we have to make the unique uniqueness right and into you can say the nodes right and we will Traverse each time in the we will Traverse the list and uh will return if the duplicate is coming duplicate node is coming right so I'll give them we will use like the first we will allocate a set to store list of node right and then we will Traverse the list while checking the visited for the uh containment of the node you can say right if the node has already been seen then it is necessary to uh you can say entrance to the cycle right and if the node where the entrance of the cycle right or then we should have already returned that node instead otherwise what we will do uh we'll check if the condition will never satisfy our condition will return all right so the algorithm uh you can say terminate for any list with the finite number of nodes right ah has the domain of the input list can be divided into two categories cycle or a cyclic UNC so a cyclic list uh resemble a null terminate chain of nodes and wireless cyclic list can be brought off uh as a cyclic list right with the final null that we will replace with the reference of some previous node right so if the while loop will terminate right we will return the null and we have Traverse the entire list that we will see into the code right and if this is a cyclic right so in this case what we will do if this is a cyclic for a cyclic list the while loop will never terminate right but at some point if condition will satisfy the condition okay so let's understand the code and we'll try to implement there so let's go to understand the hash table approach and we'll try to implement this one so here we are here the list is list class is there this varies there next is there and list node we have given right so what we will do let us go to the browsers sorry here in the code section and we'll try to implement so as you can see that we have given what a list of node we have given in which the head is given right so what we will do from the head uh we should do uh as we told you we should use a set right and this set will take you the this list note right list of this node will be for the unique list you can say we will take as this one and we say uh we should make the visit right so that we will store the unique here we stayed uh node you can say wasted nodes and equal to you can say ah new we will make hash it right we'll take a hash set and will tick like this so that ah so we have created one visited node and we will add uh all the node here if it is duplicate we will return there okay will take one ah list node as a head right we already have so we will take a node and this node is nothing but our word ah will point to our head just you can Set current correct node again right so we will check the current node ah you can make a while you can say current node right so this is our current node so let me write full current I will take like this while current node will take what ah on the current one will check what we will check if this current node is not null right if current node yeah current node not equal to null right sorry current node not equal to null then what we will do will check like we should check like if it is in the visited node or not right so we should check if the we have visited all right we'll check on the visited note if this visited node if this visitor node contains right whether there should be a method contains yeah contest if this contains this node means we have already gone through the current node right if current node is already there okay if current node is already on the visited node right means we have already visited that node so we will return that node that this is the node from where the cycle begin right this is the node from there cycle begins right and if not right so if it is not in the there so what we will do we will say visited and will say visited notes dot add here add this node in the you can say in the list right current node right this is our current node so add this current node into the visited node so that next time will come so we will check into the node and it is there right and then what we will do we will say will update our current node and current node is what our current node Dot next correct and then we will move like this right finally once this is done right then we should return there is no cycle and we will return on right so what I am doing here first of all I am checking the wasted node right if this is visited node we will uh take one head we will assume that this head is current node and we'll check this current node is not null then we will check on to the which state if this is visited then what we will do we will return this current node and then we will ah return ah if this is already visited we will return the current node if this is not visited the current we will return the uh you can say node current node right and if this is not visited we will add on to the visited notes and then what we will do we will update our current node equal to current node.next and then we equal to current node.next and then we equal to current node.next and then we will return our node and that's all so yeah it's working for us right let's submit ah this is working thank you so much okay so what we'll do let's understand uh so in this case you can say uh we are what we are doing we are we have a list of node right so this whole node we are traversing right the current node will move to all the nodes right because we are doing a current dot next slides from the head to its last node we will move to all the node right so time complexity will be o of N and uh we are storing all the nodes onto the visited right so we can say we are taking the space as not uh constant we have of n adjust space a number of nodes will be stored there so thank you guys thank you so much if you like this video please hit subscribe so that you will get more videos like this thank you so much
Linked List Cycle II
linked-list-cycle-ii
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**. **Do not modify** the linked list. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** tail connects to node index 1 **Explanation:** There is a cycle in the linked list, where tail connects to the second node. **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** tail connects to node index 0 **Explanation:** There is a cycle in the linked list, where tail connects to the first node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** no cycle **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Medium
141,287
92
hey everyone welcome back and let's write some more neat code today so today let's solve the problem reversal linked list two so we did solve the first part of this problem a long time ago so let's solve the second part of it today we're given the head of a singly linked list singly means there's only one pointer going out from every single node and we're given two integers left and right that represent some position in this case right is always going to be greater than or equal to the left position and the reason is because these positions represent positions in our linked list now they start at one so basically the first position would be position one next two next three etcetera it's not zero indexed like arrays so in this case when we're given an example problem of left two and right four that means this is uh the left position this is the right position and we wanna reverse the length list only from the left position all the way until the right position so that's what's different about the other problem where we were actually reversing the entire length list in this case we're only doing it from left all the way to right now from left to right what do they actually mean by reversing well the obvious thing is we're going to go link by link so starting from here you know there's a pointer from two to three we're gonna break that pointer and then set it equal to the previous position but in this case actually since this is the first node we're actually going to set this equal to null meaning that it doesn't actually point at any node currently so we just broke that link and then set it equal to null now we're going to move to the next position and do a similar operation right we're going to see that right now it points at 4 break this and set it equal to the previous in this case the previous is 2 and then move forward right now we got to our last node that we want to reverse we're going to break the link again so instead of pointing at 5 we want this to point backwards to the third node this is what we have so far the top right now the bottom is what we actually want it to look like so what's different about our linked list compared to this one well the main thing is we have the order right four points at three and three points at two that's what we have up here as well but the only thing is you know right now our two node just points at null and our one still points all the way to two right instead of pointing at the fourth node so that's really the only operation left for us to do so it seems pretty simple doesn't it now algorithmically what we want to say is our first node or what used to be our left node right this was the left node over here too right we want it now to point at the node that comes right after the right node remember this was the right node so we want it to point at the node that comes right after that which is five which we can do pretty easily right so the drawing is going to get a little messy but let's just cross out the null at the top left and instead have this point all the way to five and the last thing we want to do is this node which we can identify because it's the node that initially came right before the left node right so this node we want it now to point at the right node which is four so we're gonna break this link and then set the new link pointing all the way at node 4. now that we've done all of that you can see even though it's kind of messy on the top side that yes our links exactly form this linked list that we were given so this is the main idea that we're gonna follow now let's actually get into solving the problem before we continue with the video don't forget to like the video and subscribe if you find it helpful and also consider supporting the channel on patreon if you would like to it's completely optional and thank you to the already 40 patrons who are supporting the channel so let's just look at the same example that we just went over the first thing i want to mention is that i'm going to be using a dummy node in this problem and i usually do this with almost every linked list problem now it's never required but it always makes things easier in my opinion so what we're going to do by dummy note i mean that we're going to create a fake node that's not really a part of the list but we're still going to insert it at the beginning of the list because it's going to make things easier for us and when i say make things easier for us it's mainly that we don't have to handle any edge cases now you can see that in this case we want to reverse all the way from left equals two to right equals four so position two all the way to position four right that'll be easy for us because we'll do the same operations that we went over right this node is gonna end up pointing over here etcetera but what if instead of reversing from left equals two we were reversing from left equals one meaning from here all the way to here now in that case normally there wouldn't be a node on the left of it right on the left of it there's just a null over here right nothing on the left of this node right so that's just an edge case we'd have to handle it's a special case if we're actually reversing starting from the beginning of the length list right now we could handle it pretty easily like with an if statement or something but it's a little bit easier to handle it with a dummy node because now that we actually have a dummy node what we're going to do is pretend like this is a part of the list so basically now with this dummy node we would break the link from it pointing at this node and we'd end up having it point at the fourth node as if this was actually a part of the list but it's not now another edge case it's going to help us handle is in some cases uh where you know if we're starting at the beginning of the linked list is going to have a different head remember we need to return the head of the length list once we've actually reversed it which initially is one but if we reverse it from one to four becomes the new head of the length list if we were reversing from two to four one would stay as the head of the length list we can easily handle this edge case with a dummy node because this dummy node is always gonna point at the head of the linked list if it's pointing at one that means one is the head of the linked list if our dummy node is pointing at four that means four is the head of the linked list so a dummy node makes things really easy for us so now to actually solve the problem we're going to do this mainly in three phases the first phase is going to be getting a pointer to actually reach the left node right we want a pointer to be at this node and we want to have a previous pointer pointing at the node right before that because we know that's going to come in handy later on so what we're going to do is initially we're going to set previous pointer which i'm just going to call p at the dummy node and we're going to set our current pointer which i'm just going to call c at the first node we're going to iterate how many times before our current node reaches the left node how many times do we have to iterate well we're starting at position one right in this case we want to reach position two in other words we're going to have to iterate l whatever left happens to be minus one times before our current pointer is gonna point here right so this is the number of times our first loop is gonna iterate uh in this case we're just gonna be doing two minus one iterations just one iteration so we're gonna take our current pointer shift by one to be at this spot and we're going to take our previous pointer also to shift once and be at this spot p is always going to be one position behind our current pointer so since we're going step by step let's code up this first portion of the algorithm before we continue with the drawing so remember the first thing we're actually going to do is create a dummy node and we want it to point at the head node right so initially the value we can give it is zero that's the first parameter the next parameter is where its next pointer is going to be pointing out it's going to be pointing at the head of the linked list and the next part is actually iterating so how many times are we going to iterate uh we can make a loop iterating uh right or rather left minus one times is how many times we're going to iterate we are going to have two pointers right p for previous c for current and initially previous is going to point at the dummy node and current is going to point at the head node we're going to shift them left minus one time so each time that we shift we want to reassign the previous pointer to point at current we want to reassign the current pointer to point at current.next so this is the first phase current.next so this is the first phase current.next so this is the first phase of the algorithm pretty straightforward so far let's continue so next we actually want to reverse the links right so our current pointers initially at the left node we want to keep going right we want to reverse this entire portion of the linked list including every one of the links so how many times are we gonna have to iterate to actually do that well we can take the right pointer minus the left pointer right 4 minus 2 that's equal to 2 but we can see that the actual number of nodes is 3 and that's always going to be the case so we can always do right minus left plus 1 as our condition for how many times we need to execute the loop right minus left plus one and actually since we know that this is the node that comes right before the left node we want to save this node so we're not going to call it p let's just call it lp for left previous because it's the node that comes right before the left node we know this is going to come in handy later on so we'll save that but for now our previous pointer can actually just point at null so let's just assume that this is pointing at null right so what we're going to do is take the next pointer of the current node which is this you know reassign it to whatever the previous node is so right now the previous node is pointing at null we're going to set it equal to null so next we're going to take our current pointer and then shift it to the next node which is over here and we're going to take our previous pointer which was initially over here pointing at null and now we're going to set it to the current node which is two and by the way how can we actually take our current pointer from here and then shift it to the next one if we've already broken the link well we're going to save the next node in a temporary pointer before we actually do that i'll show you that in the code but for now let's continue so again we're at this is the current node we're just going to do the same thing just break the pointer so break the next pointer and reassign it to the previous node which right now is pointing at this node again we can shift our current pointer over here shift our previous pointer over here and again break this link set it to the previous four is now going to be pointing at three our current pointer is going to be pointing at five and our previous pointer p is going to be pointing at four so this is phase two of the algorithm actually reversing this portion of the linked list now let's code it up so we finished phase one of the algorithm one correction though we're gonna actually instead of calling this the previous node we're gonna call it left previous because it's gonna be once the loop has finished executing this is gonna be pointing at the node right before left but now let's actually code up phase two of the algorithm and just a reminder currently our current pointer is pointing at the left node and our left previous is pointing at the node before left now we're actually going to reverse from left all the way to right and initially remember we're setting our previous pointer to actually be at null and so we're going to do a basic for loop and remember how many times we're going to iterate we're going to do right minus left so right minus left plus one that's how many times we're going to iterate and each time we iterate we want to just break or basically reverse the link right so what we want to do is set current dot next equal to the previous node but remember after we do that we're going to be setting previous and current we're going to be updating them right previous is going to be set to current dot next but since we just reassigned current.next to since we just reassigned current.next to since we just reassigned current.next to previous we actually can't do that we have to before we do this we have to save the next pointer so current.next is save the next pointer so current.next is save the next pointer so current.next is going to be saved in temp dot next in this case we won't lose that pointer so here we can just use temp dot next and that's actually it for phase two of the algorithm now let's finish up the algorithm so now let's do phase three the final part of the algorithm which is basically just cleaning up some of the pointers right because right now we see that this portion of these three nodes are not actually connected to the entire linked list right so what do we have to do if you recall from the beginning we have to set this node to its next pointer and by the way this node is the left node if you want to identify it and we want its next pointer rather than pointing at null we want it to actually be pointing at the node that goes right after the right node right the right node that we were going to reverse up until right and how can we get that node well conveniently you can see that our current pointer is actually pointing at this node now what if this node didn't exist what if this node was just null right well in that case our current pointer would be pointing at null so it actually works out pretty nicely for us so all we have to do is really just say this node dot next is going to be set to current but how do we actually get to this node because right now nothing's pointing at this node well conveniently for us we have our left previous node which we saved right this pointer was saved lp and it's dot next pointer is pointing at two so if we say lp left previous dot next right we do uh double dot next right we're gonna go from one to two and from two we're gonna get the next pointer and then we're gonna reassign it to equal to c which is the current point right that's one operation that's pretty easy to do now that we have understood it and the last part which is actually even easier is going to be we want this node to go all the way at the beginning right so we're going to say lp this node dot next is going to be pointing at this node and how do we identify this node well remember our p pointer is still pointing at this node which is really convenient for us now you can kind of see how this double pointer really helped us out lp.next can pointer really helped us out lp.next can pointer really helped us out lp.next can be set to this and then we're actually done with the entire algorithm right we'll have this node pointing at five and have this node pointing at uh four it's obviously really messy right now but we know that this uh linked list is exactly what we want and how are we gonna return the head we're just gonna take our dummy dot next and that's going to be the new head of the linked list so that's all we need to do now let's actually code it up so phase 3 is just updating the pointers so we know we had left previous dot next is what we want to set to the last node or the node right after right which is our current node which we now understand because we went over the drawing explanation and then after that last thing we need to do is say a left previous dot next is equal to uh previous and just to remind you current is the node right after the right node and previous is the right node and then after we're done with this the only thing we have to return is dummy dot next because that's where the new head is going to be at if we ended up reassigning the head but for the first example we actually didn't but yeah this is the whole code it will be in the description if you want to take a look now let's submit it to make sure that it works and as you can see yes it does work and it's pretty efficient because this is a big o of n time complexity solution because we just iterate through the linked list once and we don't use any extra memory so the memory is big of one 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 if you would like and hopefully i'll see you pretty soon thanks for watching
Reverse Linked List II
reverse-linked-list-ii
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\], left = 2, right = 4 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[5\], left = 1, right = 1 **Output:** \[5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 500` * `-500 <= Node.val <= 500` * `1 <= left <= right <= n` **Follow up:** Could you do it in one pass?
null
Linked List
Medium
206
160
One of the very popular questions when it comes to linked list. You are given the head of two single linked lists and you have to find the intersection point. What does that mean? Let us say you have a list A and you have a list B, then one of the nodes in list B points to one of the nodes in list A and hence that interaction point. Just stick with me a little longer and I will show you clearly with the diagram. What does that exactly mean. Hello friend. Welcome back to my channel. A place where we explore the life of technology and make programming fun and easy to learn. Today we would be solving the problem. Find the intersection of two, linked lists on LeetCode. But I will explain you the problem of statement, and we will see some sample test cases. Next, we will try to approach the problem using a brute force method and see what problems you may face. Going forward, we will keep on optimizing the solution and ultimately will also do a dry run of the code so that everything sticks in your mind. This way, you will never forget about it. So, without further ado, let's get started. Okay. First, let us try to make sure that we are understanding the problem treatment correctly. You are given the head of two single linked lists and you have to find the intersection point. Let us look at this test case that we have in front of us. Because if we understand this, we have understood the problem statement. So, Look at these lists individually. Let us look at our lift one. Oh, if we take head one, then this is the current lift, right? And when we take a head to, this is a current lift. But as you can see, these are two complete linked lists in itself. By the way, if you're new to linked lists, I would highly recommend you to check out my introductory videos. so, now given this scenario, What can you see special about it? The next of known, number four points at 16, correct? And in List 2. The next of known. Number 15, also points at node 16 and hence, the intersection Who in this question, you need to return 16 as your intersection point. Right. And there could also be a case where you are given to lifts but they do not in effect. for example, in a test case, number two, we have had one. And this is a lift in itself. Correct. And we have head 2 and this is another lift in itself. note that even though it has same value 6, They do not intersect. Because in a linked list, you are concerned with the memory address. For the next of 4 is pointing at the same address. As the next of 15. To basically the address is same. And hence 16 is the intersection point. Now, if this problem, fitment is clear to you, feel free to try it out on your own. Otherwise, let us look at some of the innovative solutions that we can solve it. A good developer always tries to come up with a brute force solution. First, That is because a beautiful solution can guarantee you if the solution to a problem exists. So in this scenario let us take apart test case, once again. You have these two lists where you have had one. that represents the first lift and you have head to that prevents the second lift Now, you need to find out the intersection point, right? And, you know, that the intersection point could only be determined by the addresses of the node rather than the value. So as you can see, even though the value 4 is same in both the left. But 4 is not the intersection point. 16 is the intersection point, right? That means you need to find out the intersection point based upon the address of this nodes. You know, that these addresses could be anywhere in the CPU memory, right? So they're pretty random. So, let me just assign some random memory addresses. Oh, right now, these a b x Y and Z are memory addresses for your first list, correct? And similarly, you can have some random memory addresses for your second left. Also, So you can see that Mn and O are unique addresses for your second list. But for your intersection point, you will have these same addresses, right? And as you can see, this is the intersection point. So how does a brute force solution work? What you can do is you can start with the first node. That is 2. Correct. Or that is the memory address A And what you can do is you can check this memory address A with all these addresses. M, n o x, then y and then z. Then y. Since it does not match with any of them, then this node is not an intersection node. Similarly, you go to your next node. And this time, I am at noon number 4 or address B. Now once again, you will check this address B. With the first address with the second address of lift to, with a third address of lift to with x. With y and then with z again. It is not same anywhere, right? So, this node cannot be a intersection node. Going forward. You do a next again. As soon as you do a next, You reach your next node. And this time, you are at known number 16 or the address X. Now, what you do? You will again compare x with the first address m. Then n. then, Oh, And then have you compare it with the next address of your second left. You encounter the address X? Now, both of these addresses are same. And that means you have landed at the same node, correct? And hence, you can say that 16 is your intersection node. Who you found out the intersection node? But do you see the problem with this approach? You are doing so many comparisons, right? And you're doing all of these comparisons, for all the nodes in left one. What happens if your lists are very large? What happens if your intersection point is very far away? You will keep on comparing, and that will take a lot of time, right? And hence this method is not optimized method. So, how can you optimize it? Let us try looking into that. When you try to optimize the solutions, always go, step wise, you know that you can make a space optimized solutions and a time optimal solutions, right? So, when we were doing a brute force approach, what was your major concern? You were taking a lot of time, right? Just to compare all the addresses. So how can you reduce that time? You are taking a lot of time to look up all the variables, right? You are trying to compare all the addresses. Who, what if you can decrease that time to look up the addresses? So let us take up our same test if once again. We have a head one and we have a head, too. And we have all of these memory addresses for the first list. And you have all of these memory addresses for your second lift. Right. Now. Let us try to create a hash fit that will score. All of my addresses of lift, 1 2. What you can do is you can start off from head one, right? And as soon as you start, what is the first address, you see? You see address a correct. So you will add this address to your hash fit. Next, when you do a next, you see the next note. That is B. Once again, just take this address and add it to your hash fit. Then you have x then y and then z and then ultimately null. So what you will just simply do is just add all of these addresses to your hash fit. so, I add x y and then said, Now, this hash set is complete and we have completed, one hydration of the link left. Next to find the intersection point, what do you do? You start off with your head too. That is the second linked list. and now, what you can do is you can compare all of these addresses in your hash set, A hash set gives you a quick lookup time. You can do it in order of one. so what you can simply do is you can start traversing, this second left, you see this address M and you try to look it up in your hash table This address is not found, right? So, what do you do? You simply go on to your next point? Now, try to find N in this hash fluid. You cannot find it. Oh, just move ahead. Try to find. Oh. You cannot find out. So move ahead once again. Now you find out x as soon as you see x, you would find this element in your hash fit, right? That means. This is a repeated note. And hence, you can say that the address x Is the intersection node and hence, this will be a answer. Po in a way we were able to optimize the time taken by our solution. Correct. But what just happened? In order to save some time we are consuming some extra memory, right? We took up an extra memory of order of N. So, Can we try to optimize this solution? Even further? Sure, if you have lots of memory, then no need to worry about it, but I'm pretty sure your interview will ask you even further for a space optimal solution. To what can you do about that? Let us have a look at it. Okay, since we're trying to form a very efficient solution that is both space and time optimized. Let me take up an even bigger example. In this test case you can see that we have two large lists, right? And if a solution is optimized, then the length of these lift, shouldn't matter, right? As the rule of thumb, I would always say that. Try to visualize the problem every time that you see it. So right now, let us look at these two lists separately. If you look at lift number one individually, what do you see over here? What is the length of this list? This list have a length of 10, right? And try to see the lift to also separately. If you look at this list too what is the length of the list? The length of Lift 2 would be fixed. Correct. So now, you know, one fact that the difference of these two lists is 4. That means you have four extra nodes in left one. And after that, both the lists have a same length. somehow, if you can reach that point, then you can find out the intersection point, right? For example, in this case, the length of lift, one is 10 and the length of lift 2 is 6. The difference is 4, right? Who you know that lift one is larger by 4 elements, correct? To what happens if I take my head one and I advance it, four places one. 2, 3, and then 4. when you try to look at the head one and head to now, You see that just after two nodes you can find out the intersection point. Correct? Now, solution that comes to, my mind is take both the pointers and simultaneously move them ahead. But if I move head one step. And I move head to advanced step. Once again, if I move head one step. And I move head to one step. Then it is guaranteed that at the intersection point, both the head one and head to will be at the same position. So when you're moving both the pointer simultaneously, there will be a point when both the pointer will point at the same node. And ultimately, this will be your intersection point and you can simply return this as your answer. This node is your answer, right? This is the intersection node. So, what do you think about the solution? We will able to fuse the beauty of mathematics and we took advantage of the difference in lengths. And somehow we arrive at the solution, right? Now, let us try to do a dry run of the code to see how this actually works in action. On the left side of your screen, you have the actual code to implement this solution. and on the right, let us take up a sample test case, once again, So, you pass in the head, a And Head B. As a parameter to the function. next, what you do is you find out the length of both the left Now, I have this private function with me that will return me the length of both of these lists. So as you can see the length of list A is 5, right? So I will write down the value. 5 over here. And next. The length of lift B is 3. So, this function will return a 3 to me. In our next step. What do we do? Is if list A is longer, then we move the head pointer of lift a or if lift B is longer, then we move the head pointer of lift B. Right now, lift A is longer, right? So what I will do is I will increment this pointer by 2 places. That is the difference, correct? so, as soon as I do a head dot next two times, What will happen is this pointer? A will move to steps and it will reach over here. Now, both of the pointers A and B will be at an equal distance from the intersection. And you can take advantage of this. What you simply do is you move. Both the pointer simultaneously until unless they meet. So, I start a while loop until head a different reach equal to head B. And what we are doing the loop. I move the head a pointer one step and I move the head B pointer one step. So that will increment a pointer over here and B pointer over here. In this special scenario, just after one iteration, we were able to reach the intersection point, right? so, what you do is you simply return this azure answer If you lift with a little longer, then it would have been after a few iterations, but you would have ultimately reached the solution. The time complexity of this solution is order of N. Plus M. Where n and m are the length of 2 lift because your traversing them once. And the space complexity of this solution, is order of 1. That is because you are not consuming any extra space, you are just traveling the left, right? I hope I was able to simplify the problem and its solution for you. As per my final thoughts, take a moment to realize the solution that we just discussed. When you think about a link list date structure, you don't just have the value. In a linked list, you have the value as well as the address of the node. That means that you have two parameters to play around with. And sometimes using either of these values, can help you to reach an efficient solution. To whenever you encounter any fit problems on linked list? First try to visualize it, just try to plot out a diagram and see how the question is actually looking. You may be able to find it a solution that you didn't even expect. So, what other solutions did you find out? What problems did you face? Tell me everything in the comment section below and I would love to discuss all of them with you. You would be also glad to know that the text-based explanation to this content is available on the website study . A pretty handy website to help your programming needs. I am including a link in the description below in case you want to check it out. As a reminder, 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. Also let me know what problem do you want me to solve next. until then see ya!!.
Intersection of Two Linked Lists
intersection-of-two-linked-lists
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`. For example, the following two linked lists begin to intersect at node `c1`: The test cases are generated such that there are no cycles anywhere in the entire linked structure. **Note** that the linked lists must **retain their original structure** after the function returns. **Custom Judge:** The inputs to the **judge** are given as follows (your program is **not** given these inputs): * `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node. * `listA` - The first linked list. * `listB` - The second linked list. * `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node. * `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node. The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**. **Example 1:** **Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3 **Output:** Intersected at '8' **Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. **Example 2:** **Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1 **Output:** Intersected at '2' **Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. **Example 3:** **Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2 **Output:** No intersection **Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. **Constraints:** * The number of nodes of `listA` is in the `m`. * The number of nodes of `listB` is in the `n`. * `1 <= m, n <= 3 * 104` * `1 <= Node.val <= 105` * `0 <= skipA < m` * `0 <= skipB < n` * `intersectVal` is `0` if `listA` and `listB` do not intersect. * `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect. **Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
null
Hash Table,Linked List,Two Pointers
Easy
599
130
hello everyone welcome to clash encoder so in this video this is the question that is 130 that is surrounded regions so it is a medium level question and it is also sometimes as interviews so let's see the problem statement given a 2d board consisting or containing x and o this is actually not zero you can see the letter o capture all the regions surrounded by x so here the all the like directions are not given so we will consider only top bottom and left and right not the diagonal okay a region is captured by flipping all the zeros or sorry all the o's these are o's into x in that sounded region so this is the example that we are given and this will be our output so let's see i will explain you the like how we can do that so you can see this is the matrix this is the same matrix as given so in this we have to first of all check for the o's so these are the o's you can see and o is only trapped if this is o it is only trapped if it has all x's on its four directions you can see x are there okay so we don't have to compare this one this diagonal we don't have to compare but in this you can see this o is actually trapped it is covered by all the four sides by x so you can see it is trapped but in this so if you compare so it is not covered by the left and the oh sorry right and the bottom so it is not like covered or not cannot be captured so this is what is a simple captured word means for this o okay so now let's see and this you can see problem we are given so we have to capture all the x so for capturing them we have to flip them to or flip them or change them to x so if this uh let me change this or let me take the highlighter so you can see in this you can see only this zero okay and this zero are captured so we will have to change them to x if we have to capture them so as it is written a region is captured by flipping all the zeros into x so these three zeros are you can see are captured by x because you can see x is covering all the sides for the zero you don't have to compare this because this is diagonal we have to compare only the four side that is top left right and bottom so this is what we have to compare so we will simply you can see these x are getting trapped so we will have to what we have to do is we have to simply convert them into x so we have to overwrite this matrix and we have to simply convert them into x but if you said this 0 is not trapped by all the directions so you can see this is x okay this is x but there is no x on the bottom so this cannot be trapped if it would have been like this okay this would have been given so you can see this 0 is great getting trapped now because it is strapped by all the four directions so it cannot move so va can simply convert it to x so this is what we have to do this is what the problem statement means so let's see the algorithm for this so actually what we will do is let me show you so our algorithm main algorithm will be we will simply traverse first of all we will traverse this row or top and bottom row and uh sorry first and last column so we have to uh like reverse this first and last and uh this first and last column and rows okay then what we will do is we will first of all traverse this and let me erase these lines i will explain you here only so you can see i've written the like pseudocode also here so first i will explain you what we have to do then i will explain the pseudocode so you can see in this matrix that we are given what we will do is we will first of all traverse this top row okay we will traverse this top row and we will check if there is some zero because if you know if there is some zero like in this case if there is some zero okay if there is a zero so if this bottom is zero so it will uh or it will be not this zero will be not trapped so if we have we like get a zero over here in the boundary so we will check if it is connected with any other zero because then it cannot not also be trapped so we'll simply mark them as some other number that we will change afterwards so we'll mark them as other number if it would have been zero here then we don't have any zero or sorry oh sorry if i said zero sorry for that it is actually o it cannot be trapped because this is not covered by x and on the bottom side so that means it cannot be trapped so these zeros also these can also not be tried so that is what we have to take care of so what we'll do is we will simply traverse the first row last row and the first column and the last column and we will check if there is any zero so we will traverse this okay there is no zero you can see and we will traverse this uh first column also there is no zero and when we traverse this last row the nth row then you see there is a zero so we will what we will do is we will check if we will mark it to some other value actually that is i or something you can say any other value you can keep it as one or something like that so what we will do is we will check if it is zero okay and then we will mark it as one okay then we will go to this zero so you can see this zero so what we will do is at every point every zero occurrence if there is a zero occurred okay this zero has occurred so then what we'll do is we will run a dfs from this point and what dfs does is it will check in all the four directions that is this top bottom and left and right so it will check on the all directions and it will check if there is zero so yeah it has a zero adjacent zero so what it will do is it will mark it also as one or you can say an other number that you want to mark it as so it will be on smart as one this also will be marked as one and then a dfs will recursively run for this element so it will again check for top position left position right position and down bottom position so if it checks for the left position so you can see this is also zero so this will be also marked as one or any other value that we want to use or any character so like this we will end up having all the like values that were occurring with the zero uh that is bound to zero all the o's that were connecting with the boundary o's will be marked as any other character so that means it cannot be trapped by x so that means we will simply reduce our search space for those zeroes or o's that can be trapped by x so at the end what we will do is we will have this values as one okay we will keep them as one or i will mark them as m or you can say marked okay so at last we will have end up having this matrix so you can see we have this matrix so now what our job will be simply we have to traverse whole matrix and if there occurs oh simple oh because you can see this occurs so that means it can be trapped otherwise if like it was this o you can see if this was oh then it cannot be trapped because it is not covered by the left side or the or you can say left side only yeah this one cannot be called by the bottom side and the left right side sorry so that is what we have to do so now if any o occurs so we can simply change it to x you can see to capture it we have to simply convert or flip the o's into x so what we will do we will simply convert them to x so you can see these will be converted to x and at the end we will also keep checking if it is one or we at the mark value that we have used so actually we will use m you can say marked m mark so these are actually characters vector it is a vector of characters so this is what we have to do so we have to mark it as one so when this x occurs okay this zero occurs we will simply change it to x because it can be trapped otherwise it would have been marked as one or the m uh during the dfs quality if it is m r1 then we will simply convert it to zero again because if it cannot be trapped we have to keep it as it is o and you can see here it also it is oh sorry for that i am also getting confused between zero and oh so i will if i say zero that means only so don't uh depending on that so let's see so this is the algorithm for that you can see algorithm is also same actually it is mostly i will show you in the code also so yeah so you can see this is pseudo code actually so first what we have to do is we have to run two for loops for traversing this matrix and we have to as i told we have to first of all check for the rows okay last uh first row and the last row and first column and the last one so for doing that we can simply uh like run a loop okay two or two nested loops and then we will check if i is equal to zero that means it is the first row then we will check if the board of i zero i and j okay if this is like this point if this is zero so it will be i z j so we will simply run a dfs on this point from the dfs from this point and it will all it will mark all the adjacent pose to this point as an another character that will assume to be one or m you can see i will assume as m in the code but here i wrote as one because it is difficult to write m using this mouse so you can see we will check if board of i or i j is o then we will simply run a dfs and on that point and like at this point you can see dev phase will run so it will automatically or recursively call this one for this point so it will also call for four directions we will check for four directions if this is i j so then it will check for okay i minus one j okay then it will check for i my this point actually this one will be not marked by this okay this is diagonal so actually when we call for this it will call from the left side so then it will be marked uh keep that in mind so that means it will call for uh call for like j plus 1 j minus 1 and i plus 1 and i minus 1 that is what the dfs will do i will show you in the code also so actually let me show you here only so uh once if you see but if we call the dfs for this point okay if you call dfs for this point so it what it will do is it will check if this is o so yes it is o and it is in between the bounds you also have to check if i and row n column are between the bounds of the maximum row and the column and it is greater than zero so then we will check if it is o then we will simply convert it to i so we will set it to i or any another value that we want to use so i am using different characters for here but there you will have to use only one character then we will mark it as m or i you can say or then what will do we will call it recursively for the top side bottom side left side and right side so it will call for this point so it will again check if it is o so yes it is o and it is between the bounds then it will again mark it as i or another character that we are using and then again it will check for the left side top side bottom side and right side so again for this point also it will check if it is so then it will change it to i or another character then it will again check for the left right bottom and like that it will keep doing and at the end for every like border element if it is zero okay it will end up having another character here so that means these cannot be trapped so we'll simply don't have to uh like uh traverse them so that's why it will save a lot of time if you use dfs on like in the name using the name approach on all every element then it will have a like more time complexity but now you can see it is better now so then afterwards after we have marked all these elements as some another character then we are only left with the os which can be trapped otherwise they would have been marked as another character okay using the dfs so again we will traverse over this matrix and we will check if it is o then we will mark it as x to capture it we will mark them as x okay if it is i or another character that means it cannot be trapped it was o and it cannot be trapped it could not be trapped so that means we will simply mark it again back to o so we will mark them again to o after this so let's see the code also so i've written the code in c plus so i will explain you the code step by step so let's see so actually this is the main function that we are given and we are given a vector of vector 2d vector equation matrix of a type character so these are actually characters so uh you can see this board so we will first of all take this the row size so row size will be maybe board of support size and for getting the column size it will be actually port zero dot size so port zero will contain actually these values in this uh it will contain like these values so its size will be one two three four so this will be size for this board zero so let's see okay sorry so now you can see this is uh the base conditions that we have got okay we will also check if the row is zero so that means uh if rho is already not there then this is empty matrix that we are getting so we will simply turn so actually here the return type is void as i told you it is a by reference so that means we have to simply change the values in this board so we don't have to return it will automatically reflect into the original matrix so here is what we are doing for the calling the dfs so we will run two for loops and we will check if it is the top row okay or if it is a top column the zeroth column or if it is the last row or the last column then we will call if uh we will check again if it is o if for like we are traversing this matrix okay as i told you we're trusting this matrix and at this point we'll check if it is o then we call the dfs from that point so as it will call for the dfs function so in the defense we are passing the port and the row and the column that particular element and the maximum or the size of the row and the column so this is our dfs function so actually in this dfs function also you have to take it by reference because you are converting it to some another character so i am converting so let's see so these are the rows and columns that we are getting row and the column and these are the maximum sizes okay of the row and the column so we will check if i is less than zero so that means it is not valid so we will check for the invalid conditions and if it is these invalid conditions are true then we will simply turn because that is not valid so we will also check for column is less than zero so column is greater than the maximum size of the column and rho is greater than the maximum size of row so then we will check if the particular element is o so if it is o then we'll convert it to some another character because that cannot be converted or the captured by axis so that means we will have to convert it to another character so we have to uh here converted to the m character so then we will call the dfs for the uh four directions on the row so if we are calling for this matrix so then we will call the dfs for the top okay and the left and the right and the bottom so that is what we are doing in that step okay so we are doing that in this step so we will call the dfs for all the points and dfs will automatically recursively call for all the other adjacent elements and mark them as m if they are o because they cannot be captured they are connected to the boundary elements so if they are connected with the boundary element those o are connected to the boundary elements that means they cannot be trapped by x these are all connected if these are not connected you can see by any o on the boundary if it would have been o here then it would have been uh converted these all those would have been converted to some another collector so they cannot be trapped so this is what our simple dfs function is doing and let's see so at last what we'll do is we'll simply run two for loops again to traverse the matrix and then we'll check if the particular element of the board is o that means it can be trapped so we'll simply flip it or convert it to x and otherwise if it is m so we have to return the original matrix or return the matrix in the original form so there was no m in that so we'll have to convert it to the o back so let's see so we don't have to return anything actually it is a like void function so let's see so yeah it is running so you can see accept it so let's submit the solution yes so you can see it got accepted and it was faster than 99.97 of solutions it was faster than 99.97 of solutions it was faster than 99.97 of solutions in c crystals and also took less memory than 5.67 percent of solutions so let's than 5.67 percent of solutions so let's than 5.67 percent of solutions so let's see the time complexity so actually the time complexity for this will be simply rows into columns because for a matrix you have to like run two for loops at least because you have to traverse the matrix so it will one loop will be for the rows and one loop will be for the columns so the max time complexity will be actually approximately n into m so that time complexity will be m into m the space actually will be constant because we are not using any space we are simply converting the elements into the original matrix and returning them so our space will be constant but our time complexity will be number of rows into columns or m into n so thank you for watching guys i hope you like this video and i will also share this code in the description so you can check it from there and do like this video and subscribe channel thank you for watching guys
Surrounded Regions
surrounded-regions
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`. A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region. **Example 1:** **Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Explanation:** Notice that an 'O' should not be flipped if: - It is on the border, or - It is adjacent to an 'O' that should not be flipped. The bottom 'O' is on the border, so it is not flipped. The other three 'O' form a surrounded region, so they are flipped. **Example 2:** **Input:** board = \[\[ "X "\]\] **Output:** \[\[ "X "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 200` * `board[i][j]` is `'X'` or `'O'`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
200,286
1,737
hey everybody this is larry this is me going over q2 of the weekly contest 225 change minimum characters to satisfy one of three conditions um hit the like button hit the subscriber and draw me discord um if my energy is a little low today i'm just dealing with something huh uh everything will be okay but yeah um this one was actually a relatively tricky problem as you can see the accepted ratios a thousand accepted uh of eight thousand submissions right so a lot of wrong answers here uh in myself included i actually solved this at the very end and i think this took the most time of all the problems i did uh after four problems uh mostly because of one mistake but i think out my algorithm is mostly right but basically you have three conditions and you have to satisfy one of them i actually also initially misread this to satisfy um uh at least two of these i guess three of them cannot be true but uh but yeah um so basically i proof first doing it one at a time and what i and i did this during the contest but um but i will go over um yeah we'll go over things to optimize for because i definitely did not do it the clean way um but yeah so basically yeah so first of all we can check to see um you know uh i mean i'm gonna do this not really in order but i'm going to try to satisfy okay let's put force checking every uh a and b consists of only one distinct character which is what i did here um basically the idea uh that i built off is just having a hash table of you know all the characters to um characters to the number of count that they have uh this is of course gonna be uh of n but um but the result is that this hash table is has only 26 uh items right and then now because and the quote one of the new ends is 26 we can do a lot more boot force on it and basically for the uh for the same case i just basically go okay let's say we change a to xs b to ys what is the cost of this right so the cost of this is okay so you have n characters on string a you have you know this amount of characters for uh in string a that is of this character so you want to change everything else to this character so this is the cost of changing the string a and this is similarly the cost of changing string b and then we just take the min of all those uh so that is the same one right um and then the other one um i think there are cleaner ways to do it but this is the way that i chose to do it which is that uh yeah and actually i think i wrote a lot of extra stuff but i can actually remove this i think and i can actually remove this um but basically i brute force x and y um so this should roughly be the same but basically what i did was i actually did a um and there are different ways to do this but basically i did a prefix array uh here uh where pa of x is equal to um the number of characters oops before x not including x right and here is similar where as x of x is equal to the number of characters after x not including x right and then now um so i do this calculation as a little bit uh precalculation this kind of looks like what it should sounds like which is the prefix basically we just you know sum up all the prefix up to this character um in a careful way um definitely recommend slowing it down and kind of look for the code for if you're a little confused about this part um but yeah but basically you just have a running a and then you sum it and then you put it into the thing and then we run it in backwards for uh the suffix right because the suffix is just equal to uh the all the characters minus the prefix minus um yeah oh sorry minus the prefix minus the uh the current character right so that's basically why you know this is this and we do the same for a and b um and then lastly uh for each character you know oops we choose x to be the period right and what this means is that we choose x to the period um and then now we break down to a number of cases where uh oh and i guess this is x um yeah so basically here we do a number of cases um which is that you know um oh maybe some point statement um yeah so this is the prefix so this is um given that the current character is x is the period we want to set all the prefix of a um to x and then all the suffix of b to before b right um so basically yeah this is what this looks like which is that we um yeah here we set all the x all the a's to x b's to x minus one we get the cost we you know compare it um we set order x to um so this is set anything bigger than x no anything smaller than set anything smaller than x in a to x so this is where the prefix come in anything bigger than x or anything x or bigger in b to x minus one right so that's basically what i do here because the suffix is all the stuff that's bigger than x um and this is just the number of x exactly because we want to set it to x minus one um so yeah so that's basically the idea here uh we do the same thing here except for now we just change the middle ground so then we change a to x minus one and b is to x um and of course you have to check the bounds so what i spent a long time on that i was using z as the pivot i was doing it off by one way tries to do the 27th character or something like that uh so that was my mistake um and here yeah we set anything bigger than x and a is to x anything x or smaller to this thing um and then again we do that but now we have to change the bounds um we i could do a visualization if you want but that's uh basically the idea is that you just figure out okay if this is the character that we're pivoting um or the you know all of one string we set it to before and all the other thing string we set it to after and once we do that um that's pretty much it um yeah let me run it real quick because i did change the code a little bit yeah uh and the case that i was having issues was a b c d f h i j k l m n o p q r s t u v w x y z and i don't know just a random k or whatever um but yeah i was initially returning one because i was letting k change to z um so yeah so what's the complexity here well this is going to be linear just converting them to hash tables but then after that this is all of 26 square which is straightforward um you know this is all 26 which is also you know and this is also of 26. so this is in total of n and in terms of space this is actually going to be o of 26 because this only contains up to 26 characters uh and this as well and also these prefix and suffix only contains 26 characters so we don't use that much space um yeah that's all i have for this problem uh let me know what you think uh let me see what's the i think this part like i said um you could freeze that this is very long cover i'm not that proud of it to be honest but yeah this is the code where um uh yeah they you match them to one characters to each um and actually you could probably do them independently now that i think about it so you can actually reduce this to all of um of 26 because these are independent right um so you could just try to find the min x character and the min y character and then i added together so actually i could uh let's do that optimization right now um i mean x is equal to i don't know that's just a million um and then min x is equal to uh min of min x a n minus a c x s um and then min y is equal to min of min y uh bn minus bc ys uh and then yeah and then at the very end best is just equal to um min x plus min y um so you get so now this is uh let's run it real quick again i'll show you the code again sorry don't worry uh oh i forgot to send min y um yeah uh okay so yeah so basically here we just matched them to one character uh and so yeah so you can take a look here and here this mess of a code with comments is basically choosing the period once you get the idea the code is still messy because it took me a long time to get it um but conceptually i feel like it's okay once you have a queer daughter what you want to do let me know what you think uh and i will see you later or you could watch me salvage during the contest of the long video afterwards um you um um hmm but a one of them whoops huh i miss what that okay um yes uh strictly okay now that's good this is one okay now do this just do it you um it's a very slow answer but well better than nothing i suppose i'm okay strictly last time so x is that the prefix no that's a suffix plus uh ac uh we're going to set everything less than y and a is hmm so now the other way if x is greater than y we set everything smaller so okay uh well that's a better answer than i thought it would be so that's actually bad okay why oh no is that right 0 is 1 because we said this is wrong anyway so we set a's the prefix is going to be zero that doesn't make sense so let's see oh this is so annoying just set everything to a and everything a plus one this is set everything to x i have to have some conditions here so hmm yeah okay so this is coolly well count the suffix actually there should still be two why is this all right let's take a quick look first zero one zero why did i mess up on the counter oh wait because this is not the thing dummy but it's still well i think but it's still dummy okay maybe it's right i don't know i mean this should not be an answer just because this converts everything to a it just converts everything to the letter before a so i think this is wrong but i don't know i'm a little tired right now so let's just give it a yellow submit after running this one last time to make sure i don't put anything funky uh okay well i guess that i should have tested that one i'll put one why the output one but shouldn't this be zero at some point okay don't care about it oh whoops uh that this part is dumb i don't need it i thought i needed for something else but i guess i don't need it still the wrong answer though but then oh what uh i am dumb today this is the worst code ever don't judge please okay let's give it a go man come on what are you what do you think i'm trying to hack here why are you not giving me my hidden case um but i am so bad cd is this true yeah i guess so you just change one of the c's to d's or something this should be two maybe yeah one ladder and i don't know how to get an answer in here to be honest hmm don't miss anything anywhere maybe a typo somewhere one i guess you just change a i don't know i mean i'm sure i'm wrong it's just that i don't know where it could be wrong um this is this i'm confident about maybe i don't know i can't even run the code why do they uh this is so i mean this is why i like this you know lego formats because they tell you how to learn instead of do i miss sets no this should be okay just because i missed something silly i guess okay let's see oh maybe i got this fall um this is okay and this is okay maybe let's see what am i trying to say here is set to easy okay let's try again oh come on suffix of x this is actually just really wrong i think no maybe not okay we set everything in a the prefix of a's and x plus one and then the suffix to i now this is right maybe here i just copy it and paste so maybe there's something wrong here i can't believe this i'm taking so long this is one of those worst weeks of my life kind of thing uh okay let's see set a's to x plus one so this is the comments have longed i just copy and paste these i guess so basically i set in the other direction right this is why and what i want to do let's see let's print why is there no a in here no it doesn't i make sense asco one is that right i know this is the prefix of b so yeah okay this is right i think and this is suffix of yeah okay i don't know so i'll come back to it okay i mean i don't know how to pee but uh let's see but at least i got the um which was kind of i don't wow congrats safe vmx uh vmk sorry a lot of good people here too well um a lot of people got q2 though i don't know like a thousand people is a little bit on the lower side but it's still i don't know what am i doing wrong at least i got q4 though oops that's wrong what oh no this is just changing this to said is this for true i think my min is wrong here because you can do some i think that's maybe why uh let's actually do something like yeah uh actually anymore and i one of the sad part is that one of these uh was just a silliness where i didn't do it but um okay see this cannot be right so why do i get one i have nine minutes i actually have a debug case so let's see so that's not here okay that's good that means that one of these is true set change this to z but that's at least two so i have a wrong answer here okay seven minutes that should be enough to fix let's fix the larry so this happens when it's easy let's see so it's not here yet oh i checked the prefix which is 2x so this is the prefix so this is actually five plus one let's give it a go oh okay i mean hey everybody uh thanks for watching thanks for checking out this problem let me know what you think let me know what you're running into and i will see you hopefully next time bye
Change Minimum Characters to Satisfy One of Three Conditions
maximum-nesting-depth-of-the-parentheses
You are given two strings `a` and `b` that consist of lowercase letters. In one operation, you can change any character in `a` or `b` to **any lowercase letter**. Your goal is to satisfy **one** of the following three conditions: * **Every** letter in `a` is **strictly less** than **every** letter in `b` in the alphabet. * **Every** letter in `b` is **strictly less** than **every** letter in `a` in the alphabet. * **Both** `a` and `b` consist of **only one** distinct letter. Return _the **minimum** number of operations needed to achieve your goal._ **Example 1:** **Input:** a = "aba ", b = "caa " **Output:** 2 **Explanation:** Consider the best way to make each condition true: 1) Change b to "ccc " in 2 operations, then every letter in a is less than every letter in b. 2) Change a to "bbb " and b to "aaa " in 3 operations, then every letter in b is less than every letter in a. 3) Change a to "aaa " and b to "aaa " in 2 operations, then a and b consist of one distinct letter. The best way was done in 2 operations (either condition 1 or condition 3). **Example 2:** **Input:** a = "dabadd ", b = "cda " **Output:** 3 **Explanation:** The best way is to make condition 1 true by changing b to "eee ". **Constraints:** * `1 <= a.length, b.length <= 105` * `a` and `b` consist only of lowercase letters.
The depth of any character in the VPS is the ( number of left brackets before it ) - ( number of right brackets before it )
String,Stack
Easy
1208
869
hey everybody this is larry this is me going over march 21st lego daily challenge uh let me know what you think about this farm hit the like button the subscribe button join me on discord um and yeah we ordered power of two is today's problem uh okay starting with a positive in jan how did you do i don't know did anyone do the contest today uh let me know how you did i did okay in both fire could have been better but a little bit messy anyway let's get back to this problem uh we ordered power of two starting with a positive integer and we all ordered the digits and then number leading us to return true we can do this in such that the result power of two okay um such that i mean this is weird isn't it just hmm i was gonna say isn't it just like the power of two um but then 46 deleting we ordered the digit in it for some reason when i said when i think about reordering the digit i was thinking about reordering the binary digit so okay so we want to um basically want to reorder these numbers so that with our leading zero um we want like this is true because it's 64 right um so the short answer is that 10 equals to 9 so there's only about 30 or 31 um powers of two right so then you could create a frequency table and do a lookup table and that's basically what i'm going to do um and you're gonna actually be a little bit more clever if you like going up to only the powers of two that are the greater than the number of digits or something like that but i'm just going to do it the lazy way right so basically okay so let's just say we have a set this is uh what i call renormalized power of two um so let's just have let's just call it lookup that's called a set and then we go from for p in range sub 32 just because 2 to the 32 in python is pretty good you could do it on your language and whatever um so power of 2 to the p from 0 to 31 um so now we're going to get a number x and of course to be honest when i do if i do it in a contest i probably would do this in a i don't know but i've been trying to do things in a slicker way but every time i do it brings a slick away i've been doing it dumb so yeah so that's just you know now we have the power to let's convert to a string and then now we want to um we want to sort the um sort the string right so we can do a so we sort this and then we convert it back to string and then that's pretty much it we now then add this number to the lookup and then now for the input n we do the same thing where um okay let's actually define this as normalize uh of a number and we will return this thing roughly someone like that bless me excuse me technical difficulties oh yeah and then we could do a normalize of n as well and then we just return whether normalize of n is in lookup i think that should be good let's give it a go wish there's a quick button for this but yeah uh 10 16 23 46 55 i don't know this random number i think 24 is another one that they have but um but yeah let's give it a go let's see if this is good this looks okay let's give it a submit cool uh so what's the complexity of this well this will always take um 32 so you know and um and what's the weight i would say you know 32 is the number of bits so that will always take 32 and of course you can always actually um pre-calculate this like we actually um pre-calculate this like we actually um pre-calculate this like we can you know if we were to call it this function many times we actually would put this somewhere in memory so that we don't have to calculate it every time so then it's literally an or one lookup um we have to use the lookup is the of one but the normalize this is log n for where n is like it's log n where the log base is 10 because for each digit um you know when you stay each digit we have that number and then we sort it so it's going to be log n something like that uh and then we convert it back to string which is fine and yeah um but again you know uh this is going to be you know and so n is the input but n is not the input size is the number of bits and this is going to be i would say n log n where n is the input size this is very confusing actually saying and because n is the input n but n is not the input size right um because the input size is you know 32 bits or whatever it is and therefore it's 32.32 is the and therefore it's 32.32 is the and therefore it's 32.32 is the complexity of this algorithm um yeah and this is assuming that we have this on a lookup table and that's pretty much it in terms of space we again this is you know 32 um which is log n um not this end but linear size of the input um but again you just do it once right so yeah uh that's all i have i think let me know what you think hit the like button the subscribe button have a great rest of the weekend and i will see you tomorrow to good mental health bye
Reordered Power of 2
similar-string-groups
You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return `true` _if and only if we can do this so that the resulting number is a power of two_. **Example 1:** **Input:** n = 1 **Output:** true **Example 2:** **Input:** n = 10 **Output:** false **Constraints:** * `1 <= n <= 109`
null
Array,String,Depth-First Search,Breadth-First Search,Union Find
Hard
2276
152
hey guys welcome back to the channel today we're gonna solve lead code problem 152 maximum product sub array okay so um feel free to pause the video just to read through the problem and kind of get an understanding of what it's asking but i prefer explaining through the examples okay so given an array for example nums 2 3 negative 2 and 4. what is the maximum product i can get from zero a okay so obviously and it has to be of continuous integers so we can't say the maximum obviously the maximum is two times three times four but it's not contiguous because there's a number in between okay they have to be together and the maximum is just two and three because that's six okay because if we add this guy it becomes negative which is smaller and we can't add this guy because he's on the other side okay so it's pretty simple right pretty straightforward for this guy again the maximum you can possibly get is zero because zero is next to everyone we can pick two by himself we can pick one by itself because they're negative right next to an a1 zero is the highest okay we'll pick any number and so you have to pick the whole already okay so again the first thing i can think of okay let's get a word by path right now okay the first thing i can think of right is brute force okay let's use before so meaning if we're given theory in example one okay two three negative two and four what's the maximum possible i can get okay why don't we go through and figure out what is every possible argument i can get so the first one is to the maximum product of this guy is just then the next possible one i can get is two and three okay maximum product this guy is three then the next one like is six i'm sorry the next possible way i can guess two three negative two okay and this guy is one negative twelve okay we already know it's not gonna be this guy okay then the next one is two three negative two and four okay and this is what 12 multiplied by four i believe it's 48 so negative 48 okay it's not going to be this guy okay so the next one we can do is we can exclude this two okay and just three by itself actually counts okay he's just three okay then we can do three and negative two just negative six then we can do three negative two and four okay it's just negative 24. so you see where i'm going right the next guy can be negative two by himself okay he's just negative two so we can literally do for every possible combination of this area this is called the brute force method and this is kind of how we're gonna solve it first it's not the most efficient method however it works and i feel like it helps us understand the problem more so without further ado let's solve it using the brute force method first okay so first i'm going to define a function called uh call it max product okay match product and what if he takes a list okay so let's say pass for now okay and let's go ahead and create our driver code to call this function code so i'm just going to say noms i'm just going to use the exact example this guy's used so obviously we know if it's this we know to expect six to be the value okay then i'm gonna say print call the function okay now let's run it to make sure everything's okay it looks like everything should be okay but we'll see yeah okay return is not very good okay everything's okay so first step i'm gonna do is create a variable called maximum product or max plot for sure okay what do i wanna do i want to assign him to as low of a number i can possibly think of and you're going to see y in a little bit so i'm going to assign him to negative infinity okay so i assign him to negative infinity and as low of a possible number you can think of we can choose zero um zero might be fine but just in case of negatives but it's better to use negative infinity okay so now i want to iterate through this loop like i promised so for i in range okay let length of what of nouns okay so there's one two three four there's four items in here just to make sure let's just print um why okay just so we can kind of visualize like a bad we're praying everyone okay that's good so our follow-up is okay that's good so our follow-up is okay that's good so our follow-up is working correctly okay so what do we wanna do i'm gonna create a dummy variable called temp time temp list doesn't matter what you're calling this variable is actually useless but it's just more or less to show you guys what's going on but it doesn't actually add to our actual functionality of our code so now i'm going to create a second variable called current product so it's a current product this is actually useful i'll set an equal to one initially okay i set it to one okay so what do i want to do next i want to iterate again a second time through this array okay but i want to iterate in such a way that i'm not taking the same number twice okay so if i is on this guy okay if i zero i want to start from one okay so i don't take two by two okay and how do i wanna do it i just say four j in range okay what range i want to start from i like i said i don't want to take i so i okay so whatever i is that's where i start from right if i is here okay we start from whatever eyes and go onwards right okay to what to length okay we don't start from behind i guess if we've already compared one and three and we do two and three two four two if you've gone this way when we're this there's no point in us going from three back to two because we already we've already taken care of that so anyways we're gonna do again also noms okay so this is our second forward okay so now what do we want to do as we go through this i want to add to this template again this is this template is just less variable he doesn't add to the functionality of this code just so we can see what's going on okay so i want to append to him every time we go through the smaller so we can see what's going on okay what i want to add to him norms okay that's what i want to add into him okay every time okay then i also want to update my current product okay so what is my current product my controller is just the product of whatever he was before okay times the j i'm on for instance if we're on this guy and j is this guy okay it's just this what's like this okay and we'll keep going on okay so times norms of j i hope that's kind of making sense but again it all comes together at the end okay now i want to update my max prod okay max pro is the guy created at first right i want to update him okay now who's he gonna be he's just gonna be the maximum between himself max broad the value was before on our current product whatever is maximum or advice bigger making the maximum product so now once we have this now again like i said we're only doing this to visualize let's go ahead and make some prints okay but before we do that let's go ahead and uh return so at the end of this loop what should happen i should return my next part i think this should be correct for now let me go ahead and delete this space let's grab it again we're expecting six right like in the example six so that's correct right but let's see what happens let's print something so we can see what's actually going on so i'm going to add this print statement print what i want to print templates as we're going through this inner array okay and i also want to print the current product so we can see what the current product of each of those list is okay and also once we come out of this first loop in the second loop i want to print the max product of just the second once we're done with the array whatever the last part is so let's run in and see what happens looking good so like i explained boot first right we first start with two the product is two so we can see that you're two and next we have two and three products is six two and three product is six that's what we're printing in this line right here then two three and negative two products negative twelve just like we had on the paper then negative forty eight okay good with it then if you go through this once we've done through this because we've gone through this only one time right a maximum product of all this is six which is print max part which is what we're putting right here okay then next we pick up three okay we go with three bam we do the exact same thing maximum product which you go through here is also six it's still six because it was six before right but here we have six in this loop and we do it for the next guys again just we're going with this structure we come out and a maximum of stays six so this code works okay it works let's go ahead and see what need code thinks about this okay but before we do that let's go ahead and remove the spring statements because like we said they're not useful and let's go ahead and remove this temp list he was not useful we just created so we can visualize what was going on go ahead and remove this okay so this is the actual bread and butter the meats and potatoes of the code it works let's go ahead and take it and let it see what the code has to say to us okay let's go in let's paste it again what i like to do if i'm pasting only code i like to move everyone backwards move them back and then from this point i like to kind of like edit the guys so okay so i think it looks good let's go ahead and run let's see what happens when we run it okay accept it let's go ahead and submit it and see i think he might time out he might time it or he might be wrong let's see because again this is just a brute force method which is going through every single item exactly the time down let's see the details of the timeouts okay so whenever the input is disarray see how big it is so many items are in this array it times out okay so this solution is correct but it's not efficient because it doesn't meet any codes time limits so in part two of this video we're gonna solve it in a more efficient manner that's it for the video guys i hope it was helpful i'll see you in the next one
Maximum Product Subarray
maximum-product-subarray
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,3,-2,4\] **Output:** 6 **Explanation:** \[2,3\] has the largest product 6. **Example 2:** **Input:** nums = \[-2,0,-1\] **Output:** 0 **Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-10 <= nums[i] <= 10` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
null
Array,Dynamic Programming
Medium
53,198,238,628,713
62
everyone so today we are looking at lead code number 62 it's called unique paths and this is a classic dynamic programming problem that really focuses on a method called tabulation and once we kind of understand this we can actually solve this quite quickly but the way you want to think about this is you want to create a table and then fill in certain elements certain initial elements into that table and then you can figure out all the values for the rest of your table based off of those initial elements that's kind of how you want to get a mental model around these types of problems so let's take a look at the prompt here robot is liquid located at the top left corner of an m by n grid the robot can either move down or right at any point in time and the robot is trying to reach the bottom right of the corner of the grid marked finish how many possible unique pads are there so here we have our first example the input is m and it's three and it's a grid of three by seven and there are 28 different ways you can get to finish if that robot is moving right or down okay so let's kind of take a look at a conceptual overview of this so let's say our input is let's start small and let's say our input is um it's something simple like three by three okay so we have m equals three and n equals three so we have a very simple three by three grid okay so we'll do one two and three and then one two and 3. okay so what we want to do here is with any of these types of problems we want to figure out what are some initial values we can fill in to this grid and can we figure out the rest of the values based off of those initial values as we iterate over the grid so let's think about it this is where we need to get to and what are ways we can move well we can move right we can move across or we can move down so those are two initial values we know that one path will be going all the way right and one path can go all the way down so we can actually fill those in we can just fill those in with a one that is one way we can get to one way we can move and we can move all the way down now once we have these initial values filled in is there a way to calculate the rest of the grid based off of these initial values so let's think about it if we're trying to get here what are the different paths we can take well we can take one right and get here or we can take one down and get over here so there's two different ways fill that in that's 2 right there and if we look here another way to think about this is if we take this 1 here and we take this 1 and we just add those together we're going to get 2 here now we don't need to figure out the rest of the ways how to get to this cell right here we know there's two different ways to get to this cell and there's one way to get to this cell okay so now what we can do is that this cell right over here is just going to be the sum of 2 and 1 which is going to be 3. so again we know that there's two ways to get to this cell and there's one way to get to this cell so this cell will be three ways it will be the sum of two and three and again we can just fill out the entire grid just based off of that simple principle so here this will be three and then this will be six and six of course is the correct answer so it's once we kind of understand that basic concept it's actually not too bad okay so coding it up let's go ahead and move over here to the code so what we want to do first is just create our grid const table and we can just do um array.from array.from array.from we'll do a length of m and then we'll fill in each one of the rows with a new array of a length of n and all we're doing here is just go ahead and creating that two by two array right here our grid okay so now what next thing we want to do is we want to fill in the initial values so we can just iterate over uh over our grid so 4 let i equal 0 i is less than table dot length i plus and then we just want to fill in that initial value on that table so we can do table of i at zero is going to equal one and then here we can do four let i equals zero i is less than table of zero dot length i plus and then we can do table of uh 0 at index i is going to equal 1. okay so all we've done here is we've just gone ahead and filled in the ones here and filled in the ones on the column as well and so now we iterate over this 2d grid 4 let i equals 1 i is less than table.length i equals 1 i is less than table.length i equals 1 i is less than table.length and we're starting at 1 because we already filled in that initial value so we can start at one we can start at this point right there so table dot length i plus okay four let j equals one j is less than table of i dot length j plus and now we are here we just want to fill in this value which is just a sum of the cell above and the cell to the left of it so we can just do table of i j is going to equal table of i minus 1 j plus table of i j minus 1. and then we just go ahead and return the very last element in our table n minus 1 and table of n minus 1. okay and that's it's not too bad i think the main thing is when you come across these problems try to think of a grid or a table and what are initial values you can fill in to that table and can you move through that can you iterate through the table and use the values that are already in there to fill out the rest of them that's the key way to look at these dynamic programming problems and they become a lot easier and as you can see there's not a lot of code but you do want to make sure you think through all of this because it is easy to make mistakes but once you kind of get once you kind of have an understanding of what you want to do you can see there's actually not that much code that you have to write so that is not leak code number 62. hope you liked it and i'll see you on the next one
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
33
Share with your friends and condition poster and powder talk about very important question - above about very important question - above about very important question - above this question has been discussed many times on international, so today to explain it very well, the question is filter element in short and advocated by Ahmed Hafiz Editor Software and Along with this, I have given some examples here so that if you come here and see, then this address would be haunted, you are seeing that I wrote 300 later, the statement here was adjusted, it is possible that if it has been tweeted by two times, then it is possible. In the portion and 210 suited for 1000 means it is completely soft and terrific where it is considered so friends here near this position 1000 see this but those doing research on this should subscribe quote means travel all the elements and Like you get your element becomes its portion return to get enough like we are here we are looking for then hunter got this question so our one nourished this so your brute force inside this on you stupid and universities coconut we do less than I too Because you were dark, she was soft, we ever tightened, so we can take advantage of that thing, we know - then the result first know - then the result first know - then the result first tell the full gift Aurora flex and brightness, in the middle of that hotel here, you don't know what is your address from here to here Is it tight or frill, we have this question here but back to right there is no add on the topic, here it will take 1.5 time, it is no add on the topic, here it will take 1.5 time, it is no add on the topic, here it will take 1.5 time, it is ok, that is why it is a very favorite question of the interviewers because you are fitted with a modified bike. Many people had fought here many times, that is why there is a rumor that health experts are going to do it possible. So, let me tell you about it - the basic tell you about it - the basic tell you about it - the basic funda is going to go with it, if you know the middle element, then it is okay in the table. And after this we check whether it has a hotter hotspot than red chilli or not. How if the element on the left which is the first element is smaller than this element, now f551 is not lifted right here as you know. And this is the lifted reminder limit and because this element is smaller than this one mission, so I will make the first part short and right here, you will see this text message also, so the point on the left, this point is smaller than this plant limit, so I know. You can find out by going to the middle element, the left side is not there and one more thing, if the life part is not sorted then you can guarantee that the right part is fine and only because of this one, Pandey Khoon, this one. The part has reached you, there is no passport against it because it was rotated, it is ok, it is rotated, so if it is a lace part, then I am checking the fly water add password etc. How come I am telling you that it will go to you on Monday, so how much is ours - we go to you on Monday, so how much is ours - we go to you on Monday, so how much is ours - we can put it because Akhilesh's pipe is returning on him, he is getting shift at both the places, poetry recitation in which place, fear and our elements can be the partner with likes, then the partner on the left will go to the part, what should I do, then this one is there for him to remember you. The address is lifted twenty-20 and the time address is lifted twenty-20 and the time address is lifted twenty-20 and the time element is to point which is our her him her 6 Now I want to chart that our okay he is straight whatsapp recent ₹ 50 will he is straight whatsapp recent ₹ 50 will he is straight whatsapp recent ₹ 50 will do we will do from here till here we will check whether our element is that this If it likes in the range, then you will see that the hand should be bigger than 6250. It is small, which means it will be 6, so there will be no partner inside it is actually coming like a simreli. If we give an example, then if here we have father-in-law's rally of 513. I have here we have father-in-law's rally of 513. I have here we have father-in-law's rally of 513. I have 3 inches here, so now what will we do, first we will make pizza, if there is a cleft left in it, then the first point is that shoulder because Twenty-20 license fee means because Twenty-20 license fee means because Twenty-20 license fee means difficult for, there is no doubt that it is ours, do you like it or not? If it does, then we should select only the element which increases the hotspot by 120, if it is small, then it is not so. Right, this means our element and left, if it is not affected anywhere, then the entire left side will be cut off by this and from the right side, Bigg Boss. If you call a fashion diva, then this is the king's logic. Simran Jaiswal can see the example. Here I know whether our left part is sorted or the right part of ours which element is unsorted, so what is the condition of referring first, it is not the first lesson. Platform party leaders will know that the noose will be lifted from the right and will check that what we have to file is in the part which it does, that is, which is bigger than our 190 and smaller than our holiday train, then yes, it is so, then read this lesson. Call for and we will complete this part, okay, so every time I am looking left or right, if you are doing the complete credit card, then he will enjoy it and I am going to support him. Okay, you also think how it is going to be completed. And from the court you will get all the good things. Okay, you will consume Aslam. Okay, so I have made a spoon crown here, now I have made it in a straight way. Do you want to fold it in this way? Okay, so I have made it. Said that you got this and you got this, now you make its next point, if you get entries at this time, then iron or this is our dough Slide - 1st Chapter 01 - 4th, yours should go dough Slide - 1st Chapter 01 - 4th, yours should go dough Slide - 1st Chapter 01 - 4th, yours should go viral after that, tell this garlic, till then I will do all the tricks. Okay, so after visiting this example, I would have lit up, what I told you earlier, they are going to put it here, so only let's go, noble minded, it is a bit difficult, so many parts of a normal man, searchlight, this is so I am shocked here, so much lesson, human sister Shweta has become. First midding is done by width people during cyber to Jayanagar middle elementary when we return the mit portion will be modified a little bit below. Now below is the solar panel technical part of the modification. This is the part. If this one is commissioned, how do you do it? Left is if this is recognition rule means mails then how we are the first part okay this explained to you body that if this is low so we are miding on the side but 0123 45 the safety of then the media element will be our 0612 is a special guest so miding Or after we come here, we will check after legislation and eat yes how to solve twenty-20 lessons legislation and eat yes how to solve twenty-20 lessons legislation and eat yes how to solve twenty-20 lessons lifted and it is also visible in yes lifted up turn on do we believe that is why it is 50% then like it believe that is why it is 50% then like it believe that is why it is 50% then like it its scripters In this apps lock side, if it has increased from this twenty and also the smaller one in it, then see that 26 is not big, then these fields will go out, we will go inside this, we oregano was introduced in this post mount that we can say that If there are no side effects, this is Ireland, then it means that you can add this whole click and the next one - Moon Water people and the next one - Moon Water people and the next one - Moon Water people gathered there left ventricle and from our here till here - hot so we decided the left whole till here - hot so we decided the left whole till here - hot so we decided the left whole so I am the same here. But when it was looked down, it was already zero tight on the first places, your people were the same hero and high, our 16, which Media Khatri, now our loan place, Mithlesh, will withdraw from Aa Four till Road in Mithlesh, so if you subscribe this channel, you will get a little Do n't forget to subscribe Sa So this and this means towards nine knots then you can see this in your like right kirtan and attend 21 york nya good ok equal to this characterization of ours is found here see here also you will be able to open but Here I wrote in the note because if we first check with the media event then send a message here that if there is a condition, more people will be injured, Yasmin, then people will wake up, our net run rate will become that of a meadowlark, due to this, the villagers here will be informed about this. If nickel is too high then yes the label is too high, this cross section will be found only and only to 16 medium read so a video shifting this and to our channel and we click so let's do this set a reminder and while typing scanner 20% There will be more brothers who our 105 our 20% There will be more brothers who our 105 our 20% There will be more brothers who our 105 our 6 you see our three okay media our three home secretaries of Meghvar model and we for chakli volume element witch representatives 2017 in the middle so we 2017 oil is one percent in it so we the right part. Will do joint and we will open whatever is there, it will go to medium to high, chilli will go to 134, so let's first take the sex power to ours which ranges from Gujjars to America to Europe, has to write to it is 100ml, this one is fine for the criminal elements. It is equal to Tamil Nadu, it is not equal, let us check the part, if the hotspot is on the left, as well as this one, if the elements fight on the left, then take it there, when it likes, it is like this, then again today our tweet of this - is like this, then again today our tweet of this - is like this, then again today our tweet of this - 151 - 00 5000 and we will check and green 151 - 00 5000 and we will check and green 151 - 00 5000 and we will check and green chillies will also come along with it. Zero four media limit. Our element will be available. Okay, all of you friends are working in this manner while doing sexual acts. Fans have no right - doing sexual acts. Fans have no right - doing sexual acts. Fans have no right - You have to cook for 5 minutes like this. We know that for this whole thing, you should experience that point, if there is no element, then people do not subscribe to 10516 media world false channel, that is, if you subscribe to the channel, then subscribe that now come back, is the fiber more limited, is it equal to this? This is not at all equal, we are not at the level of chakli, it is not a nifty platform, so the password of sunlight is the one to enter the password of bright, if we apply pressure, then see, these lips do not respond, it means that the minute is fine, so this which Commit Sundha your in 5 minutes go for so no before every form now we will take out the belt in it so it is complete and you will check if it is equal to the middle element then it is secure then it is not equal so now we will come here if you for Admit Now see all of you people, this has been resolved, so here we are talking about the point, it is necessary to work the corner test properly, only then can this process be admitted, so these people, you are sixty years of marriage, your sixty is also coming. This is not admitted to what notice 1068 then you will come to the application Aishwarya Krishna if you go and gift situation was bigger than gas pipeline burst and - cyber cafe is bigger than gas pipeline burst and - cyber cafe is bigger than gas pipeline burst and - cyber cafe is small is equal then will give a mark here feeling that We are on the mark again - IS NOT BETTER THAN SIXTY So come - IS NOT BETTER THAN SIXTY So come - IS NOT BETTER THAN SIXTY So come together and I was at this place for a minute - together and I was at this place for a minute - together and I was at this place for a minute - This is your middle, your fore and this is polythene. Now look, you brothers of this one, there will be peace, take a little near this place. It is not like that, you see, it has been fried well, so like these people will come out, after this, Rawat is here to see you, I am ahead like you, the village people ran away, return minus one, okay and here will give you an option. From here till here it is closed and this settlement is seen after the end of the sleepers, meaning if you are not able to return from here then it means that all the international cricketers will not be able to return. The taste element is famous, so finally you are Came out of the files and - will you turn it on, there is you are Came out of the files and - will you turn it on, there is you are Came out of the files and - will you turn it on, there is no separate interest, okay, so this and this question is a very important question, I will show it to you guys, okay, understand it properly, we may have asked you many times about the walls of sweets, now we will talk about it. Inside, right before ending on Diwali, if you guys like this video then please like and subscribe, we will go to select bye.
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
216
hey everyone nitish's side hope you are doing good so let's start with the question so the question is combination sum three okay so there are question related combination sum and combination two so you can that you can check that out also so first we will check combinations on three so what is this we like find all valid combination of k numbers that sum up to n okay so you're given a k and you're given an n so you have to find out k numbers so sum is equal to n so such that the following conditions are true only number 1 through 9 are used okay and you can't use the same number again so each number is used at most once so what you have to return you have to written a list of all possible valid combination the list must not contain the same combination twice okay so the same element or the same you can say same sub list cannot be there and the conversation may return in any order there is no need to maintain any sequence okay so let's understand with an example okay so we have given this example k equal to 3 and our n is equal to 7 so what's the condition you can take only number from 1 to 9 and you can choose at most one okay only single element can be there no you can't take one at like three times if k is equal so you have k equal to three so that means you have three position one two three so and you need the sum of three of them is equal to seven okay so let's say i will take one here okay and if we take one we can't take the same number again so let's assume we'll take two here okay so after that we can't take one and two in this position so we have option of either we can choose from three to nine so let's say we choose three okay so if you do some three plus two plus one is six so this is not a good option so we will remove this we'll choose the next option so we have four okay so if you can see one plus two plus four is seven so this is one possible sub list we can take okay let's see whether we can take any other okay so after four if we do the sum like all will be greater than seven so let's change here okay so here we have position of two to nine okay so let's assume we will make it as three okay so one plus three and now let's assume we will put two here so one plus three plus two is again six okay and three we can't take because three is already taken so and if we do four so it will become eight so we only have this one possible output for this case okay so let's see within an example so we have again k equal to three so that means we have three position one two three and we need a sum as nine here but we have option either we can choose one to nine okay so like at every place we have the one to nine option but if we choose one number from here so we can't choose the same number again at this position so let's say we'll take one here we will take two and we can't take three if we take three it will become six if we take four it will become seven if it will if we will take five it will become eight let's say we'll take six so one plus two plus six is nine so this is the one possible output and there are other option also so you can see with an example so 1 plus 3 plus 5 is also one option 2 plus 3 plus 4 is equal to 9 okay and if we see the example 3 we have k equal to 4 okay but we need the sum as uh sorry sum s1 so let's say we'll take one but if we take any number uh with this which is not one it will give the sum greater than one so there is no valid uh sub list so we just written the empty list okay so i hope the question is clear to you let's see how we can okay so let's understand with the example two so we have k equal to three and we have n equal to nine so we have three position one two three so what we will do we will pick any number at a time and we'll go further okay so let's say we'll take one here now if we take one here we can't take one at the next position so let's assume we'll take two okay so now two will take and now we can't take one and two so let's say we'll take three so if we do the sum of them so three plus two plus one is six which is not equal to nine okay so what we will do we will backtrack from that position okay so we will change at this position so we'll remove this and we will just push one two and we'll put 4 okay now if we do the sum it will become 7 similarly it is also not equal to 9 after this we again backtrack we backtrack basically means we will remove the last element that is inserted because this is not giving us output and our k is also filled if let's say we have k equal to 4 so then we'll go further but here we just like our k is also full and our sum is also not become 9 that means we have to roll back again it's not written so we will roll back and we'll put 5 here so it will be 8 again this is not equal to so we'll again roll back and we got 1 2 6 say which is equal to 9 okay so like this is the one combination we got after this if we increase our basically this value if we put 7 this sum will become like greater than the given sum so what we will do we will not go further than this we'll just return at this position okay so it means now you have to backtrack this position this you have done by two you create the combination now you have to backtrack okay so how will you do so you will make this three like this will remain at the same position and you will again do the position for this so you can't take one here you can't take you will take you can take two here so we'll take two and three plus two plus one is 6 okay but this is not equal to 9 so we'll roll back this we'll put 3 we can't put 3 here we'll put 4 so 4 plus 3 is 7 plus 1 is 8 which is also not 9 so we'll change okay we again change it we'll make five okay so one plus three plus five is nine and which is equal to nine so we got our output this is the second possible okay after this let's say we'll increase okay if we increase this will come six one plus three plus six is ten so we don't need to move further when we get our possible output okay so now you again roll back at this position you will come at this position you have one now you will put four okay similarly and now you will put two here so by this you will change every time like you will go through with this then again you roll back and you will change this position similarly when you like reach to nine after this you like try all the combination then you come back at this position and you make it as two and you make all the combinations so as you can see this is the one more combination two plus three plus four this can be also a valid option okay so it's just a normal backtracking question so what we have to do every time we will take a element we will insert it and we'll solve the question if we were not able to solve we will just backtrack from that point okay so it will be more clear if we write the code for okay so let's see let's create a global list of list so we don't have to pass in every function okay list equal to new error list and we'll just return that list okay let's call the solve function and let me give the k and let me give the n also and let's create a sub list also okay so let's get in teacher sub list equal to new array list okay so now we'll solve our function so avoid solve and k and n and list of integer sublist okay so this will be our base case in recursion and we will have a recursive three okay so what we will do uh we only have option from one to nine so we'll loop over it so for we have this option only for enter equal to one two i will go to nine and i plus okay so what we have to do either we will take it so first step we will take it so sublist dot add will take i and we'll call our recursion function so what we will do so let's say we will take this so if we take this uh we will decrement our k okay so we'll do k minus 1 and we'll also reduce our sum we'll do n minus i and we'll pass this sub list okay now the back tracking strip making strip so what we need to do let's say after doing this you will able to solve or you will not able to solve you have to traverse all the path or all the direction so you will remove it now you will let's assume you will take one here so for the next time you will take two at that position so we will remove the last element that we just inserted size minus one okay so i think we have done with the recursive tree so let's write the base case so what will be our base case so how we can check whether we got the valid input so valid input is only possible when you're so when let me explain you here so as you can see this is a valid input because one plus two plus four is equal to seven so that means our k is full and there's some s7 so if i do the vice versa that means if i decrement it from 7 minus 4 minus 2 minus 1 their n should be 0 and their k is also 0 which means all values are filled okay so what we will check if n is equal to zero and k is also zero then you have to do something okay else uh let me just write if n is less than zero or k is less than zero then just written from here you don't have to do anything okay so if both are equal then you have to insert it in your list so list dot add sub list okay and we just do written okay so there is a problem at this 13 line the problem is if you just do list or that sub list so what you are doing it every time you are inserting at the sub list and every time you are removing it okay so if you insert into the list like it will insert it reference list reference so every time when you update or delete it will basically it will not have a any element that is that will represent that particular valid uh sub list so what we will do we'll create a new error list of that type because in list we are storing our reference if we store the value then it's different but here it's a reference okay so let's i think we have covered all the cases let's run it okay let's see so we are getting a wrong answer and why i'm get like why i show you this wrong answer there is a reason okay so what is the reason you can see like one is at that like all are possibly valid output but they are having a one thing wrong like each number is used at most once which we are not following as you can see 5 plus 1 is also 7 but 1 is repeating here similarly if you can see for five one two three two all are seven but the same digit is repeated so what we need to do we need to pass one more thing here okay so we'll pass start basically from where you have to start okay so it's like we will take a start so at every time you don't have to start from one you have to start from i you should be start from start and let's say you will take one integer at a time so next time you can't again like pass here you don't have to pass start okay you have to pass here i plus one so the same element will not come again okay so now let's run it this time i think it will be yeah so this giving the correct output let's submit it okay cool our code is submitted the time complexity is you can say it's a order of like we are doing for loop another inside that we are calling a recursion function so you can say it's a n square but it's just a nine of loop okay so we have only have i one to nine so it's a order of n nine into n you can say and it's on an average it's our order of n so yeah hope you like it thank you for watching and do join the telegram group if you're in any doubt and in concern thank you
Combination Sum III
combination-sum-iii
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true: * Only numbers `1` through `9` are used. * Each number is used **at most once**. Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order. **Example 1:** **Input:** k = 3, n = 7 **Output:** \[\[1,2,4\]\] **Explanation:** 1 + 2 + 4 = 7 There are no other valid combinations. **Example 2:** **Input:** k = 3, n = 9 **Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\] **Explanation:** 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. **Example 3:** **Input:** k = 4, n = 1 **Output:** \[\] **Explanation:** There are no valid combinations. Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. **Constraints:** * `2 <= k <= 9` * `1 <= n <= 60`
null
Array,Backtracking
Medium
39
98
Hello Everyone So In This Video Before Going To Discuss A Problem Valid Binary Search Tree So Let's See What The Problems And Use This Problem Governor Taaseer Wali Channel Don't Forget To Subscribe And Subscribe Button And Notes Person Do This Superhit Number Liquid 1 Six Speed Look Select It's Really Musalla Factory 425 Site Contains Only Notes With Flute Notes Key Subscribe And Similarly The Rights Of Lord Vishnu Decided To Aaj Shoot Contains Only Notes With This Great Arvind A Notes Key Sonth From Britain 60 Left Be Late Because Android has greater dangers to proper taste for all the notes to hear Buddha left and right subscribe button 6th same page 48 to 15 798 notes in the loop subscribe to that NSC got votes right all the notes Richa Tubelight should have greater than not valid for Available in this property Tasty Big Guide Body VHP and Subscribe to that 428 Vinod A Notes in the Laptop Emotional Notes Value Flu 6 to Samay Jab 1994 Channel Subscribe Must Subscribe and subscribe Video then subscribe to the Page if you that Films Se Belt BST Note Far Left Sardar Notes Value Android Note 4 Greater Than Not Value But Still From Where Did Not A Valid Bases Soft Features Problem 98143 Subscribe Button President C The President Of Forest 60406 Sudhir And Information In The Mid Valley Between Us Subscribe Meanwhile Notes Shift six digits definitely not the minimum balance Tweet - Infinity And the minimum balance Tweet - Infinity And the minimum balance Tweet - Infinity And Share And Subscribe Like This Is Too Connect With Greater Than - Infinity And Connect With Greater Than - Infinity And Connect With Greater Than - Infinity And Definition Of Infinity Sudhir Reason Main Surakshit Ko Tools Life Electron Note For Vote Bhi To Possible Rains Par 400 For This Is Not Have any valid point where there was destroyed evidence six coffees lying on the left side maximum value 406 absolute minimum value b - infinity only 406 absolute minimum value b - infinity only 406 absolute minimum value b - infinity only for jain minority status for the president 60406 subscribe and interact with no invalid subscribe The Video then subscribe to The Amazing 6 Ki Loot cases in hand mixer in the year when it's going right The value of 86 The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing spider-man Changes are there Amazing spider-man Changes are there Amazing spider-man Changes are there yesterday morning Neetu's recorded number It is true Voters Referee E M &amp; Women SIM Surya Pisces Voters Referee E M &amp; Women SIM Surya Pisces Voters Referee E M &amp; Women SIM Surya Pisces WhatsApp President Professor Cutting Secretary Veer Change The Language Subscribe Don't forget to subscribe my channel and subscribe to Yudhishtar Range is late since affair going in this direction witch android vote only withdrawal from media Subscribe and changes will not withdraw cases changes share and subscribe right side subscribe se char subscribe 21 a main safe bhi like this is that from four wheel drive andar rights of free beneficial for human rights including maximum 10 m tow here me sava 6 sava 5 Se 6 Min Changes to Front Value End Change 240 Se Z Important Hero Kaise Transfer 600 800th Urs Half Midning 6806 Daily Return Forms Will Send You A Daily Basis For This To- For This To- For This To- Do List Check The Like This Is Not Like Share This Info Lata Mangeshkar Distance From This Not Against A Greater Than 6000 Did Not Match Winner Tree And Withdraw 1972 10 Minutes 600 Click This Subscribe Button And Don't Forget To Subscribe To My Channel Pims Returning A Bullion Value Statement That Were Destroyed The British Rule Where Is The Best This is it is gold subscribe channel must subscribe liked The Video then subscribe to The Amazing channel do n't forget to subscribe and subscribe who is the present value and where going towards right to recall and valid squid don't like share subscribe button changes The Video then subscribe to the Page if you liked The Video then subscribe to Main Maths Hair Fruit Balance Garlic and Equal to Men They can return for cars in the 12th Plan To-Do List Will Provide Jobs for This Channel Subscribe 6 View from the Root Rooted as Like This From - Infinitive Like This From - Infinitive Like This From - Infinitive for interior value Wipro middling hair long maintain long max subah college various methoded which has long been value and long max value against values will be - infinitive will be - infinitive will be - infinitive 250 and long hidden Treasure and attracting someone love you can provide minimum and maximum long will the government in the long don't like this favorite with values ​​from the long don't like this favorite with values ​​from the tehsildar later moving ahead roots rotting hormone donal bisht condition weak 240 to z 12512 longman value which is the best app So the plant condition comes to give falls on 12345 10 ranges are valid 9 we are going to the laptop 500 years in this duration you two to two cash withdrawal on Thursday 1000 from left side subscribe my channel improve also one more Maithil Doctor Add Like This Vivo v5 Root Divert Root Point To Note Thursday 21st Co Rotting Hormone Equal Donal Pradesh Condition Comes To Give Falls Through 12628 Loosening To Make Idli 12205 Subscribe To Tweet - A Native And Such To Tweet - A Native And Such To Tweet - A Native And Such Improvement Diplo Condition Is Weakness Falls If you do n't wash then liquid liner eighth line number 1090 subscribe me to whenever bandanwar madonna call set no root bellcomes one fruit with lack a main women same is 2.5 inches from next to 1968 condition to be rooted s ko chot lies between - infinitive 250 chot lies between - infinitive 250 chot lies between - infinitive 250 maxis to state condition rudrapur this 12512 - infinity hai na dha na ki henry chair surya passport arrange for 12th like this and forest b ki like this what is this point every thing is fine no will go to observe this were going to college will attend Passing in root divert root canal in the last 2 years old living this is it has happened in dubai one more me download all set to here no root will be null ko shuru this point internal so wherever bhi international k the vinod editing and 20 k soft Directly Return True Tagible Donal All Return True Love You Can See Hidden From Every Year They Loot Lo Uttar Pradesh Remote Control Tractor Exhibition For Entries Dear And Love Is Well At Midnight No. 86 From Line No. 8 And As Well As The Written Must Subscribe Like This point so a welcome back 2 F 2 and hear you can see from the left side with your default value added no point in points right return forms of any value directly not a valid tasty synovial fluid not a valid tasty subscribe and subscribe the Channel and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to admin Changes to Front Value Episode Mein Parv Will See How To Look At Key Judgment Madam Call Back With Root Will Bhi Nominal Vikas Bhi Hai 128 Right Now Be Quiet With Truth About Right Hero That They Vote Side It's Subscribe And Change Now Assigned To Noida Route Is Point Internal Sadhe Sab Sadhe Returned From Near May The Subject Matter Will Be Removed From The Call Stack Exhibition For Every Sphere And Starts Admission Helpline Number 90 Routes One Sudhir And Subscribe Like This Is A Proof Smudge 2014 This One Node From Subscribe Must Subscribe Directly Returns The Video then subscribe to the Page if you liked The Video then Value True From Where There Will Be Sent To The Left His Life But Come True And Acid Roots to Roots Welcome back to note so one check the left side you to-do and one check the left side you to-do and one check the left side you to-do and subscribe channel subscribe now to receive new updates reviews liquid liner 2009 acid vikram7 bluetooth write maximum 10m and changes loot lo notice not equal donal message condition Come to forms root value is note but that person is excited in that 210 subscribe 502 100 subscribe is but you can see 7 cigarettes daily way to make such white this condition improves Sudhir and condition can not to withdraw it is not different from 2nd subscribe and subscribe the Video then subscribe to subscribe and Share Thank you liked The Video then subscribe to Like this software also receive true and from various forms for when will proceed from left form internet or any other person directly Returns The Video then subscribe to The Amazing spider-man Thursday Must Subscribe Welcome Back From Year A Super State Bazaar From Left Only Also Recent For Not For Note 510 Loop Sub Tree Return Default Value Sweden Falls On Recent Falls Evidence For Beating The Retreat To Develop BSP Will Return subscribe The Channel Please subscribe and Share subscribe and subscribe the invalid to the same condition Must subscribe this channel History literature in the swift That man is greater than that Vijay must develop a greater than incomplete lies between To complete the missions Channel Don't Forget To Subscribe Thursday That Root Welcome To Nal Hai Nustam Will Be 213 Lee Ki Roti Record On Also Been Written True Swayam Admin Returns Through Able To Remote Control Time Exhibition For Every Year Will Start From Line Number 8 To 10 Minutes Return True To Life In True Love That Android Came Back To Three Mere Latest Roop Subha Ghotu At Site Wizard 20K Swift Updater Line Number 90 A Penis Balance Method Will Be In Contact With New Root Canal Which Were Going Towards Right Fruit Come Seervi Hai Play List On Line Number 1090 Acid True Value Through Share And Back To Three Lee 120 Value Right This Witch Directly Returned Value Evolve Points Pet Means Loot Jewelry Must Subscribe 2014 Sweden Subscribe Must Subscribe To Tomorrow Morning Richer Expansion Disbalance Metro Line Number 10 Years Later Written Update Route Comes From National Record True Value Which Of This Is The Value Of Route Will Return True Jai Hind Is Sweater Liquid Form Line Number 8 Wickets Private Colleges Will Attend Passing Through Don't Left Believe This And This Is Well In The written true information through left root comes back to the loot I left values ​​through I left values ​​through I left values ​​through super does not fit seized at its left atrium plate laptop returns values ​​through atrium plate laptop returns values ​​through atrium plate laptop returns values ​​through one of us are going towards right to recall and validation five Android were going to the west macrame this Rich Man The Day When They Got Right 6000 Value In Which Is The 12125 subscribe The Amazing spider-man spider-man spider-man Se Channel Subscribe Number Is That He Will Go To Italy And Country Three Note Sunao Ka Swaroop Come Here Key Roots Not Equal Donal 625 Ki And Max That Subodh Condition Comes To Gifts Novgorod Tour Laptops For Colleges Will Attend Passing Through Water Live Wallpaper Koi Dal Fame And Remains The Same With Fame Actress 228 367 On One Yesterday Morning Rather Off And I Little Tomorrow State With Root Personal Will Not When You Love A Women Remains Same Next Changes to Roots Rally Reason Trend Also Be Directly One Will Start From Line Number 80 Feel Receive Karo Root Comes Back to 6 I Let This Be True That Pranav Goes to the Height of Sex We Update Line Number Here with Just 120 Days New Delhi One More Is Valid Message Put Contact With Root Canal Proposal When To Daughters Day Ne Thursday Veer Torch Shuru Tangible Tune Also A 320 K Britain True Directly Exhibition Appointment Should Be Taken Will Start From Line Number 90 Sudhir And 16 Android Subscribe Don't forget to subscribe my channel Under the thumbs up You can see from the left world True that from Rate items All received Ru like this fennel as root of this binary tree Hit seasoned from its left side Receive true and from British rule and five Daru No Deposit Bonus Of Lord Even Lord And Directly Through subscribe to the Page if you liked The Video then subscribe To My Channel Please subscribe and Never Miss न
Validate Binary Search Tree
validate-binary-search-tree
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_. A **valid BST** is defined as follows: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[2,1,3\] **Output:** true **Example 2:** **Input:** root = \[5,1,4,null,null,3,6\] **Output:** false **Explanation:** The root node's value is 5 but its right child's value is 4. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,501
1,920
hi guys welcome to algorithms Made Easy my name is kushboo and in this video we are going to see the question build array from permutation so this is an easy tag question but we are going to solve it with the follower so stay tuned and watch the video till the end now let's go through the question once given a zero based permutation nums which is zero indexed build an array answer of the same length where answer of 5 is equal to nums of I for each 0 less than irises nums of length and we need to return that array a zero based permutation of nums is an array of distinct integers from 0 to nums dot length minus 1 which is all inclusive so over here we are given two examples let's go through one of them the input is given which has 6 length and the numbers that are there in the area are from 0 till 5 that is nums dot length minus 1. so you are given some permutation of these numbers and you need to Output another permutation this permutation is going to be built based on this particular condition wherein answer of I is equal to nums of I so over here we are given in the explanation that the zeroth position will contain nums of 0 which becomes nums of 0 itself and that is 0 nums of 1 that is this first index answer would be nums of fun now this nums of fun can be replaced with 2 and nums of 2 is nothing but this one so numbers of 2 is 1 and the second position gets filled with one similarly we need to fill all the other elements as well so the second index will become nums of 2 which is nums of 1 that is equivalent to 2 so this 2 gets filled over here the third one is nums of three now nums of three is five and nums of five is four so four goes at the third position for the fourth one nums of four when nums of four is three so nums of three which is five gets filled in the fourth position and for the last one we have nums of five and number five has the number four so nums of four is three and so three gets filled over here so this is the way that we are going to fill the array now we are also given some constraints with this question wherein the length of this array is going to be from 1 till thousand so numbers are going to range from 0 till 999. and the elements are always going to be distinct so these are the conditions that are given to us and there is a follow-up with this as and there is a follow-up with this as and there is a follow-up with this as well that can you solve it without using an extra space that is in over one space so first let's try to go it in The Brute Force way and then we'll see the follow-up answer for this follow-up answer for this follow-up answer for this so for the Brute Force it's very simple we are given the equation with us and we just need to write a code that is going to take in that equation and build the answer so over here we are going to take a result array and we are going to Loop in and we are just going to fill the result array that's it and return the result so this is a very simple brute for solution let's try to run this it's giving a perfect result and if you submit it gets submitted the time complexity over here is O of n because we are going to have a for Loop and we are going for all the elements in that array and we are creating a new resultant array so the space complexity over here also becomes o of n now given in the description follower can you solve it without using an extra space so now let's go ahead and deep dive on how we can reduce the space complexity for this problem let's take the first example that was given to us wherein these are the indexes and these are the values for those indexes so till now we have understood what the question demands from us that is we are going to build another array which is going to contain output which is nothing but these values over here so what we need to have in order to get to this point the first thing that we need to have is the original array elements that is the nums of zero one two three four five and the second thing that we need is the nums of this one so we also need the nums of 0 which we got from this nums of 2 which we got from over here nums of 1 which comes from here numbers of 5 3 and so on so at a particular point we should be able to derive this and this values that's clear so we need two values at each and every position with us now if we try changing the values without keeping in mind that we may need that value somewhere in the future we will end up corrupting the data and will not be able to recover the values so now how would you not hamper the original data yet add the new data into the array so let's go through the constraints again the nums dot length constraint is from 1 till thousand and so we'll focus on this particular part of the constraint 1000 means that we still have the capacity to utilize the bits in the integer which means if you write a binary representation for this particular integer there will be some bits that are still unused and will always remain unused because Beyond thousand there is no number that is going so in order to keep both the datas with us we are going to somehow use the space that is not used in the integer let's suppose this was a string array instead of an integer array it would have been very simple because we could have appended something for example 0 underscore 2 and then we could have separated those values based on the separator that is underscore since this is an integer it's a slightly tricky thing to append the values now how can you append these values you know that you need to go beyond thousands so there would be some multiple that you need to take into account and there are two numbers A and B so what are those multiplication and addition numbers that we are going to have those are nothing but the numbers that we are going to keep into that one particular meta information and some constant that we can use to amplify that number so that we can identify that this number has already been manipulated and doesn't need any manipulation now so this is the equation that we can use num1 will be one of these number either the 0 or this 0. some constant will look into it what constant we can have num2 is going to be one of the numbers which is say the after value that we are going to put into this array so that is going to consider this whole thing which is nothing but the 0 1 2 4 5 3. how do you recover the data now that we will see ahead for now let's see what this constant can be now this constant can be a fairly large number a prime number which is again beyond the array that is given to us or the bounds of the array so simply put it is something larger which goes beyond this particular array so say this is of length 6 you can take something like 6 plus 1 that is going beyond the array now this whole equation is nothing but the meta information that contains my previous and my after value so we'll take that as a meta now from that to get the first number we will be doing this meta value modulus of this constant why because when you divide this number by this particular constant you will get some value which is going to be the second number and since you have added some random data into it the modulus of it that is the remainder of it will give you the number one and number two will be the division simply the division with the constant that you are going to use so these are the ways in which you can recover your first and the second number from the aggregation of these numbers so what can these num1 and num to be number one can be the numbers of I and num2 can be nums of I so this is going to be my original data and this is going to be my after value or the resultant data so for this I am going to use a division operation and for nums of I am going to use a modulus operation so now that we have everything with us all the equations with us all the knowledge with us let's go ahead and do the dry run so this is my original array and over here this is the equation that was there let's consider this nums of i as a this as a constant and this as a b that is a resultant value now this constant over here is one zero one why because array size or my bounds are from 0 till 1000 so I have taken a larger value than what bounds were given to me so this is going to be fine or else you can also use the prime number which is larger than thousand or you can also take the length of this array plus one so n plus 1 as this particular C value as well so now that we have all the data over here which is the a b and c value so let's go and do a dry run on this particular example for the zeroth value we have a as nums of 0 which is 0. b as nums of 0 which is nums of this 0 which is again 0. so 0 plus this equation gives us 0. so let's go in and fill it that becomes 0. moving on to the next value now this is nums of 1 which is nothing but 2 and nums of 1 that is nums of 2 is nothing but 1. so the equation becomes 2 plus thousand and one into one which is one zero three and that comes into this position now for the third value this becomes nums of 2 which is 1 nums of 2 which is nothing but nums of 1. now over here we have already modified this particular data so what are you going to do are you going to use this no because this is not the actual value so we cannot use one zero three directly we need to take the value 2 out from that and then use it so how do you take this original nums of I from this we saw in the equation that modulus will give this particular value so we are going to do the modulus operation on this with the constant that we are going to take that will give us the original value for this particular data and that is 2. so instead of directly using this nums of 2 we are always going to use the value which is this value modulus with the constant and that will always save us from the mistake of using the value which is already been calculated or which is beyond the bounds of the array so using this equation we'll get 1 plus 1001 into 2 which is equivalent to two zero three and that goes over here similarly we go and find out the third index value which is nothing but 5 plus 4 into 2001 which is four zero nine similarly we'll go ahead and fill in the fourth one which is nums of 4 that is 3 nums of 3 which is this mod one zero one which is 5 that is if you divide it will be divided by 4 that is four zero four and the remainder will be 5 so this becomes 5 and when you do this it becomes 3 plus 5005 which is l08 over here similarly we are going to fill the last value as well and this value becomes three zero seven now one round of filling the array with the meta value which contains both the value is done now is this the answer that we were looking for no it contains both the values we need to get the after value which we needed so we'll again run one more Loop over this and then we'll see what are the resultant values that we are going to get so now the result for this particular data will be given by this meta value divided by the constant that we use because that is the value B now why are we dividing this we are dividing this because this was the original number and this was the number that we were supposed to Output but since it is multiplied by this particular constant to get the number we are going to divide it so the meta value that is there divided by this constant will give us the actual required data so if you fill this will give you the array now this divided by the constant will give you 1 and remainder as 2 which is nothing but the original value this value divided by my constant will give me 2 plus 1 as a remainder this will give me 4 plus 5 as a remainder 5 plus 3 as a remainder 3 plus 4 as a remainder so we do not want to do anything with the remainder we just want the number that we got from dividing the values and this is nothing but our resultant array that we need to return so in two iterations without using an extra space but modifying the same array we can achieve a of one memory efficiency for this particular question so now that we know everything about this let's go ahead and code it out so let's just remove all the code that we wrote earlier and now we are going to write a new code so over here since it is of one space solution we do not need any extra array we are just going to Loop in twice to get the result so initially let's first take the value for the constant in a variable and now we are going to go and form the intermediate array so for that we will start putting the meta information into the num set for clarity let's take a few variables so a is going to be the original number and B is going to be nums of I which is nums of a now my 10th value or The Meta value is going to be a plus B multiplied by constant value and as we saw in our example as well that this B will at some point contain the modified value so to extract the actual value we are going to take a modulus with the constant that we are using over here and this will give me the temp value now the nums of I is nothing but 10. so instead of taking this temp variable I can simply put this in numbers of I and this can move out so this is the intermediate array that we were talking about and now we'll take one more for Loop and this will actually convert this temporary array into a resultant array so my nums of I now becomes nums of I by my constitute so we can even write this and that's it we can return the num's eye and this is going to be a dot let's try to run this it is giving a perfect result let's submit this and it got submitted so the time complexity over here still stays the same which is O of N and the space complexity has reduced from o of n to O of 1 because we are just modifying the input array that is given to us so that's it for this question I hope you like the solution if you did please do hit that like button and do subscribe to our Channel and if you have any thoughts or comments please do Post those in the comment section below and if you have any other question that you want us to make a video do post that as well in the comments and we'll try to pick it up as soon as possible thank you for watching see you in the next one foreign
Build Array from Permutation
determine-color-of-a-chessboard-square
Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**). **Example 1:** **Input:** nums = \[0,2,1,5,3,4\] **Output:** \[0,1,2,4,5,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[0\], nums\[2\], nums\[1\], nums\[5\], nums\[3\], nums\[4\]\] = \[0,1,2,4,5,3\] **Example 2:** **Input:** nums = \[5,0,1,2,3,4\] **Output:** \[4,5,0,1,2,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[5\], nums\[0\], nums\[1\], nums\[2\], nums\[3\], nums\[4\]\] = \[4,5,0,1,2,3\] **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < nums.length` * The elements in `nums` are **distinct**. **Follow-up:** Can you solve it without using an extra space (i.e., `O(1)` memory)?
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
Math,String
Easy
null
963
hey what's up guys chung here again so today let's continue uh on this minimum array rectangle problem number two here so i believe a few days back i we discussed about the minimum array rectangle number one so now this time let's take a look uh number two and if you guys still remember in the number one everything else are the same okay the only difference is for the in the number one is the uh other lines all the lines uh that consists of a rectangle has to be either uh vertical or horizontal okay so in that problem you know it's a little bit easier in my opinion because in that problem you know we have we i think i believe we use two solutions the first one is the uh we fix two points here we fix two points and then since and with these two points okay p1 and p3 we can easily find the p2 and p4 okay so that's the first approach we use and second approach was the uh was remembering all the uh out of vertical lines here okay basically we were using like a hash table to store all the vertical lines and it's like and with all these vertical lines also for each of the vertical lines we also use another hash table to store its latest x coordinates so that we can scan it right that's a two approaching here that's sorry that was the those are where the two approach for the first rectangle problem but for well here since the rectangle can be uh can be rotated right in either direction so um so we cannot basically we cannot like use the two points right to fix that basically our first approach for this problem is that we have to find still okay we find the first uh we find first two uh points and then we'll try to use the uh the pythagoras theorem to find the third one to find the third point okay and this is a third point okay with the third point then it's easier we can find the fourth point i will any i mean i can show you guys uh how can we find the first point by using three points later on but let's try to find the three points first okay cool okay so i think first i'm going to define like uh like hyper functions you know to help me calculate the distance okay between two points like p1 and p2 here and basically the distance i'm calculating here is the you know the p1.0 okay minus the p1.0 okay minus the p1.0 okay minus p2 p20 the first x the difference of x and i'm gonna do a power of two plus same thing p one dot one minus p two one the second element of p two still and then i'm gonna do a return here return d okay that's pretty straightforward and then the first thing is just a brutal force uh basically we either through other points okay and we either we find the two points first and then we then start the third point and then by using the first three point we can find uh the fourth point okay so uh let's see so the answer is this okay system dot maximum right and then p1 okay in p1 in points okay and then for p2 in points okay uh yeah let's see actually maybe it's we can use that scene technique to reduce the amount of points we are like we are never mind let me finish this one first let me finish the real brutal force version here so basically if p1 equals to p2 okay we simply continue okay because we don't want to find we need four different points okay so now we have two points now let's find the third point okay if p3 is in uh for p3 in points so first if p1 equals to p3 or p or p2 is equal to p3 okay we continue else what how can we know if the third point is the point we need to know that's why we use we need to use the uh pythagoras theorem right we need to know if those two the distance between p1 and p2 basically if the a squared plus b squared equals to c square that's when we can tell okay so we have a 90 degree angle okay between the p1 p2 and p2 p3 okay so basically if the distance right up between the p1 and p2 plus right distance of the p2 p3 not it's not equal to the distance okay it's not equal to distance p1 and p3 okay so if that's the case we also continue right basically that's this p3 is not the node we uh the third point we are looking for here and okay so now if the third point is there okay if we have find the third point now here comes the trick so how can we find the fourth point so here's the uh the trick basically you know the x1 basically the x1 uh plus x3 equals to the x2 plus x4 and y1 plus y3 equals to the y2 plus what y4 you know let's say there are like four points here okay there's a one two three and four so no matter how we rotate this rectangle these two formulas always stays true you can try it right i mean this is one two three and four okay in this case it's like uh one two three and four yeah there i think there is like a formula or you can look some something up let me try to find these things here for you guys okay so i found this website here let me drag it to here so basically this is the website i mean where you can uh basically you can play around with it so that you can understand why this why that's uh that equation uh always oh it's true it's always true okay you can drag it right and drag it wherever you whatever you want but and there's like some more explanation on this one to explain the uh the relationship between those two points here between those four points not two points sorry cool coming back here right since we have this formula here right we have this like equation then with three points find we can simply find the fourth point okay now the x4 will be what will be the p1 okay 0 plus p3 0 minus p 2 0 okay same thing for the y4 right so for the y4 here p1 1 p3 1 p2 1 okay so now we just need to look for if x4 and y4 is in the points okay uh if it's in the points then we simply do an array right we simply do a we do area equals what we do what we can utilize this method but the only difference oh sorry so we can basically the two side right it's going to be uh the distance between the p1 and p2 okay times distance of the p2 dot p3 yeah p2 p3 but remember we have a square result right that's why we have to do a we have to use this squirt i mean so we have to use this square foot method to get the actual length okay square foot here okay and then we simply update right uh do a minimum of update answer dot area okay and then we can simply return the answer here answer of course if the answer is smaller than the system dot maximum right else austere zero yeah i think this should just work okay let's try to run this now let's see uh p3 if p1 p2 p3 continue maybe here maybe the uh if area is greater than zero then we update okay let's see yeah i think i know uh what went wrong so here i'm using like uh a set but in the points here it's a list not a set so what we need to do here we have to convert these points to a point set not only we can just use this set but also when we're looking for those points right we're looking for those points it we can uh sorry when we doing this fourth point look up here we don't have to scan the whole list since we're converting to a set then it's going to be o1 so we're going to improve that improve the runtime here basically here um p 0 okay dot p 1. for p in points okay here point set and then point set okay so i think here we can remove these things here okay let's try to run it again at least the test case passed submit you know i believe these things it will tle because uh oops no it didn't tle okay surprise okay i thought it was tle because the time comply stays it's like it's gonna be a what uh un square right basically we have a first loop here second loop and then the third loop i thought it would tle but it barely passed okay i think one of the uh one of the improvements we can do is we can do a scene like just like what we did in the first rectangle problem you know so every time we have a point here okay we add it we add this one to the scene like this you know uh like scene dot at uh add p1 okay and here we just do a scene okay piece yeah so that we incrementally we slowly increasing the size of the out of the scene here okay i think this should also work let's try it okay submit yes it is it's much faster you know but still the percentage didn't change much but the runtime does did decrease a lot so basically you know what we're doing here instead of course uh for the first loop we have to loop through all the other points but for the second and the third loop here i mean we don't have to look through everything right because we just need to know like what we just need to loop the points that we have seen before that's why i'm using this scene set right to improve this uh because now because the first time we only have one two three and four so not so it's not just strictly uh unsc and uh it's not strictly n to the power of three okay it's uh maybe it's n uh to the power of 2.5 n uh to the power of 2.5 n uh to the power of 2.5 or something like that you know basically by using the same here we can improve the performance by a lot okay cool so i think that's pretty much the first approach here i mean it's kind of straightforward right the only thing you need you guys need to understand basically two things first you guys need to know the uh the pythagoras theorem so that we can use this one to find our third point and here basically find third point and then more importantly that's how we find the fourth point okay and once we have our fourth point all it's left is just to calculate the area and then compare with the answer cool so that's the first approach okay it's still like a it's still like uh n cubed right so even though it's like better perform better than n cubed but i believe it's still bounded to n cube okay so let's try another way let's try another solution here okay so another solution is the uh you know it's by using the uh the center point of those two diagonals you know if you guys remember the uh the rectangle problem one is like always uh like this right so that so basically there's only one possibilities of the two diagonals right that's the only part the only possibilities of those two diagonals but with this like kind of uh the problem number two here those two diagonals i mean they can be rotated basically as long as the center point doesn't change okay those two diagonals can rotate to any direction okay so they can rotate like this i mean right and they can also rotate somewhere here okay so then basically this is one of the rectangle okay and this is also one of the rectangle basically there are there's going to be unlimited like in infinite number of squares that's this two these two diagonals can be formed okay so that's how we are going to find our four points here um yeah so the way we're going to do here is we are we're gonna use like uh also a hash set right we're gonna use a hashtag to find to maintain right to maintain the uh out to maintain each of the diagonals that's uh every two points can form okay basically we have like this list of points right so basically each two points can form like uh essentially can form a diagonal okay basically so that's why we're gonna loop through all the combinations of the two points and with each two points we can find the basically the length of diagonals okay and then we and we can also find the point right the middle point of the diagonal that's why we're gonna use those two things as a key right to as a key to store each of the diagonal lines here and then um yeah and then once we have those the hashtag table hashtag map then we can loop through the hashtag map right we'll be finding we're so basically we're trying to find uh the two lines the two diagonal lines which who has the same center point middle point and the same length then we know okay so the points for those two diagonals are the are one of the candidates we need to form like rectangles okay so let's try that basically uh still we need this like we need these things here we need this uh distance to help us define the uh the distance and then uh we need a diagonal diagonals default uh default dictionary okay so the list so why i'm using a list here because you know with the same center point like the and also the same length right we're gonna have we might have different pairs okay we may have different pairs of the notes here for example here if we have a if we also have like notes here like somewhere here and here right then with these two things i believe those two pairs of notes will have the same center point and the same length of diagonal so with the same center point the same like and the same length of the diagonals of the point pair we're going to store them into the same list here so that later on we can simply loop through the pairs with the same key okay so uh for uh i can range so we're gonna have like a length of the points here uh for j in range uh and um sorry i plus 1 to n okay that's how we iterate all the combinations all the two combinations of the two points okay uh so p1 equals to uh p sorry points i okay and then p2 equals to point j okay so the center x right the center x equals to the p1 what's the center x is p 1 0 plus p 2 0 and divided by 2 okay so we need a parenthesis here okay same thing for the center y here right so for center y we have a p one plus p two one divided by two okay now the this the distance right or the length we can call it the length is the uh distance basic distance between the p1 and p2 okay and we're using or remember this length is like us uh the power us uh the square of the actual length but doesn't really matter we just need a like unique value that can be a part of the key so it doesn't really matter if you do a square foot or like just use this like the square version uh yeah um now the uh we have a i goodnose okay so now we have all the keys we need the first one is the center x the x and y and then what the length okay that's the three keys okay and then we do append right pan to what p1 and p and p2 okay so that's how we maintain the hash set of the diagonals as long as i mean as long as those three parts are the same then we know okay so those all the points right all the points will be uh will be able to form like a rectangle because they are have they have the same uh diagonals with the same length and the same center position now we simply need we just simply need to uh eat it through all the all uh points with the same key okay so answer equals this uh max size okay for key i'm going to use the key here in die diagonals okay so with the key we have the points uh points pair points per list right equals to the uh the diagonals key so here is storing all the pairs with the same diagonal key right and then we're going to have like a length here uh like n1 equals to the point the length so why we're doing this thing here because we only will continue if the n1 is greater than one right so why we're doing this track because let's say if there's only one pair if there is only one pair with the same uh same diagonal key here it means that there's only p1 and p2 here right so there i there won't there aren't any there isn't any other points that can help the p1 and p2 to form the rectangle here that's why we're going to check if there's only one pair then there's no way we can form like a rectangle okay so if the n if the pair number is greater than one then we know okay we can try all the possible pairs okay so for i in range and one okay and for j in range like i plus one dot and one okay now we have all the points here we have p1 equals what this thing uh i zero okay and we have p2 p3 p4 okay p1 p2 is this i1 p3 is j 0 and p4 is j 1. okay so basically this is a p1p2 this is a p3 and p4 okay so now what's the area here right so the error rates it's kind of obvious right the area is like the square footage square foot of the distance uh from p p1 to p3 times square foot of the distance of the p1 and p4 okay then same thing answer equals to the minimum of answer dot area okay and then uh same return here okay yeah run submit cool see this one is much faster okay it's much faster it's even you know uh the worst case scenario i mean this thing it should be like uh at least it's an n square right yeah i think so and for this solution is n squared because uh for to calculate the diagonals hashtag here i will look through all the nodes here all the points so that's n square and then here we uh we're looking through all the keys here i mean here the key here is much smaller seems like the test cases they're given here has a lot of there's a lot of rectangles and then actually the set the size of the diagonals it will be much smaller and this here is definitely uh smaller than n square yeah and so this one is the most expensive part cool so basically that's the second solution here all right i know this video is kind of long and probably not that clearly explained but i just want to show you guys like the two different uh two different type of the rectangle problem the first one is the it's not the rotated version the second one is rotated version so for the rotated version there are like two ways you can find those four points okay the first one is find the points one by one find the first one second one and then use the pythagoras theorem to find the third points and then use this like the relationships to find the fourth point which is the n-cubed time complexity which is the n-cubed time complexity which is the n-cubed time complexity and the second one is it's much faster because we pre-built the much faster because we pre-built the much faster because we pre-built the diagonals basically we use the diagonals diagonal lines to find to fix the two points and with the same diagonal lines then we know okay uh those two pairs can form like a rectangle and which is much faster cool guys i think that's it for this problem yeah thank you so much for watching the video and stay tuned guys see you soon bye
Minimum Area Rectangle II
three-equal-parts
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** points = \[\[1,2\],\[2,1\],\[1,0\],\[0,1\]\] **Output:** 2.00000 **Explanation:** The minimum area rectangle occurs at \[1,2\],\[2,1\],\[1,0\],\[0,1\], with an area of 2. **Example 2:** **Input:** points = \[\[0,1\],\[2,1\],\[1,1\],\[1,0\],\[2,0\]\] **Output:** 1.00000 **Explanation:** The minimum area rectangle occurs at \[1,0\],\[1,1\],\[2,1\],\[2,0\], with an area of 1. **Example 3:** **Input:** points = \[\[0,3\],\[1,2\],\[3,1\],\[1,3\],\[2,1\]\] **Output:** 0 **Explanation:** There is no possible rectangle to form from these points. **Constraints:** * `1 <= points.length <= 50` * `points[i].length == 2` * `0 <= xi, yi <= 4 * 104` * All the given points are **unique**.
null
Array,Math
Hard
null
67
okay let's up to this problem this 67 add binary we've been given two binary numbers in their string confirm that we should return their summation and also in binary string format so the input of both knowing every and contains only characters of one is zero so we don't need to verify that these strings are actually you know if we remove the quotation they are valid binary numbers basically what this line is saying so the example here we get 1 and 1 so when we add this two together 1 plus 1 is 1 we're going to carry 1 and we have the 0 in that position we have 1 plus 1 this 1 plus we don't have any teachers here but we have one carry so 1 plus 1 we get 1 0 here so it's 1 0 and the second example we got 1 0 adding that to 1 0 1 the result we get has 1 0 1 so it's a one digit longer than these two things it's the same for this one here so to cut this up the most straightforward a way to do it is just to simulate how humans would do this binary number additions so let's use the second example as an example to show that how human will actually solve this problem let's say that we want to add this to a number together so the way that we do binary number addition this is too similar to what we do with decimals we add the digits in the sin will align the number the two number first and we add the digits in the same location but the overflow happens at 2 right there this at this particular location is around 1 when we add those two together we get 1 and there is no overflow no carry when we got on this to number 1 the result is two but two exists is it's bigger than or equal to 2 so we have overflow we have a zero in this specific position then we have one more carry let's just carry us another additional number there we've got a 1 here and in the very last location we got a 1 0 and the overflow 1 here so the result is 1 0 1 so that's how we do the binary not to a number adding two binary numbers together as a human so the most straightforward to code this problem is to simulate this process we align this two numbers we iterate them from the right hand side towards the left and we use the one thing use something to keep track of the carry and use some kind of a collection to collect all these individual digits kills and in the end we try to piece all this stuff together us return that as final result so that's the pretty much the approach the anytime has space complexity in terms of that both of those are equal to in the order of the maximun lens of there's two input strings because you can see here the number of additions that we need to do operation we need to is upper bounded by the maximum length of the one of the input numbers and the space is just to hold the hold of the result which is also equal to the maximum length of this two number really add 1 as the additional carry there that's the time of space complexity so let's quickly put this question up so us so we went duping those two things in their reverse order for the character a and character B and zipping is two things we reverse a we reverse those two actually we should use this I think it's a tools has a zip longest what this zipping does is to have an option to pad the shorter ones with whatever default body will get submissive life so look example here one when we add this to in the regular zip we would be terminated at this location you know just after the only one calculation because the shorter ones only have one and it did return it but for the longest we can pad this shorter ones with zero this is just to some convenient functionalities you can always prepare up by yourself and I just take the lens of the two strings and pad the shorter ones with zeros but this is just a little bit more convenient yeah and it reads just like English you know for this two digits we zip in this two strings you know that we reversed order and we pad whatever the smaller one was zeros in you know to the left then we should do the calculation the carry and lender int convert this string characters char into integer numbers so that we can do additions plus the previous carry divide that by 2 the we take the carry and reminder from this deep lot then the remainder is going to go in our collection in this case I want something I can append to the left so we use a deck that gets basically a double linked a list doubly linked really yeah double illegally Lister so we can insert for left or right you can use lists as well just regular default so something shipped directly out of the box but when you append to the right I imagine that in the end you have to do a reversal so we add a reminder to the result and finally if the car is nonzero so even though we exhausted all the digisphere we don't have any addition of this happening but we have one additional carry we should also add that to the result and of course carries starts with zero so we don't have any sort of like a dent in the calculation and in the end that we should just return the stringbuilder concatenating everything together join but we have to cast every element from integers into strings so that's we yeah we use this string function to convert every element in result into strings and just concatenate them all together so this should be now our algorithm let's see let's do some final checking if I have anything wrong it looks all good to me so let's try submit and see what happens okay it works yeah so this is the one of the method of solving this problem just try to basically implement the way that people would human would do this binary number auditions we add numbers you know bit by bit and that's how to solve it let's talk about another approach so another approach I guess is if you know it you know if you don't know it and there's no hint on that's what exactly the that's what the interviewer is wanted then you're going to be stuck in there the other way of doing it is to using the bit little bit and manipulations so what we can see here is that just take this example here as well just to do a binary number addition without you know using actual addition we can do that with I think it's a very exclusive all and the leftist shift the rationale is that the exclusive all here like a 0 &amp; 1 here at exclusive all here like a 0 &amp; 1 here at exclusive all here like a 0 &amp; 1 here at the last position the exclusive all is just gonna be 1 so if we have 1 + 1 the just gonna be 1 so if we have 1 + 1 the just gonna be 1 so if we have 1 + 1 the exclusive all s 0 so basically exclusive all gives the reminder and an operation if you have two ones that's the only case you will get I want or remain in case you get you're gonna get at zero this gives the punk shifter that I shifted and if you do this I shifted that to left once you get to the let's say that correct Akari and like the example here I would basically we if we treat these carriers something like you know zero one zero we in sexually are adding things we especially at doing editions of this to number then the result the remainder result have to do another addition with this carry number and then we have to use the remainder result to do another additional addition with this carried number so that's just you kind of need a loop to do this we additionally result the termination criterion just had to you no longer have any carry number in there so basically you can treat this second number as a carry and the first thing as a reminder so let's cut this up we first to convert this two numbers into binary integers and while we still have some kind of carry number the second number we treat that us carry what we do is to you know the a is the reminder that's the exclusive all and the B is going to be the shifted version laughter carry the tractor carry so that's a B and we let that to the two left of one by one position and then in the end we should return what is that we should return the binary string representation of a I think Python has s 0 2 in front 0 B in found to indicate the string yes binary so we don't need that indicator so we should just return this let's see if it works yeah I think so yeah it's actually faster but somehow it's taking us using more memory but this number I don't know it might be just some kind of overhead or wreden initiations I also noticed that the runtime number also varies a lot by difference by runs yeah so don't take this thing too seriously you should always analyzing the time that space complexity for this by itself yeah so on that regard let's talk about think about what kind of time complexity we need for this thing so for this I'm not sure if it's the maximal ends of this - for an hour straight for this - for an hour straight for this - for an hour straight for different plantation it's the simulation I said it's very clear that it's equal to the maximum length of this but for this one it's actually hard to think about the time complexity it appears to me that it's you should be longer because this is what a little bit is since that it's taking more but uh I don't just ride out of my hand know the number so yeah I'll look it up and try to think about and maybe post a comments down there or if you know I think um believe a comment that would be very helpful so that's the question for today thank you very much
Add Binary
add-binary
Given two binary strings `a` and `b`, return _their sum as a binary string_. **Example 1:** **Input:** a = "11", b = "1" **Output:** "100" **Example 2:** **Input:** a = "1010", b = "1011" **Output:** "10101" **Constraints:** * `1 <= a.length, b.length <= 104` * `a` and `b` consist only of `'0'` or `'1'` characters. * Each string does not contain leading zeros except for the zero itself.
null
Math,String,Bit Manipulation,Simulation
Easy
2,43,66,1031
187
welcome to this video now we're going to solve a liquid problem 187 repeated dna sequences and this is a medium level of problem all dna is composed of a series of nucleotides abbreviated as ac z and t for example this string when starting dna it is sometimes useful to identify repeated sequences within the dna write a function to find all the 10 letter long sequences that means sub strings that occur more than once in a dna molecule for example if we are given this a string we have to return then we have to return this to substring of length 10 and this two substring repeated twice in the given string here we see it's repeated twice this strings here it's repeated and here we see c so 5 c and 5 a so it's means this string and this repeated here so it's repeated twice so we have to return this to string and for this given strings we see that we have all a letter and in this strings this string repeated twice okay so for this given string we have to return this substring of length 10 on the lead chord side we see that if we are given this string then we have to return this to substring of length 10 okay and we have to written this as a list now let's see how we can solve this problem if we're given this a string then we can generate substring of length 10 from this given string so this is a substring of length 10 here this is a substring of length 10 again this is a substring of length 10 and so on okay and here this is a substring of length 10 and so on and so forth okay we can generate all of the substring shown on the screen of length 10 and among the substring we see two sub strings that appears more than once okay let's find out them all right here these soft things and this substring they appear straight and this substring appears twice in this list okay so we have to return the substring that appears more than once okay in the list we see these two sub strings appears more than once so we have to return the two sub strings as a list so we will return this list when we have input these strings we can solve this problem using hashmap and also you can solve this problem using set let's see first how we can solve this problem using hashmap then we will see how can solve this problem using set now we're going to go through the intuition of hash map solution first we're going to construct a hash map as key the substrings and as value the appearance of the substrings these two strings appears twice in the list and all other strings appears once okay so we use your dot to represent all the strings that appears want now what we're gonna do we're going to check the value for the key if we see the value is more than once for a substring in the hash map then we'll add that substring to the list so we have here two sub strings this substring and this substring so we'll add the two substring to the list okay this is the list will return and this is how we can solve this problem the solution will takes big of n time complexity where it is the length of the given strings and it will also takes big off in space complexity to construct the hashmap now let's see how we can solve this problem using set now we're going to go through the intuition for hash set we can generate all the substrings of length 10 we see here now what we're going to do we're going to construct a set and then we're going to add every single substrings of length 10 to the set first we have this substring okay and this substring appears to right and this substring appears to it then we're going to represent all the substrings that appears once in this list by dot okay and we'll add all the substring to the set and then we'll add this substring then we have also and we'll add all the substring to the set and we're going to represent all the substring that appears once by dot and then whenever we reach to this string here we see this is already exist in our set so we'll add that to our list okay we'll add that to our list and then when you reach to this substring then we see it exist in our set so we'll add to our list okay so finally we will return this list the solution will takes big of end time complexity and it also takes bigger of in space complexity to construct the set and this is how we can solve this problem this isn't that much difficult problem to understand now let's see the code for this problem now we're going to see the code for hashmap solution now i'm going to write the java code using hash map first let's construct hashmap map as key string and as value integer okay map equals to new hash map now let's insert the substring to the hash map with their appearance for int i equals to 0 i less than s dot length minus 10 i plus now let's generate substring of length 10 string substring equals to s dot sub string from i to i plus 10 okay for first iteration it will generate substring from 0 to 10 for next iteration from 1 to 11 and so on now let's insert the substring to the hash map with their appearance math dot put the substring then math.get or default then math.get or default then math.get or default substring zero plot one and this is the code to construct our hashmap now let's iterate through the key of our hashmap and then we'll check if the value for substring is greater than one then we'll add to our list and then we'll return that list okay list it will only store string list equals to new array list now let's iterate through the key of our hash set math dot entry string and integer item okay is item of our hashmap has two property key and value now map dot entry set now we're gonna check if item dot get value is greater than one then we'll add the key to the list okay add item dot get key okay and at the end we'll return the list now let's submit this code and let's see if it works oh sorry here we should have equal submit it again okay we see the code is now working and this is the solution for hashmap now let's see the solution using set now we're going to solve this problem using set let's construct set the set will store only string then name set equals to new hash set another set string it will store our answer the list of substring that we needs to return hash set now we're going to run a for loop for int i equals to 0 i less than equals to s dot length minus 10 i plus now let's generate the substring of length 10 substring equals to s dot sub string from i to i plus 10 now we're going to check if set dot contains the substring if the substring exist in the set then what we'll do we'll add the substring to the list dot add substring else if not then what we're going to do we're going to add the substring to our set dot add substring and then we will return new array list and here we're converting the set list to error list okay now let's submit this code and let's see if it works this is the code using hash set all right guys this is the solution to this problem all right guys if you want more video like this subscribe to the channel like this video share this video and stay tuned with cs ninja i'll see you in the next video
Repeated DNA Sequences
repeated-dna-sequences
The **DNA sequence** is composed of a series of nucleotides abbreviated as `'A'`, `'C'`, `'G'`, and `'T'`. * For example, `"ACGAATTCCG "` is a **DNA sequence**. When studying **DNA**, it is useful to identify repeated sequences within the DNA. Given a string `s` that represents a **DNA sequence**, return all the **`10`\-letter-long** sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in **any order**. **Example 1:** **Input:** s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" **Output:** \["AAAAACCCCC","CCCCCAAAAA"\] **Example 2:** **Input:** s = "AAAAAAAAAAAAA" **Output:** \["AAAAAAAAAA"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'A'`, `'C'`, `'G'`, or `'T'`.
null
Hash Table,String,Bit Manipulation,Sliding Window,Rolling Hash,Hash Function
Medium
null
1,004
Hello Vipin Pandey Challenge And With Just One Day Away From Getting The Dawn Electronic Solve Veer Subscribe And Do Question Self Explanatory Notes PDF To Word This Word For Example Which Nothing But Do Not Wash subscribe and subscribe the Channel subscribe that without maths diet slide presentation at after creative commons attribution 2.5 at after creative commons attribution 2.5 at after creative commons attribution 2.5 approach with all these questions on the mexican cigarette once reel solution list code 100 the selected cm name on latest wedding decoration airport is something like this 11000 forces to e will use this point Approach and have not done fuel rule with respect one and aligned with another point according to 08150 element with oo a second day is this is the volume of the current and axis 0 click here with attention subscribe will simply click then increase a video clip That by one and will move ahead the end points again on the question is my current element at index is the value of the world channel Subscribe Liquid You are able to move from the subscribe And subscribe The Amazing Subscribe This select 60 will create vegetable name FD which does nothing but left account which stores fog against will do any consideration a long gap see will keep another with absolute will store and answer is a slap chat start with edition key and power limited tried all the taxes 012 to a three course of 160 Report element which has it index this will improve that and along with knowing that he will check the who is on Instagram and start and its one under appointed updated on that all content in this will move ahead and accounts how to who is the current length This 2 - 22 - 829 is the current length This 2 - 22 - 829 is the current length This 2 - 22 - 829 Language Video To A Blind Limit We Have Check How Many Elements Of Winter Fest At Least Count zero-width Will Update Subscribe Button To zero-width Will Update Subscribe Button To zero-width Will Update Subscribe Button To One Will Update FootWwl Subscribe Now To Receive A Plate Country The Process Who Is The Current Element With Hearts And Pointer Is A Row And Again Will Check The Best Account Is Loot Ki Or Not Listen To Me To Subscribe To The Page If You Liked The Video Then Subscribe To Subscribe Our Me Bikaner Element With Hubs And Axis 10 Foot Account Is To- Do is not lose Axis 10 Foot Account Is To- Do is not lose Axis 10 Foot Account Is To- Do is not lose his condition has not given water logging and subscribe to 220 time will remove that point on hit the current website inductive width of its one to continue Vikram reduce the a slap account subjected to work and will there start point to Back Side Reaction subscribe this Hair subscribe Free blind man again this lineage sexual language bilaspur one super this week case end left continuous key end is point * floor and value eggs end is point * floor and value eggs end is point * floor and value eggs 0518 subscribe to subscribe and subscribe 15 - 3 this To-do so on this day again will not 15 - 3 this To-do so on this day again will not 15 - 3 this To-do so on this day again will not update includes goo now in half an hour which process suggestion comment element and index of wave video2 a six 16 - feminine 16 - feminine 16 - feminine 200 will not update on maximum this bell icon this element witch heats 60 will avoid points of 217 Seven - 380 divine secretion for a difficult Seven - 380 divine secretion for a difficult Seven - 380 divine secretion for a difficult fluid will not be updated on that Bihar were most from 0.5 Vidron in middle and were most from 0.5 Vidron in middle and were most from 0.5 Vidron in middle and victims pain updated on a shrinking increase fit available Edison a scientist that and - do it is not see this six sexual that and - do it is not see this six sexual that and - do it is not see this six sexual synthroid updated on that And Connect With Latest Has Account Is Also Like Video Description Is Not Dual Subscribe To 2018 Subscribe From Three To Four Subscribe One Plate Continues To Process FD Account Victims Equal To One From Twitter Earth Is Video D Option Recording Element Health Related 100 Feet Account Is Loot ke sirf but what they will update subscribe to the page that Ritesh nothing but a link 20 - 5th floor soe points 240 se z 20 - 5th floor soe points 240 se z 20 - 5th floor soe points 240 se z subscribe to subscribe our updated that now these bodhak acid answers will fix I hope you understand the great Indian the report In the department which is not visible and invisible maximum is real under-51 computer under-51 computer under-51 computer so let's check weather hormone twist and after not limit with limits condition was different elements and active Video subscribe this Video subscribe Video Ko Ki Agar Wife Abhi Best All The Lord Tips End Tricks Tips Subscribe This Video Long Updated On That In The Family Check The Con Is Mean By End - Start Voice Of Previous Muslim - Start Voice Of Previous Muslim - Start Voice Of Previous Muslim Samsung Electronics Limit A Time Complexity Of course Interesting And Drop Fuel 10 Complexities Of The Subjects Of Mode Of That IF YOU WANT TO DAYS SESSION LIQUID PLEASE DON'T FORGET TO LIKE SHARE AND SUBSCRIBE TO R CHANNEL THANKS FOR GIVING US ANOTHER GREAT HIT A PIVOTAL MARO THAT A
Max Consecutive Ones III
least-operators-to-express-number
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s. **Example 1:** **Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2 **Output:** 6 **Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. **Example 2:** **Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3 **Output:** 10 **Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`. * `0 <= k <= nums.length`
null
Math,Dynamic Programming
Hard
null
1,881
hey everybody this is larry this is me going over q2 of the weekly contest 243 maximum value after insertion which is actually now that i read that out loud it sounds a little uh sounds like an innuendo but anyway hit the like button there's a subscribe button join me on discord and you know let's chat about this problem and the title um but yeah so they actually you know it actually becomes two problems um because this is a maximum value sure but with the negative value then your essentially converts it to the minimum value right um and the idea is going to be greedy and i really should have got this food but uh this but basically you have say some number and you're adding any digit um the quick way of thinking about it is that yeah so you just kind of go from left to right you try to first place okay this is random try the first place where you can insert this to become better right and so it you know you can kind of try in a way you're boot forcing it but um but you're trying to do it in a implementationally intelligent way so you try to try this first um and then you know that's not gonna be the biggest maybe because you know that this is gonna be the biggest or bigger and then so forth and then dot you know you move to just ford right and then from that it's about spotting the pattern of okay well you know if i'm inserting say a four it never makes sense to you know in the prefix if i see a five obviously you want that to be in the front and basically that's the idea that you keep going and that's pretty much it and yeah and for the negative number is the opposite because you're minimizing it so basically you start from the beginning and you try to get the first number where it is less than it um try to draw it out but basically um the idea is just comparing all these things but in a very uh straightforward way um so that's basically my implementation um and because if you do it naively the length of n is going to matter because the length of n is 10 to the fifth but if you're able to do you know because if you are actually complain comparing strings you know constructed strings every time it's going to be n squared but this will allow it to be oh and in a greedy kind of way um i thought i did this pretty quickly but i got two wrong answers on this one i'm not gonna lie because i was watching it too much um and i didn't think it through what happened to the eco so my first and second implementation had ego signs but i only removed it in one place uh and that's all i got two wrong answers so today was not my day but yeah but as you can see this is linear time and linear space because we reconstruct the string um and yeah and if it can't find anything where this is the case you i just returned the i just put it all the way at the end um yeah that's all i have for this one again let me know what you think uh and you can watch me stop it live and stumble on it now during the contest maximum value okay oh this is a positive number then we insert it here so foreign hmm okay so what's the minimum wire otherwise minimum um did i mess up the order whoops i was thinking about that but i wasn't sure i guess i should have checked it more hold it on this one then oh wow i am really bad today the three we added to the tree but that's no good okay so i made that mistake on both places silly mistakes and also i can see now my new answer is that the same yeah okay really chef thought that for a little bit instead of wasting 10 minutes on penalties uh yeah so this was a rough contest and day for me so yeah uh hit the like button and hit the subscribe and show me some love uh and hopefully it will bounce back uh as i explain more problems but i hope you all have a good night have a good long weekend and i will see y'all later bye
Maximum Value after Insertion
closest-subsequence-sum
You are given a very large integer `n`, represented as a string,​​​​​​ and an integer digit `x`. The digits in `n` and the digit `x` are in the **inclusive** range `[1, 9]`, and `n` may represent a **negative** number. You want to **maximize** `n`**'s numerical value** by inserting `x` anywhere in the decimal representation of `n`​​​​​​. You **cannot** insert `x` to the left of the negative sign. * For example, if `n = 73` and `x = 6`, it would be best to insert it between `7` and `3`, making `n = 763`. * If `n = -55` and `x = 2`, it would be best to insert it before the first `5`, making `n = -255`. Return _a string representing the **maximum** value of_ `n`_​​​​​​ after the insertion_. **Example 1:** **Input:** n = "99 ", x = 9 **Output:** "999 " **Explanation:** The result is the same regardless of where you insert 9. **Example 2:** **Input:** n = "-13 ", x = 2 **Output:** "-123 " **Explanation:** You can make n one of {-213, -123, -132}, and the largest of those three is -123. **Constraints:** * `1 <= n.length <= 105` * `1 <= x <= 9` * The digits in `n`​​​ are in the range `[1, 9]`. * `n` is a valid representation of an integer. * In the case of a negative `n`,​​​​​​ it will begin with `'-'`.
The naive solution is to check all possible subsequences. This works in O(2^n). Divide the array into two parts of nearly is equal size. Consider all subsets of one part and make a list of all possible subset sums and sort this list. Consider all subsets of the other part, and for each one, let its sum = x, do binary search to get the nearest possible value to goal - x in the first part.
Array,Two Pointers,Dynamic Programming,Bit Manipulation,Bitmask
Hard
2108,2162
299
hi i am ayushi rawat and welcome to my channel today we will discuss the september lead code challenge day 10 problem bulls and cows now let's have a look at the problem statement you are playing the following bulls and cows game with your friend you write down a number and ask your friend to guess what's the number each time your friend makes a guess you provide a hint that indicates how many digits in the set guess match your secret number exactly in both digits and position called as bulls and how many digits match the secret number but locate in the wrong position called as cows your friend will use successive guesses and hints eventually derive the secret number write a function to return a hint according to the secret number and friends guess use a to indicate the bulls and b to indicate the cows please note that both secret number and friends guess may contain duplicate digits okay here's a link provided in the question that redirects to the wikipedia page of bulls and cows problem if you wish you can have a look moving on let's understand this with the help of an example i've taken the secret number as 1 2 3 4 and the first case as 1 3 0 2 so now we have to return the hint here the answer will be 1 a 2 b why because a is bulls and b is caused okay so we have one a here that is because one digit one matches the digit also and holds the correct position and three and two matches the digit but holds wrong position so that is one bull and two cows that leads us to 1 a and 2 b now let's look at the provided example secret number is 1 8 0 seven and guess is seven eight one zero so the answer should be one a three b why because one bull and three cows the bull is eight that is eight is in the correct position and the cows are 0 1 7 that is the digits are correct but are in the wrong position same goes for the second example secret number is 1 2 3 and the first guess is 0 triple 1 here our output will be 1 a and 1 b that is one bull and one curve note you may assume that the secret number and your friends guess only contain digits and their lengths are always equal it will become more clearer to you once we code now let's quickly dive into the code let's initially take bulls and cows as zero and now we will declare two lists here new guess and new secret next we will run a for loop over length of secret you can also take case because as mentioned in the node the length is equal now we will check for condition if secret of i is equals to guess of i then we will append bulls y1 otherwise we will append secret of i to new secret and we will append guess of i to the new guess now we will run another for loop on new guest list and check if the key is in new secret if the key is found in new secret then we will append cows by one if keys found a new secret we appended cows by one therefore now we'll remove that key from new secret at the end we will return bulls and cows make sure you enter the correct format now let's try running our code now let's try submitting it and it's done if you wish to connect with me on other social platforms the link is mentioned in the description box below you can find the code for lead code challenge solution in my github repository the link is mentioned in the description box below if you have any queries or suggestions feel free to reach out to me if you like the video hit the like button and subscribe my channel thank you for watching
Bulls and Cows
bulls-and-cows
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: * The number of "bulls ", which are digits in the guess that are in the correct position. * The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls. Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_. The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits. **Example 1:** **Input:** secret = "1807 ", guess = "7810 " **Output:** "1A3B " **Explanation:** Bulls are connected with a '|' and cows are underlined: "1807 " | "7810 " **Example 2:** **Input:** secret = "1123 ", guess = "0111 " **Output:** "1A1B " **Explanation:** Bulls are connected with a '|' and cows are underlined: "1123 " "1123 " | or | "0111 " "0111 " Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. **Constraints:** * `1 <= secret.length, guess.length <= 1000` * `secret.length == guess.length` * `secret` and `guess` consist of digits only.
null
Hash Table,String,Counting
Medium
null
1,523
hi everyone my name is steve today we're going to go through a very simple question it's actually very easy but just there is some logic that you need to sort it out to solve this problem but that's it let's take a look so problem 1523 count all numbers in that interval range so given two non-active integers low and so given two non-active integers low and so given two non-active integers low and high it's asking us to return the count of odd numbers between low and high inclusive for example three and seven these are the two bounds and between these two bounds there are three odd numbers that is three five and seven another example is eight and ten there's only one which is nine between eight and ten eight nine ten there's only one odd number which is nine a very beautiful solution is that we can just account there's how many total numbers are there which is absurd that's very silly so we of course we're not going to go through that way um another approach is that we can use high minus low that's going to give us the total number within this range but that includes both odd and even numbers so a very simple intuition which is going to lead us to we can use that difference divided by two will that always be correct no it's not always there are a few cases that we need to consider let's take a look for example if this is three and seven so it's very straightforward just three four five six seven so a total of five numbers winning this range inclusive and the odd numbers are three five and seven so total that is three right but we know the difference between these two boundaries is seven minus three that is four divided by 2 that is 2 right so but we actually have 3 odd numbers so that is an edge case or like a different case it might not be an edge case it might be one of the regular cases another example is 8 and 10. both of these two boundaries the even numbers so 8 9 10 minus 8 is 2. so 2 divided by 2 is 1 so there's only one odd number which is 9. this is the regular more regular case if we just take the difference divide the difference by two third case which is low is seven high is ten so this is an odd number the lower boundary is odd number and higher boundary is an even number so seven eight nine 10 all numbers are 7 and 9. so there's two numbers here so 10 but the difference between the two boundaries 10 divided by 10 minus 7 is 3 divided by 2 is 1. integer division in any programming language should be 3 divided by 2 is 1. so but this the number of odd numbers are 2. so this one is kind of similar to this case so let's see is there any anything similar between the first case and the third case there is one similarity that we can find is there is an odd number in this range in the limit in the boundaries right for example this one both the low and high boundaries they both have the odd number as the boundaries and for this one there is one odd number as the boundary so we can simply and safely draw the conclusion that as long as there is one of the boundaries is an odd number we need to divide the difference by two and plus one if both of the two boundaries are even numbers we can simply use the difference divide by two that's going to give us the total number of all numbers very straightforward as that so now let's start writing the code we'll just check if this low boundary is a an even number so we'll just do modular 2 is an even number this means it's an even number and we'll do the same for this volume 2 equals to 0 that means both the lower and higher boundary these two numbers they are even numbers if that is the case we can safely do high minus low divided by two that's going to give us the correct answer otherwise that means either the lower bunch or the higher boundary the uh not an even number that means either one of them is at odd numbers so and if that is the case well just to return the difference between low and high divided by two plus one that is going to give us the correct answer in that case now let's hit submit and see correct there is no other tricks to this problem there are various ways to solve this problem but i feel this is the most straightforward way to explain and understand this problem and i don't want to minimize to further simplify this logic to make it a one line it's kind of we can do that but it will be less readable and understandable um i hope this makes sense if that is the case please do me a favor and gently tap the like button on youtube video that's going to help me out dramatically i really appreciate it and also don't forget to subscribe to my youtube channel as i have accumulated quite a few legal videos on algorithm or data structures feel free to check it out hopefully i'll just see you guys in just a few short minutes that's it thanks very much for watching
Count Odd Numbers in an Interval Range
capital-gainloss
Given two non-negative integers `low` and `high`. Return the _count of odd numbers between_ `low` _and_ `high` _(inclusive)_. **Example 1:** **Input:** low = 3, high = 7 **Output:** 3 **Explanation:** The odd numbers between 3 and 7 are \[3,5,7\]. **Example 2:** **Input:** low = 8, high = 10 **Output:** 1 **Explanation:** The odd numbers between 8 and 10 are \[9\]. **Constraints:** * `0 <= low <= high <= 10^9`
null
Database
Medium
null
879
Hello everyone welcome to my channel, its video number is going to be 25 and liquid number is 879 and surprisingly this question is quite easy but its statement is a bit long and the question bill is incidentally say Dr. Tu zero one measure set I tell the question is very It is good, so we will read the description carefully. Okay, so it is going to be an easy question once you understand it is Profitable Schemes. The name of the question is, It is by Amazon. Let us see the statement of the question and understand what the question is. Okay, so give it here. It has been said that there are total N members, you will have N people and you have given the list of crime which are those people and the members can comment on it. Now if you do this to make the crime a crime then your profit will be so much. The profit will be fine and he needs so many members to commit the crime. Look here at the group allegation. Look at example number one. Profit crime. If you want to commit the crime of paragraph number zero, then how much profit is required. ₹ 2 how much profit is required. ₹ 2 how much profit is required. ₹ 2 and you can commit that crime. Yes, because look, I have a total of five members, right now it is from five members and you need only two people to commit this crime, so you can do this member participate C one crime date member Kant participate in andar crime par example if mother Let's say you have committed the crime of Ayat, you have got a profit of ₹ 2 crime of Ayat, you have got a profit of ₹ 2 crime of Ayat, you have got a profit of ₹ 2 and two members have lost their lives, then only three members are children. Okay, so in order to commit further crimes of A, only those three members are children and their help is required. You have to do it, okay, so now look here, how to define a profitable scheme, it is said that you can do it in Squaremat, okay, but your minimum profit should be at least this much, look here, I have given profit three, so this will give you It is saying that do the crime in such a way that there should be at least this much profit and your total number of criminals should not be more than 5. Atmos, you can do it is okay and this is all he is asking from you. From how many such crimes can you comment, the date can be chosen? You will see this example and then you will understand better that here I have said that I have a total of five terrorists, minimum profit should be at least three. Only then will it be a profitable scheme, okay for me, so look at it, pay attention to what I did, here I have given you Make N Profit and Fat List, you will get 3D group code, if you do crime one, you will get three rupees, the total is five rupees, right? So the minimum profit should have been three, look, I took five jobs, so now it's just a matter, it has become a method, this is a profitable scheme in which I have done it to all five members, two members are here to commit the first crime and to commit the second crime. In the second one, two members are from here, okay, so the tax member is the one who has committed the crime of the index, like look at this, these three will be three rupees profit, right, only two people are going in this, okay and 3 more should be my minimum profit too. Okay, that is, this is also a profit scheme and there were five people from me, now I have taken only two people here, so this is also a profit table scheme, okay, so now here too, let me explain well. Again a scheme, what it is saying is that either you commit both these crimes, it is okay if you reduce both of them, then how many men are you going to commit this crime, two men is fine but you have 5 men. If the total is two people, children, how many people are there, if three people are children, then you can do the second crime also, right, because only two people are needed to do that, okay, and I, there were three people and children, so I took two people and one. And also did this, how much was the total profit? 2+3=5 and the minimum how much was the total profit? 2+3=5 and the minimum how much was the total profit? 2+3=5 and the minimum profit I wanted was three, which means it is fine, I took five profits, so one scheme is done, now what is the scheme saying that you are only doing crime. Do number one, he will get three, my profit is three and maximum profit is three or he should be more and mine is three, which is fine and I need only two men, it is okay to do crime number one and I have total five men. I have seen that if I get it from a friend then do the second crime before the first one, do the crime of ₹ 2 and do the crime of ₹ 3. crime of ₹ 2 and do the crime of ₹ 3. crime of ₹ 2 and do the crime of ₹ 3. I will get a total of ₹ 5 which is I will get a total of ₹ 5 which is I will get a total of ₹ 5 which is more than the minimum profit. How many people were waiting for this? Two people were singing for this, if two people are required then the total tax is done, I was just a total of five people and I did the tax, this fine is fine, so this is the profit made in the second scheme. What did they say, brother, do this crime only, this one only. There will be ₹3 profit, which one do this crime only, this one only. There will be ₹3 profit, which one do this crime only, this one only. There will be ₹3 profit, which one gives it greater and you are equal, this is the minimum profit right and only two people are involved in doing this, which one takes it equally and both the profits are equal, the answer is two, how can you do two schemes, okay then see his approach. To understand, first of all you can think like this, remember friend, I met you, give the answer, then what happened in the first scheme, did you take both the rights, you got both the profits, what did you do in the second scheme. If you look at it then add it, you must be understanding that you have a definite option to take up this crime, that is, how will the person taken up be, or else he will not. People, is note taking ok then it is definitely clear from here that we can set DP, that is, we can see the memorization by applying recjan, whether it is okay or not, so in this video I will explain recjan and memorization, after that give further in the next video. Sometime we will also do the top dr, sorry, we will do the bottom up, okay, so let's see how this will be formed after all, ok, so it is the same, first of all, which is our approach, this approach and memorization, this was our example, so you Think for yourself whether I will do Ayat King or not, then I will have to keep an index for that, I correct I, will I do that crime or not, then I will start from zero, will I do that zero crime or not, after that we will move ahead, okay and this zero. How much profit will you make in doing this and how many people will be needed to do that? Well, from this index, now you can find out both how much is the profit and the size of the group, how many members will be needed in the group. Okay, it is done who. What crime are you doing on the index, after that let's see brother, how much is your current profit. Okay, donate the current profit by P. Okay, how much current profit have you earned because it is obvious that when you are doing crime. So give an ad, what do you have to keep in mind that the number of members you are advertising to should not be more than five. Okay, and if the profit is greater than three, then you should be equal, only then there will be benefit, if not now then there will be profit. You will stay in P only then you will get profit because what is your ultimate goal? Do you need a profitable scheme? Okay, so what will I track in P, how much profit am I making right now and keep a variable named People in which how many members are there right now? How many members do I have right now, okay, in the beginning, it is zero, okay, and in the beginning, my people are also zero, okay, now we will see further, at what time, people will be needed to do it. time, at what time, people will be needed to do it. Okay, so see, now let's make a tree diagram of this. Best understand from this. I will come now in the beginning I was zero in the index this is my index ok and I have zero profit I have zero people ok so I remember I had two options that I will not commit 0 crime or I will do it again ok so measure friend Right, if we look beyond zero, and if I don't do this, then now I will move to the next sequence, then IDEX becomes + 1, this is fine IDEX becomes + 1, this is fine IDEX becomes + 1, this is fine and obviously I have not committed any crime yet, right? If I have skipped, then profit will remain zero of zero and I have committed some crime, people will also remain zero of zero, correct crime, when I have not committed it, then people will have zero profit, zero index will be just one plus one. If I had committed it then the crime will be fine. There will definitely be an index plus one, but the profit will be huge. If you commit the crime of zero and three, how much profit will you make? ₹2, then you will get ₹2. Ok, how many more profit will you make? ₹2, then you will get ₹2. Ok, how many more profit will you make? ₹2, then you will get ₹2. Ok, how many more people were needed to do the crime. Two people, so two people, let's go right here. I have understood till now, after this, now let's move ahead, look here, after this, there are two options here, either do it or don't do it, so if I do not commit the first index crime, then it is okay, I will do it from the secondary. It's gone no profit no people required here if I commit this crime then I will go on the index number then index here what crime did I commit induction then how much profit did I get three got here it was zero plus three How many people are needed to make a profit? Two people were needed to commit this crime. Now look, pay attention, it is very important. Look here, I have reached the index number, which means I have now exhausted all the indexes. Brother, 012, I am out, if I am, then first of all, I am late after checking. First of all, I am late after checking that brother, the amount of profit I have earned so far is my number. Of people, it should not be greater than that brother, total only five people can do it and let's take mother, six is ​​written here, can do it and let's take mother, six is ​​written here, can do it and let's take mother, six is ​​written here, so now I cannot consider anything, it will not be kept as main, it will not have any value because you have to anyway. You have to make the number of people always less than or equal to N, so look here, I have given the number which is fine which is totally fine because this is equal to N is my correct which is the total number of members near me. After that, let's see how much profit we earned, brother, we earned three profits, give it greater, equal, you define minimum profit, that means we have got a good lesson, we have got a profit scheme, which one is this one, so I am from here. I will return one that brother, I got one thing, here from the left side, we will have zero from here, so here you see, here zero is from the left side, zero is made from the right side, then what will be the sum of both, zero plus one, total one. We got this one above, we have made it forward, okay, so we have made it from the left side, now let's see how much comes from the right side, okay here also again it will be the same, taken not taken or not taken, if not taken then index should be 2. There will be no profit, there will be no people, okay, you are the one and you are the one, and if I have committed this crime, then the index number will be on you. If you go, then the profit of this crime should be found. What is the index number of one? Three. Neither, here two were two plus three became five and already two people were taken and in this two people are going to do that, so I took it two by two, okay so now the index is closed out. Here too, whatever else it may be, the first thing I will check is that all the men I have taken from the story are not greater than that. Which is fine. Now I check that brother, it is greater than the minimum profit. Either it should be equal, brother, this is you, my minimum profit is three, so it will not be accepted that I got zero profit from here, there is no beneficial, this profitable scheme is ok, so I will send zero from here, now I come here, look out. I have gone off and on, now I have seen earlier that the number of people should be taken or equal, you are fine because my N look is five and here only man, I made him profit also see greater den equal, you are the minimum profit of mine. Threshold profit is three, I want more than this or equal and this is five kamli i.e. one scheme, I this is five kamli i.e. one scheme, I this is five kamli i.e. one scheme, I found one more way from where I am getting the profit by bus, which is that way, so I got 0 from here. And from here I sent 1, the sum of both of them is one, so what did I get here, note from take one and taken seven, then zero, sorry one plus one, how much is the answer, remember the answer was you, isn't it, so simple. If you look at it, you can also just code, it is very simple, you have to pay attention to one thing, if you memorize it, then you are seeing three variables changing, index, what is the profit, okay and the number is also changing, so three to customize. I have taken this example for you with three variables. Okay, I will not draw the entire example but you will understand one very important thing. Okay, now I am in this statement, in the beginning, profit is zero, people are zero, now look at the minimum profit. If you want to reach two then it is okay. If you want to reach the minimum profit of two then reduce one. We start from zero. If we take mother, we do not take more. It is okay then we do not draw the whole diagram. You understand only half of what I am saying. A will go and mother, let's take it, I am late, now the index will become 1, the profit will become one, how many more people did I need, one person was needed to do this, so I took one, okay, let's come after this. Note take you note taking so I am making taken right now so how much will be the profit index and you will be how much will be the profit here one already and there is profit in this two then three become profit and after this one what is here How much will be the group, I wanted two people, I am fine, two more and one here is ready to do it, so a total of three people, I have done it till now, okay, now tell me one thing, when you explore as many lessons as possible from this point. If you note taken, then it is obvious that you are okay here, I will remain three out of three, but look here, this profit is just going to keep increasing, right, if you keep taking, then this profit will keep increasing. So let's take profit, okay mother, it became five, then further five became 110, why do you have to do such a big value, when you know that your profit should be at least two or more than two, then you can still take your profit. If it is a profitable scheme, then you are making it bigger by adding more to it, otherwise I will have problems, like if we take mother, we take vector, we take DP vector, then there is a profit variable in it, then the profit will keep getting bigger, so you will also remember the profit here. Neither will it become very big, so why don't we do this, I know that brother, my minimum profit should be two or more, which I have got here, so I can further increase it to five or 10, 100-100. so I can further increase it to five or 10, 100-100. so I can further increase it to five or 10, 100-100. Why should I keep increasing further, what will I send further, see that in committing the crime after this, it takes ₹ 1. Okay, ₹ 1. Okay, ₹ 1. Okay, so here I am doing two, three plus one tax or I am saying that the minimum is my threshold, how much is the minimum, two. So why do n't I send only two because even with that my valid profit table scheme will be there. What am I saying? Whatever calculation I will do tomorrow, I will send it like this, the minimum of which is my current profit, what is my current profit? It is piti na plus the profit which is less in the current index, I have made profit out of these two or the minimum threshold minimum, sorry, the minimum profit which has been given to me, the question is, now let's take my profit plus mother, if it costs ₹ 2 to commit the current crime. costs ₹ 2 to commit the current crime. costs ₹ 2 to commit the current crime. Three, two become five, okay, it became five, and what is the minimum profit? If two, then I will send only two, because even two, I will still have a profitable scheme, because here I was saying that the minimum profit should be only two, why should I give this three? If it increases further then it is 10 12 110 which is fine because if my profit is not equal to my minimum profit, it will not remain only two, but even then I will get a profitable lesson. Correct, then there is no benefit to me if I increase the profit. If I go on doing big value then I will face problem otherwise if there is no other problem then if I do a small option now then it will be more clear, right here I was explaining to you that you will make profit whenever you want further tomorrow. You will definitely do recession in your recovery. It is not necessary to send P+Profit I in profit. It is okay with you. not necessary to send P+Profit I in profit. It is okay with you. Whatever is the minimum profit, send the minimum which is from these two. It is okay to send whatever is the minimum between these two. What was the comma after that? GROUP OF PEOPLE Yes, you can send it to GROUP because now this is what I definitely want, NOW GROUP A PEOPLE GROUP OF I PLUS PEOPLE, which is my current PM number PEOPLE, because I can't cross PEOPLE, IT SHOULD NOT BE GREATER DEN NUMBER Of people, I will definitely have to send it in plus, but here it is not necessary to have P plus profit time in between, I can send off of both of them because there will be problem in memorization because the profit will keep on increasing the more you move ahead. Is n't it, then there will be a big value in memorization, then how much will be the big value, okay, that's why I am saying, take minimum, then minimum people, still your answer will be correct, okay, let's do the court now and see and the story is exactly like this. Like, if we write the code now, then bill just convert this story, you go into the code and see how its code will be, so let's do this question, we will do it exactly as told by Rickson, okay, first of all, put your function here. Define what I know, first of all I will take the index, which crime am I going to commit, what is the number of my profit now and the number of people that I am taking to commit this crime, it is okay till now it is clear and apart from this all this also. Let's send the profit on Go, whatever it is, right, now before we complete it, I go here in my profits key, first of all, I have given it a big variable named N and apart from this, the inter wall profit is ok as much. It is given in the question that what should be the minimum profit. If we send that also then let's start with the total number. You cannot take more than this. You cannot take more members than this. What is the number of profit? People are also zero in the profit group. And sent the profit, more people than this is fine and if you have reached from the last egg, you have gone out of the box, then what I said, then check that your profit should be greater, give equal, minimum profit should be there. There should be profit only then you have got one thing, else make the return zero, this thing is exactly what was told and it was also told that you will definitely get flood but no profit and no people increment, both were sent as they were. And the people have also been sent, okay and the rest is sent, there is profit in the group and the profit is clear till now, after that it is long taken, now the note is taken in, so you also make the taken, what is important in taken, brother? I plus one will definitely make profit. Yours is overflowing. Correct, how much profit is overflowing in profit and the mean profit will be sent as it will get bigger, so there is no need to increase more than that. Even if it grows further, I will keep sending the minimum of both. And the people will keep on increasing, right, group of I have taken so many people in it, I have taken more than everyone else, what do I have to send in the last brother, I have got as many profit bills from take care and note taken, it is not much, just understand the question, I was giving it, okay, we will solve it. Then if it is present here then the answer is correct A means they are going right now this one is correct there is a train that look at the minimum set T - 1 size of set T - 1 size of set T - 1 size of T right here we will check it here otherwise we will return it here Whatever P is, that's why I was saying, look, I have taken maximum one here, but if the profit keeps increasing then there will be problem or it will get auto bound, so to save from that, let it remain till the minimum profit which is my minimum profit. Value has been given whose value can go up to maximum 100, I have taken 101 because somehow if you have reached the minimum profit, your answer should appear in the modal, then I will modify it here, okay and I will also modify it here and Here also I apply mode is fine, I have to keep it constant, let's see I hope it is sold pass, which date is cases Android, submit this and let's see, let's pass every test, how let's get late, so see here, I did it and here But we should have done it here too, we are sending zero here, okay so let's go late, let us know whether we should go now or not, well here also we did not do it, I made this smile a little in memorization, this and this miss. If I had done this then this was the same. If I had done this without this then it would have been solved by this. If I had missed then do the memories well. I hope I am able to help you. Any doubt is there. Resident D is in the comment area right RP out C. you gas video 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
1,299
The next question is where is the nice Mentos Ripples? Ok, this question is telling you, let us take countries like this. I don’t know if you make us take countries like this. I don’t know if you make us take countries like this. I don’t know if you make a cup and let us make fresh here for what. It will erase all this talk. I mean, you can also provide a second board instead of deleting anything. Is it true? I’m being honest for the first time. deleting anything. Is it true? I’m being honest for the first time. deleting anything. Is it true? I’m being honest for the first time. I'm using it. I'm still using it today. What's going on? Okay, second. Is it not going to work or what? Okay, okay. This problem, for example, if we assume that we will take the same numbers that are there, where are they? 17 18 5 4 6 1 17 18 5 4 61. This problem tells you, I am here. Al-Rish 61. This problem tells you, I am here. Al-Rish 61. This problem tells you, I am here. Al-Rish wants you to triple every number in this village, from the beginning of the village until the end, in the big number on the right side of it. I don't understand if I tell you, for example, 17. I want you still, meaning the largest number in the numbers I have, so we will find that the largest number here is 18 5 4 6. 1 We will find a number, how many 18 and 18, which will be six, which is 461, which is six, okay, so we will go to four from the first number after that until here, so what is how many six will we find there with a number here one and he told you the last number he always wore. I think he said that, right? He tells you that it is nice, good, nice. How will we do something like this? Let's see the traditional solution that we can think of. By the way, he prefers to know in the internet that gets a large time, okay, and after that you start improving the code, he will understand that you understand, even that you can't leave your code to waste, understand. The world, the code, must improve. Always try to think first about the difficult, traditional solution, Al-Ahly, to think first about the difficult, traditional solution, Al-Ahly, to think first about the difficult, traditional solution, Al-Ahly, which is Al-Ahly in writing, but its time which is Al-Ahly in writing, but its time which is Al-Ahly in writing, but its time will be a little big, and after that you start thinking about it. Something we can do will improve. I found goodness and blessings. I have not found it. So this issue really has no solution. Ok, leave the cold force, which is completely normal. I will take the 17 and I will work from the first 18 up to one and get the max from it. I mean, I will get the max between these numbers like this. After I make this instant like this, I am supposed to return the max and replace it from the one I put here, and I take the 18 and work immediately. You go on five, and after that, instead of the max, there is 18, which is how many sixes, and after that, five, okay. What time is this code? We will find that our set is in the name of God, the Most Gracious, the Most Merciful. This takes the Nesquik, okay, because Square, because I take each number and roll on the rest of the numbers in Love. A second time, I do Instagram under each other, and the two are fine so far. Our code takes that Square has more, all of them are variables, and the variables in Space will be more abundant. Okay, okay, can he answer with you, I earned, I don't know. To be honest, I haven't tried it, but he can answer with you, Expedi, but I'm not satisfied. I mean, I feel bad. We can solve this issue with a second-best solution, and he will answer with can solve this issue with a second-best solution, and he will answer with can solve this issue with a second-best solution, and he will answer with us. Ok, so it will be less than the now square. What can we do ? Ok, let’s see the solution that can be given to us. Ok, ? Ok, let’s see the solution that can be given to us. Ok, ? Ok, let’s see the solution that can be given to us. Ok, so we have arrived at the women’s time. If you so we have arrived at the women’s time. If you so we have arrived at the women’s time. If you notice, guys, we are here to get the value whose value will be replaced by 17. I have to get the max, meaning zero 1 2 3 4 5. I have to get the max one so far, The value that you lost is only one, which means that you roll on all the numbers that you rolled over here, except for the first value, and in the same story here with the two, you rolled from three to five, and you also had the max, which is up to the value of two. In short, what does the witness mean? With what you say, a simple twist is what you are, for example, in order to get the max of the zero, you will get the max. Okay, wait until we continue from three. You will get the max from four to five, known as negative one, beautiful and strong. You will get the max from four to five. The max is between six, right now. So, Monday, because You get the value that the one here told you that you won't need to damage it. You will compare the value in India. Focus, guys. The value in geometry is three okay. I want to get it now. What is five? Four three is three. This is three okay. I want to get the one in three. I got the four. It was six. The important thing is that you will compare the value of three with the max that was in the next set. Ok, I don't understand. I think that you will understand it in the code perfectly, but I hope it is clear. What you mean, in short, is that you will rotate from back to front. Here the office is minus one. You will see the max. Here between the six and the negative one, okay, the big one is the six. I mean the big one. Okay, so the value here remains one. I have 4. You will get the max. Between this six and the one that was the last max with you will have how many sixes left. That's it. How many sixes will you have left? You will come at 18. You will get the max between five and the last value you have, which is six. What will be the six? It will come at 17. It will land here at 18. I feel what it means. You got a little confused, right. There are a lot of people who got confused and the world is not perfect. But this boy is fine. He will tell you what. I will give you a hat trick from the end to the first. Erase, uncle, all of this. I am now walking from the end to the first. I am walking on the contrary. There is a variable factor called Max. His word is a word with a minus one. It is very nice. Continue talking here. I will tell you that it is good to do Max with a minus one. And in all eyes on Max. This means this. I mean, he told you in every... Roll, I am standing here right now. I put the six and leave it at the max value, which is 1. After that, I renew the max value. Between six and one, the max will remain at how much the max will remain at six. After that, I will compare the four. After that, I will go along and put these four at the six that is the last max. He has renewed the value of the max, and so we write the code along. It is ok. Now I will create a variable called max equal, negative one, and I will create it as soon as you walk from the illiterate equal and we are fine, whichever is larger. I will go from the last. The first. I can return to it the same vector that was given to me in the first place. I mean, it remains. I was taken advantage of a little bit. I will tell him here, put me in the village of Equals Max and renew the value of the Max equal to the Max between the old Max. Okay, I am in the second one, and after that I use it, so I will not return to the real office. Okay. Can I put a new variable here whose name is, for example, what is that? For example, it is equal to the verse. I think that works perfectly. Thank God. It answered. Okay. It will work on its own. If we do the opposite, we try that. I tried it. I mean, you mean to say I get the first max without knowing this step. You will get the gain of one. I mean, if you have negative two, okay, what is the solution? That's right and we won't go on any longer
Replace Elements with Greatest Element on Right Side
k-concatenation-maximum-sum
Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`. After doing so, return the array. **Example 1:** **Input:** arr = \[17,18,5,4,6,1\] **Output:** \[18,6,6,6,1,-1\] **Explanation:** - index 0 --> the greatest element to the right of index 0 is index 1 (18). - index 1 --> the greatest element to the right of index 1 is index 4 (6). - index 2 --> the greatest element to the right of index 2 is index 4 (6). - index 3 --> the greatest element to the right of index 3 is index 4 (6). - index 4 --> the greatest element to the right of index 4 is index 5 (1). - index 5 --> there are no elements to the right of index 5, so we put -1. **Example 2:** **Input:** arr = \[400\] **Output:** \[-1\] **Explanation:** There are no elements to the right of index 0. **Constraints:** * `1 <= arr.length <= 104` * `1 <= arr[i] <= 105`
How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1.
Array,Dynamic Programming
Medium
null
77
okay let's talk about combinations so combinations is actually that you generate combination and you'll return all of possible combinations for the integer n and k so let's integer so integers like from 1 to n in case the then of the subset so you will definitely understand how do you do a picture in this video so you need a list of lists to store the value right so i'm going to call this equal new arraylist so i'm going to pick code backtracker so what i actually do is i actually i'm using the void type so backtrack and i need to i definitely need this of this right integer and this and also integer k and what i will do i will definitely need a temporary list and what i also need is my starting value right starting value so the starting value is one it's not zero right so let's idea okay so what you actually do is backtrack your code list your code and you'll know this of individual which is temp and also you're starting from one right and you just return this that's pretty much standard backtrack and what you actually do is okay what happened to my k why do i pass in k case 2 right so i would decrement every single time when i uh call the backtrack so if my k equal to zero which means i can add to this right okay this standard if k equal to zero i can add to the list so i'm going to add my temp to this but i'm not going coding uh 10 lists i'm going to new a release and add a 10 into the list because the type right when you add your when you add you can just return that will be simple straightforward so uh let's just start how do you do it so you will say i equal to star and i less than equal to m minus k plus one okay where do i plus one because the equal sign value and i plus so you might not you might think like what should i use n minus k plus one so imagine n equal to four minus two is two plus one three so you will start from one two three right one two three so one the first thing there is one two three right you are not using the full on your first index right so they this is pretty tricky you will save a lot of time so a minus k plus one four minus two plus one is one so two plus one is three so it's three so the first index you have is from one to three you and i like try the full value on your first index it's not possible because uh you when you add you had to add the uh in ascending order right so that's the way okay so what you actually do is you add the eye and you remove the eye right and how do you remove your room the last thing this that's the way okay so let's talk about backtrack so what you actually do is you need and i mean you need this you need an you need you don't need k you decrement k and what you actually need to do you need 10 right and start a star will become i plus one right there is the pretty standard so you're not using the same value so 2 is not allowed so this idea and let's see it's good and it's also good okay let's talk about timing space so uh what do you think so you're starting from your generate a tree which is out of n height is elephant but for each level it is all of so you either pick or not pick the value right so it's all of two times n minus k plus one you have a minus k plus one possibility for each level right so it's two to the n minus k plus one and time that i mean less time and space is also um i mean two to the n minus k plus one uh your general one two three four five six right so two to the six should be i mean it's a wrong it's around right six is less than a right it's always around two to eight so that would be your solution and i hope you get it so if i'm wrong on the time and space let me know and the question is so good and good luck
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46