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,897
welcome back for another video we are going to do analytical question the question is we distribute characters to make own strings equal you are given an array of strings words geo indexed in one operation pick two distinct indices i and j where words i is a now empty string and move any character from words i to any position in words j written to if you can make every string in words equal using any number of operations and false otherwise example one what is abc aabc bc the output is 2. explanation move the first a inwards 1 to the front of words 2 to make words 1 equal abc and words words2 equal abc all the strings are now equal to abc so return 2. example 2 words is a b a the output is false explanation it is impossible to make owner strings equal using the operation let's work for the code we first initialized a way to store the frequency of characters then check the frequency of characters to see if characters can be divided equally among strings time complexity is o n space complexity is o one the solution works thank you if this video is helpful please like this video and subscribe to the channel thanks for watching
Redistribute Characters to Make All Strings Equal
maximize-palindrome-length-from-subsequences
You are given an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_. **Example 1:** **Input:** words = \[ "abc ", "aabc ", "bc "\] **Output:** true **Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc " and words\[2\] = "abc ". All the strings are now equal to "abc ", so return `true`. **Example 2:** **Input:** words = \[ "ab ", "a "\] **Output:** false **Explanation:** It is impossible to make all the strings equal using the operation. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of lowercase English letters.
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
String,Dynamic Programming
Hard
516
141
all right in today's video we're going to be doing link list cycle 141 okay given ahead the head of the link list determine if the linked list has a cycle in it 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 pause or position is used to denote the index of the node that the Tails next pointer is connected to note that pulse is not passed as a parameter return true if there is a cycle in the linked list otherwise return false okay and then you continue to move all right so like this clearly has a cycle you have a linked list and then you have a one node connecting back to a previous node and there you have a cycle here you have one and two and you see it clearly linked to another node so that's a cycle too this is true and then this node is not linked to anything so it is uh there is no cycle okay so this is like a I don't really like how they say pause like to denote the index because uh all we're doing is returning true or false and um we don't need to know the position in which uh there isn't like a cycle I guess so this is a little bit confusing because maybe if we're doing like in C or some other like a statically type language maybe you have this position but I guess it's not uh not needed uh in this case so I don't quite understand what pulse is but I understand like hey we gotta make sure we're not having a uh a cycle all right so there are like two ways to do this but I'm gonna just show one of the ways I'll probably show both we'll see I have to ask how do you do this all right so this is how we're going to do it uh we have this link list let me let me I have I got this new pen and it seems to be uh helping me draw beautiful illustrations all right so we have this linkless cycle one way we can do that is uh have a list create like a list or a set or a hash map to keep track of all the things that are uh that all the nodes that we're gonna see as we Traverse so when we see this node over here we put it in the list if we see this node over here we put it in a list and we see this node here we put it in a list right then if we uh as we go we keep on checking if we visited this list and if we've already seen this know like if we go across and then we come back to this and we already see this node then we're like okay we found there is a uh there is a cycle and if we don't like let's say if it's like a linear one let's clear this nope and let's say there is a linear one like that goes to nothing when we put it in the list right we will probably just reach the end where all these nodes are in and then we get to a none and then we know we went through the whole list we did not find anything uh going back to it uh then we just say it's false right that's how you spell false all right so that is what we're going to do for the first iteration now uh one thing is it'll just we only have to iterate it through once through like the length of the list right the time complexity will be like o of n but the space no and uh the space complexity will also be over because we have to go through each node at least once and in the space complexity would be the same at worst right all right so let's just start writing it so let us create so like I like to use a set because a set it you can easily retrieve it very fast we don't need a hash map in this case so we're just going to call visited equals set and then we're gonna say while head we'll just say well head is true um if head is and visited return true right because that means we reached a cycle otherwise visited you add head and um then you make head equal to head dot next and then we return false at the end all right so what we did right is we're traversing through the link list uh if it's invisited we're like we found a cycle otherwise uh we just add it to the visited set and then we say head equals head next so that means we're moving forward into the link list and then if we reach the end where ahead is going to be none we're going to return false and let's return false like that all right so let's run it let's see if the initial test cases work uh silly invalid syntax I don't have to have is all right some syntax error I just I always put is in all right but we are able to pass all the basic test cases up here and then we're gonna submit them all right so uh we did really well in runtime but we did really poorly in um memory so there is actually another solution I always struggle with the solution but uh it is the one where you can just have you can use no memory at all so like you wouldn't use um this visited set at all but it is a much it's a better solution but I like this one it gets the job done but let's try to do this like new this other solution that I need all right hey guys if you like my videos and even if you didn't like my videos and you thought my solution was crap please like And subscribe that'll be helpful it's really cheap for you to do and it really helps me out all right thank you no all right the other solution is essentially uh called a it's like you have a slow and then you have a fast pointer all right slow fast high knees okay the slow and fast pointer let's say we have this link list right and then it Cycles back here and then we have okay we have this here all right this is a lovely picture all right and um what we're going to have is two pointers right one pointer here and another pointer a little bit uh further along right and we're going to continue to Traverse across the link list until both pointers so like in the next iteration this pointer goes here and uh this pointer goes here and eventually at some point both the pointers are going to like align like this and then we know that we are at a then we know we found a cycle right so you're gonna have a slow pointer and a fast pointer and the fast pointer is going to go two nodes ahead and then the slow pointer is going to go one at a time and eventually they will both meet okay this is uh I don't know what the official term is called but that's what we're gonna do all right so all right has cycle all right so we're going to create slow which equals none right and then we're gonna do uh fast which will equal um head all right so while uh fast and like Fast dot next right because we want to make sure because this one this pointer is going to go a little bit faster than the previous ones then the slow one so it's going to go uh two nodes ahead so we have to make sure both the Fast and the fast dot next are not none right they both have True Values right um and then if fast is uh equal to slow right and slow is like not none we know that we have found the cycle so we're going to say that is true otherwise now what we have to do is um move forward so we have to say slow dot next if uh slow right slow dot next else uh we're gonna just make it fast right and then um fast is going to equal fast dot next all right so let me to explain this is just a inline if statement and because we make slow none initially uh we have to just take that into account so like if slow is none we just immediately just make it whatever existing fast is right because fast has had but in any other case we just move to the next uh node right so that is how we're going to continue and then if uh fast and Fast dot next is one of them is not true then we break and we're going to return false so remember we're having two pointers one slightly uh slightly in front of the other one and they're gonna move across the link list until they both meet eventually both of them will meet if it's a cycle if they both don't meet and they reach the end of the list that means it has not reached the cycle it's not Honda cycle and it's just like a flat linked list all right so let's run this first all right and then all right so as you can see now so this memory consumption is uh faster is it consumes less memory than my previous implementation right because we're not storing the nodes in like a set or a hash map right and we're never storing anything really so that's why uh storage is always going to be constant but we're still going to take o n of time right because we still have to Traverse each node at least once before we can figure out we have a cycle right at worst so that is it for linkless cycle leak code 141 all right peace
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. 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. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **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
Easy
142,202
253
how's it going everybody today we're gonna do a question number 253 meeting rooms number two last week we actually did meeting rooms number one and for those who haven't seen that just check the playlist or check a link down below for meeting room number one the reason I chose to do number two is because this is a good example of how when you go through an interview someone can evolve a question may sound similar but is quite different and the complexity will be slightly harder but it's not too bad so what we're gonna do is first trying to read the question understand it I'm gonna visualize a couple of scenarios and then we're gonna coat the problem okay so stay tuned alright let's read the question give an array of media room time intervals consisting of start and end times s 1 e 1 and so on so forth find the minimum number of conference rooms required alright so for those who are not aware from the previous question for meeting rooms number one all we were just to give you a recap of meeting room number one was all about in meeting room number one all we had to do was to understand whether or not I could attend all meetings right given basically in array of tuples which gives me the start and end time but for meeting number two this particular question I'm being asked how many rooms do I need such that I can effectively fulfill all the meetings that are scheduled right so one thing we need to understand from the previous question meeting rooms number one was a way to do is find overlaps right but in question number two those overlaps should result in a new meeting room right because you know if you can't attend those meetings from the previous question therefore you're gonna return back saying oh sorry I can't attend but there's this question instead of doing that maybe we had to do something little more right so once you identify that overlap then you have to actually create our increment somehow another meeting room right so this question is very similar to the previous one however there's a slight twist all right so that's like an example let's bring this sheet here okay cool so I will use an example here where I have you know four intervals right and we have to determine how many rooms I need right so when we look at this if we iterate it through here what do we see that okay this one starts from zero to 30 right so I'm gonna create a room say I open up one room that starts from zero all the way to 30 right that's cool but when we look at the next element we look at okay well this starts at one but ends at five this actually starts way before it ends right so effectively what we need to do here is open up a new room number two which is gonna be from 1 to 5 great so we look at the next interval - all right whoa this starts at 2 right - all right whoa this starts at 2 right - all right whoa this starts at 2 right and ends at 3 well it starts also earlier than the 30th right and it starts also earlier than 5 because that ends a 5 so what do we need to do here right we need to create a third room from 2 to 3 right and then we look at the last element it starts a 7 o'clock to 10 so 7 o'clock well that is definitely starting before the first room is all available but we could check the next one oh is it available in this one sure it is and it's also available here so we can actually slot in something like you know arbitrarily here it doesn't matter like a slot in seven to ten o'clock right so in this example you can see that all we really need to do is compare the starting time and effectively the earliest time available which my start where I could slot in my next meeting right so this becomes a little bit more easier right so all we have to do ensure is that okay well I have to make sure that these guys as I slot it in right out to make sure that you know there's a critical part we need to do remember from a previous question whether ensure that we have no guarantee in this question saying that this is sorted so one of the things that we have to ensure to do is sort the array by the starting time this is important because if we do that then we ensure that as we create new rooms and those things like the end times are actually in a certain order right and all I have to do right now is take the starting times and compare it to the latest or earliest available end time of my existing rooms that see if that start time is less than or greater than my end times right so if it is less than well they're not gonna create a new room but if it's greater than my end time then I could just basically pack it in and when I pack it in then I know that is my that time that slot has been filled and effectively I can't use that room anymore right so let's check with some code to solve this problem to have a little bit better understanding alright cool so let's get into code alright one of the things like I said before we have to check for edge cases right what if I'm only given one slot time slot right if I'm only given one time slot then I might as well just returned that back to them I don't need to tell them that go on you're creating a whole room so I'm gonna check if my intervals right dot length is less than two right if it is then I'm just gonna return one example right or it could return the intervals dot length but I'm just gonna return one for now because you know if you only have one room then you'll need to create one room great that's good enough now the next thing is we have to sort the elements so intervals dots sort at a be here and they create this here alright and I need to return the a at position 0 minus B at position 0 which is effectively the start times right and then close this bracket great alright cool now that we have things sorted by the start times of the tuples what do we need to do right remember when we looked at the diagram we need to start tracking something right - to make start tracking something right - to make start tracking something right - to make the decision whether or not we create a new room or not right and one thing I like to track are we should track it's a check well when is the earliest end time that we already have for our current brooms right so maybe I'm gonna creating like a early room time right earliest room time available I'm gonna make it such that it's an array right and an array of maybe basically I'm gonna populate it first with the intervals at 0 1 position so what I'm really doing is saying that ok well I know I have one slot that ends at 30 right just to start it off and that's the earliest room available right so when I get to the next step I'll go like okay well this one starts at 5 o'clock if I checked the earliest room is only gonna end at 30 then well I'm gonna have to create a new room right so I'm gonna have to create more rooms at 6:00 era so by determining more rooms at 6:00 era so by determining more rooms at 6:00 era so by determining by having a length of the early swing time we could actually determine how many rooms are gonna be available right so maybe a better name is gonna be rooms let's call it rooms room time all right cool all right and then what do we need to do next right now we have to effectively iterate through the intervals right so for let's go let I equal to 1 right and I it's gonna be less then the reason why I'm doing it I go to 1 because we pre-populated with the first value pre-populated with the first value pre-populated with the first value okay so intervals and intervals dot length and I plus right so we're gonna iterate through everything and I'm gonna extract certain things from each element I'm gonna extract the start time and the end time from the intervals rolls I guess spell enter vowels at position i right this is don't mind the selectable syntax is basically a fun way to write a set right this basically is the same thing as saying okay start equals to interval at you know I at 0 and also like end time at 1 this is basically using the spread operator and effectively signing the first variable to like 0 the second variable that comes up is gonna be the end time so it's just a simple way I like to keep it here cool so I have a start and end time here right the next thing I want to do is ensure that I have the latest room time right so what I'm gonna do right now is let latest or earliest the guy's house pellet or all this will equal to the math dot minimum of the room time right so we're gonna basically saying what is the earliest time a room is available in this array of rooms that are booked and of course I'm gonna use a spread operator again to effectively what it really does is saying that okay if I have 30 here or 10 there as an example all it's gonna say like okay well I'm gonna make sure it's a thirty ten and check it that way sex era okay so now that I have the earliest time in there in this current case is gonna be thirty because we pre-populated that already right pre-populated that already right pre-populated that already right and our first start and end time just let you know is gonna be the five and ten right all right so what do we need to do right all we need to do is check if my start time right it's gonna be less than my earliest time available on the rooms right because I need to check if it's not then what do we do right we're gonna create a room so I'm just gonna go and room time dot push the end time right so what this does is gonna push the ten into this interval right because you know the earliest time that this is available is thirty and definitely this start time at five is not good it is less than this right so therefore we have to push the end time in here all right cool and otherwise what do we do otherwise we are just going to go back into room time right at that room time dot index of and I'm gonna say earliest right so I'm gonna go back to the index of where that particular value I'm looking for right and I'm gonna make that equal to my end time right so effectively it's the same case of okay well if I could book that room I'm just gonna change the fabric availability to the latest one available okay cool so that's that and finally what we can do here is return or turn the rooms room time dot length all right cool so to go over this real quick again all we really do is just check whether or not we start before we and in an earliest available end time would be and then once we do that we just checked how many rooms have been booked after this process now this solution should provide a solution so let's check and see if it does or not and boom ooh I messed up here hmm ah the edge case see some things gonna need to catch the edge case we can't just return one right we sure we should just return the intervals not length here so when it's empty you'll just return of zero great solve the question awesome now here's the fun part right what is the time complexity of this thing and also what is the bottleneck of this right now how can we improve this now I'm gonna leave this so you guys can think about it a little bit however one way to improve this algorithm or at least know that you know somewhere can be improvements can be thinking like do we really need to store or this whole thing of finding index of a particular element that's kind of like troublesome right what other algorithms allows you to find the latest time available think about it in JavaScript unfortunately we don't have minimum heaps mean heaps you have you could build it up yourself if you want I know in other coding languages you could use heaps but in this case you will probably want to consider using a min heap to optimize this slightly further so you don't have to go to the whole math dot min and look through the whole array again you can actually just pull up the top node and that would be the minimum element that you're interested in and then we just need to update that right but for simplicity I'm simply mystic I'm not gonna go implement this whole heap thing because I'm lazy however if you want some little study notes and if or if you're interested in me to go into teatime deeper let me know in the below and I can but for now this is a good enough solution right for the time complexity here though if we look at it what is the bottleneck here for time this is you know n log n right cuz it's sorts and this element is basically you know n right however yeah so I'll let you take a while yes why don't you would you guess in this particular solution what is the time complexity okay leave a comment below and for the one who gets it right you know mentioned a problem and I'll do that problem next time okay see ya peace
Meeting Rooms II
meeting-rooms-ii
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_. **Example 1:** **Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\] **Output:** 2 **Example 2:** **Input:** intervals = \[\[7,10\],\[2,4\]\] **Output:** 1 **Constraints:** * `1 <= intervals.length <= 104` * `0 <= starti < endi <= 106`
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied. If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
Medium
56,252,452,1184
328
Hey gas welcome and welcome back, what have you given us in my channel, here we have kept a single link. Okay, what do we have to do, here we have to group all the notes of all the different indias together and which and There will be notes of indiasis, we have to group them together, it is okay and who will follow the groups of index and groups of indiasis, okay, then what will you do after that, if you return to English, then first let us understand our problem through the example. Is it okay, after that we will see how we can solve it. Look what we have given you, a single link list has been given, suppose you are three four five six, this is given, okay now what do you have to do and all the notes of Indiasis. If you want to group them together, then who are they? This will be your first N. But if you can, then what you have to do is to collect them together. What will become next of one, what will become of three, what will become of next of three, what will become of five, okay? This is done, your group of OD, now what do we have to do and if we have to make K, then who will be in and, this will be what is here, we do not have to see the number, we have to see here, indices second, what is your and is. Here what is yours and is, so we have grouped it together, okay so you have grouped it, now what will it do, which is the and group, it will follow it, that is, the next one of fifth will be this and the six connect next will be your right. So you have to do this and return it. Okay, I hope you have understood what is your problem, so what do we do? First let us understand a little bit of English, what is English, see what is English here, don't give it in English. There are fields, okay, this is your data structure, what happens in it, there are two fields, what the first does is, it holds what is your data, okay and the second does, what is your next note, which note is connected to it, its address is held. What will it do? It will hold its address. Okay, so what will happen in this. Again, there will be data here and it will hold the address. Whose address will it hold? Whose note will be connected to it in the next, so in this way you will know that any node What is the next right, which note is connected to which, we have to know, here it will help us, why, how, see, here you are a van, you should first know that it will be the head, it will be your first and will be of the group. He will be the first element and the first member of the group and who will be the next member of the group, you have to know this but what will be his next, what will be the next of the van, what will be the next of you, see who will be the next of the van. Who will be the three? From whom can the information be obtained? Because the note pointer will be holding its address, so here we have to know the information of 3 from Tu, then the number of the OD and the number of the OD. What is the next element of the element here? What will we do if it becomes the next of van? From this we have to know what is its next. It will go to OD, so what is its next. We have put it in OD. Okay. Now, who will be your next? If your next is four, then how will we know about four? If we will know about this three, then who is three are in OD, so who will be next to us, what will become of us, what will come in it, ok, OD's. Next will be I, so here we will connect here. Okay, now who will be the next of three, here is five, how will you know about five, you will find out from this four, right, who is four, if this is I, then and's. Whatever will happen next, this is okay here and whatever will be next of OD i.e. is okay here and whatever will be next of OD i.e. is okay here and whatever will be next of OD i.e. whatever will be next of your pipe, here six. Once this is done, then let me explain to you through the second example. It is okay here, so we will take the second example, you three. Six four here let's take 911 13 okay this is your second example so what we have to do here is to put the OD together so here what will happen after tu will be six what will happen after six here will be 13 and A group has been formed, which process will we follow? Look at us in this, understand. Okay, so who will be its first member, what will be your tree, who will be this one, so see who will be the next hit, so take it here and take it here. First, what will be made in the next member's next, what will be made in the next of OD, then you will know which is your event, what will be your next actually, and what will be next, this is not you, six is after you, six is ​​whose next, this is three after you, six is ​​whose next, this is three after you, six is ​​whose next, this is three 's next. What are these three and what will 's next. What are these three and what will 's next. What are these three and what will we do, here equals, you will give and ka, next event 's six are connected, okay, 's six are connected, okay, 's six are connected, okay, and here is, in the next OD, you are connected to you will move the break here and here it will come. Well, if it comes here, what will you do and you will make equal, what's next, okay then you will know and four will come, this one is four, so whose is it actually next, six is ​​next, it will work, we will know from the other because it is odd. Ka is next to six, that is, what is your six's next four, then four will be connected here, okay, so your and is here now, so will you do the next of and also, if you move forward here, then and equals you. And Next, what do we have to do in this process? How long do we have to keep following until our event ends and Next is your tap? If even one tap happens, you will not do the process further. Okay, so here you see what you will do. And your six is ​​on, now what will you do in the next is ​​on, now what will you do in the next is ​​on, now what will you do in the next six, you will put the next 4, you will put the nine in the nine and you will move it and here it will go to A. Okay, now what will you put in the next four, the next 11 in the nine will you put here then F. You will move end and co and here A will go and k will go to next i.e. 11's next i.e. k will go to next i.e. 11's next i.e. k will go to next i.e. 11's next i.e. your 13 a, ok now 11 connection will be null here then this will become null ok so your and here a will go then this loop is yours. After that, this process will not work for you, it will not work, okay, now we have to return the link list, so what do we have to do in the link list, to whom do we have to connect this 13, you have to connect this 13 with its skip first member, so for this What will we have to do, we will have to take another duminod and equals, you will have to do more to us so that the event will start from where it started, we will do it already, I will show it to you in the court, we will do it already, okay, so what will we do with this? What will we do next by going to the last, what will we do next in the odd, yours is equal to 10 is equal to whose, the temp will be yours, here the starting point of and will be equal to its, okay, so we will do this, so I will give you the code for this. Let me show you, see what we will do, first we will check that there is no head, okay, then we will take another list note, this is a rummy note, your one will be equal and we will take another, this will be equal to the next one, okay, and we will take this temp. What will we do now, will we keep the difference of whose event, so and we have taken one, why we did that, here I have told you because we have to connect also, go to the last, so we have to keep it, okay, we have done it, now we will run this loop. For how long will you run it, see what it means that when you have the value in and is in the next, then you do it, okay, if it becomes null, then you will not do it, you will go out, okay, so here OD. What will be the next of and do then you will move OD to OD equals tu order next and what will be the connection next of OD then now you will move and next ok then who will you connect in the next of OD will you do 10 to 10 what is starting The point is of your event, there is a difference in it, so what will you do after going to the headquarters, will you do it, right, this is the solution to your problem, I hope you have understood it. If you liked the video, then please like, share and subscribe. Thank you
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
3
hey guys welcome to yet another session by scala in this session we'll be looking into longest substring without repeating characters and we're going to solve this particular problem so before we move on please make sure to subscribe to scala's youtube channel so that you don't miss our upcoming videos and also leave a like if you enjoy our content and if you have any queries leave a comment down below and we would love to help you out with the answers so now let's understand what will be covered in the session first of all we'll be looking into a problem statement in the topic which i just said which is longest substring without repeating characters then we will be solving them by different approaches first of all we'll be looking into a brute force approach then we'll be looking into a sliding window approach and also a optimized sliding window approach so all of these implementations will be done using python and if you want to look into other implementations using java or c plus check out interview bit blog and that link is provided in the description so now without any release let's begin with this session okay guys first let's understand the problem statement of the longest substring without repeating characters so let's take a string s okay so this is the string s okay so this the task to find the length of the longest substring without repeating characters so how long a substring is there without repeating any characters for example in this case uh it is three and in this case again it is three okay because a b c b okay so basically b is characters which got repeated this w is characters got repeated another w okay so now abc is the longest substring without repeating characters among all the substrings so a b c again a is repeated so in this case b w no but w k e so or k e w so this is the longest sub string so w k is the longest substring without repeating character so this is basically the example which we wanted to show you okay so now let's take uh for example substring is a contiguous sequence of characters with a string view is a substring of string interview bit so even though individual is a regular uh term but not many uh repeating characters immediately for example one me repeating characters i and t one is i and i uh so it would be i n t e r v i yeah so till this it would be a non-repeating character because then e non-repeating character because then e non-repeating character because then e will be repeated okay like so you will basically have to look into like that uh so now this is a problem statement now given any string we'll have to figure out the longest substring without any repeating characters within the others of the strings okay so now there are three different approaches there's brute force there is sliding window and there is an optimized sliding window let's first understand all of these methods and then move on to the code implementation so first of all the simplest approach is to solve this problem to generate all the substrings of the given uh string and among all the substrings having whole unique characters literally from the maximum length so to put it simply let's look at the algorithm so to generate or generate all the substring of a string loop from the start till the end uh index of the string so let us consider start indexes i and indexes j so run a nested loop i is equal to 0 to n minus 1 and j is equal to i plus 1 till n so basically what happens is it will go from the very start the entire thing will be a substring and then one letter less one letter list so it will basically look into all the substrings and make sure that all the substrings are taken into account so now once all the substrings are taken to check if the substring contains all unique characters put all the characters in the set one by one if any of the characters are already present in the set skip the string else consider its length and maximize it so now every character will be put into a set and that set would be uh basically the thing which will be used to check these strings and if there is a character repeating that will be excluded and then they move on to the next string until and unless they find a substring with all unique characters in it right so this is what the brute force approaches it's pretty straight forward second comes the sliding window approach okay let's look at this particular so this is the algorithm uh if you guys want just have a look at it i'll be showing you how exactly it works from here so input string over here is java concept of the day character array over here so repeated so j a b a gets repeated okay so let's ignore that let's move on to a b because anyway a and a is repeating so let's move on to b so now v a c o n then c comes back so now c is repeating so now it's a five letter character without any repeating sub string so right now this would be considered the actual answer until they check the next one so now i will be taken from o now because the last repeating character was c so now it will be taken from o so o n c e p t and o are repeating characters okay so now repositioning the eye so the isd positioned to the same position from this place to this because it's o and then they start from the next letter which is n and n c p t o f and t is repeating so now the i will be moved to the character before the repeating character which is o then o f t h e d a y okay so now the longest substring without repeated characters is of the day if this was smaller than this then this would be taken into account that's how sliding window approach works it goes from the side to see the complete uh substring so now there's an optimized sliding window approach it's the same approach but a little more optimized so initially both ing are initialized to zero okay inj are initialized to zero expand the window one by one uh and check there are repeated characters uh stop when you find one so abc so a is i j is a so a i and j are a so this is how you figure out so i and j is equal to a so that basically means character is repeating so a b c are non-repeating so a b c are non-repeating so a b c are non-repeating characters so now start shrinking the window till there is no repeated character so i is taken uh till b because now uh from a to i so now b c a are non-repeating characters now b c a are non-repeating characters now b c a are non-repeating characters so now check again back to this so b c a but again a is repeating so now again move the i till a non-repeating character and the i till a non-repeating character and the i till a non-repeating character and then a b then again move the i to a non-repeating character then b a c then non-repeating character then b a c then non-repeating character then b a c then again move the i to a non-repeating again move the i to a non-repeating again move the i to a non-repeating character then ca so this is the optimized sliding window approach which is even more better which basically takes lesser time than this approach which is sliding window approach okay so in this case they're using a hash set as a sliding window right in this case it's by using a regular array so by using a hash set what they are doing is they are reducing the time taken to run the program which will take lesser processing power and uh also it will basically give you the approach uh give you the process uh the result in a very shorter time than the sliding window approach because these are the three different approaches i think you understood how the three different approach works if you want to look at the algorithm you can take a look pause and look at it so initialize left to zero right zero which is basically i is zero j zero then initialize the hash set store all the characters of the current window so index right toward end and then the uh right one moves and if it finds a repeating character it stops there and then the eye is taken to the next character so that there is no repeating uh character so then that is taken and then the same process is done again so this is optimized sliding window now let us look at the code of all three of them one by one and try to execute them and understand how exactly they differ okay first of all brute force approach let me just copy this before copying and moving on let me just quickly explain so start and end characters is equal to 0 x 128 okay so for then we have a for loop so this for loop is taking start n plus 1 okay so c is equal to s of y and over here you can see s is provided as hello this is a string we are taking uh and so we want to check what is the uh unrepeating character like length of the longest substring without repeating characters in this hollow string so s is taken over here so c is equal to s of i first s of i would be zero so if sfi the first character would be h so h will be taken and h will be checked first then from h they go to e they go to l and when they come to the next cell there will be repeating characters so the for loop would break it will come out and the length of s would be taken which would be three and then the result is zero right now and then they go to another for loop and they do same thing in this case they check the next string in order to figure out and they return the result so now the set what would it be in this particular case it would be hal which would be three then they start from low which would be two so hgl is basically the longest substring without repeating characters uh yeah so that basically would be number three so there will be three let's see if that's the answer over here i'm gonna paste run okay so three right uh what if i change this to scalar academy so the longest substring is 6 without repeating character so in this case s c a l e r then a is there so it is six so i think this is the longest one without repeating characters or even this academy also could be taken which is the again a longer substring without any repeating character so six is the right answer so now let's move on to the next part which is basically a sliding window approach see it's a much simpler approach in this they have to create two different for loops in this they just have one nested for loop in order to do all the required actions so now uh sliding window py right so now let me run this so answer obviously should be three i think i didn't copy the part where we have provide the substring and now you can see hello so the answer should obviously be three let me do something else like hello scalar now it is seven okay so sliding window works and finally the last method is optimized sliding window pasting it running it so the answer would be 3 but the only way you can figure out if something is properly working is opening up your own terminal your own thing and check out how exactly the time varies for all of these right so you can check out how exactly the information varies for all of this non the normal approach sliding window an optimized sliding window uh so this is basically the video i hope you guys have understood again if you want to look at other implementations of code in java or cps or other languages you can go check out the interview bit blog which is available in the description box below you can just click on it and you'll be taken over there uh and yeah so all the other implementations are over there you can read about the problem and try to solve those uh problems by solving it by yourself okay so that's basically it for this particular session guys thank you meet you in another session
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
80
hey everyone welcome back to the channel i hope you guys are doing extremely well so today we'll be solving the problem remove duplicates from the sorted array before moving on to the problem if you guys are new to our channel please do consider subscribing to our channel so the problem states that you're given a sorted array nums and you need to remove the duplicates yes in place such that the each element appears only once and return the new length now there's a lot of stuff written over here let me explain you what is written over here so basically you will be given an array and at the end of the function you need to return the length of the number of unique elements now you will be given a sorted array and if you see the number of unique elements over here is three so at the end of the program you need to return this length three and before returning this three you need to make sure that this array is modified and how will you modify this basically what you need to do is you need to place all the unique elements at the front like 1 comma 2 comma 3 so 3 elements are placed at the front and after this you know that there are still four places left in the array now in these four places you can place anything you want doesn't matter what they want is you need to remove duplicates and make sure that all the unique elements comes in front so the program wants you to return the length three so whenever you return the length three they i trade for the length three and check if the length three contains all the unique elements and it has removed duplicates or not so it is only checking for this portion it's not going to check for this portion so that is what the problem states so if you are in an interview and this problem comes up to you the naive solution that you're going to tell to the interviewer will be using a hash set to solve this problem what are you going to tell the interviewer is you're going to declare a hashtag which is initially empty and what you do is you iterate for every element so at the first you have one so you insert it into the hash set after that you move to the next one and when you insert it into the hash set the one doesn't gets inserted because you know any set doesn't stores duplicate next time when you go to 2 and you insert it into the set it stores 2 next time when you go to 2 it doesn't inserts it into the set again you go to 2 it doesn't insert it into the set because it's a duplicate next time when you go to three it inserts it into the set next time when you go to three it's a duplicate so it doesn't insert it into the set so basically you can say that the number of unique elements from the set is three by getting the set dot size so that's your length that you're going to return but before that you need to make sure that these three elements are placed at the front now you know that the set stores element in the ascending order so when you pick up the first element that's one you can simply take it out and place it over here after that you get the next element that is this two you take it out and place it over here after that you're gonna take this three out and i'm gonna place it over here so once you have placed all the elements of the set in the first three positions your task is done now it doesn't matter what you place over here what matters is all the three unique elements should be placed in the front so you have your size you can simply return it so if i talk about the time complexity of this brute force approach it's going to be a big o of n log n for the first time when you insert all the elements into the hash set because n for traversing in the array and login for inserting into the set and another big o of n to basically take the elements out of the set and place it at the array now imagine if the array doesn't have duplicates so you have to place all the elements from the set into the array so that's gonna take a big of n and if you talk about the space complexity that you are using is a big o of n because you're storing all the elements of the array in a hash set so that's about the brute force approach so before moving to the next part of the video i like to share some free resources with you so i'll be leaving the link in the description you can go to the link and check out all these free classes on different topics like backtracking segmentry hashing dynamic programming game theory binary trees and every other topic that you can see over here you can also find tracks related to beginner intermediate advanced and remember these classes are taken by top educators so these classes are free so please do go check out these free classes because they are really in an organized way and if at any moment they do ask you for a referral code please do use take you forward to watch all these free classes and it's absolutely free so you can also check out the new batch of an academy that's starting on january 8th that is the conquest 2021 where they will be teaching you all the topics from the beginner level to the advanced level in a duration of 52 weeks so you can pause the video and check out all the topics that they will be teaching week wise over here so just in case after watching the free classes and checking out the syllabus of the batches if you feel like getting a subscription you can check out the subscriptions and if you are willing to enroll you can use the coupon code take you forward where you will be getting an additional 10 discount so guys uh go check it out if you feel like taking it then only take or else you can watch out all the free resources that's available on the internet so the optimal approach will be to use the two pointer approach so what we do is so initially i keep the pointer i at one and we have one more pointer j so our j pointer is over here so we see that i and j are having same values so they're not different so i need someone different than one so what i do is i move the j pointer to a place ahead so at this point we see that the value at the index i and the value at index j are different so what i'm going to do is i'm going to move this i pointer to one step ahead and after that i'm going to take this 2 and place it over here that's a very simple step i'm just going to do an a of i equal to a of j and that's going to place it right after that since we have place 2 our next task is to find out an element which is not 2 so again we move j to the next guy so over here we compare if the value at j and the value at i are different or not so we see that both of them are two so we haven't found an element which is different than two so we move our g to next two now over here we again find a two so again that's not similar and we see two and two are equal so what we do is we move this j over here so this is the moment when we see that this 2 and this 3 are different so we have to take this 3 and place it over here so for that what we do is we move the i pointer one step to this and right after that we can do a of i equal to a of j that will make sure that a 3 is placed over here right after that we move j again we try to find out an element which is different than 3 so 3 is same so we again move it so the moment we move it we see that j is crossing the boundary and since it crosses the boundary we stop so the moment the j pointer crosses i can say i have my answer so currently i am standing at the second index yes i am standing at the second index and we have made sure that the modified array will look something like this 1 2 3 and as we know what matters is the first three elements so how do we get the number of elements i is currently standing at 0 1 2 second index so if we simply return i plus 1 we can get the number of unique elements and that's going to be my answer so if i talk about the time complexity it's nothing but a bigger of n because we are just hydrating over the array elements and if we talk about the space complexity it's a simple big o of n because we are doing the modifications in the given array only so right after this let's discuss the c plus as well as the java solution to this problem so in the java solution you can see that you are given the nums array so what we do is initially we check if the array is null or empty we simply return a 0 because we will not be having any unique elements right after that we keep a pointer at i equal to 0 and we keep a pointer j equal to 1 if you remember and we simply move on j till it doesn't crosses the boundary and what we check is if nums of j is not equal to norms of i because we are looking for an element which is different and the moment we get someone who is different what we do is we move i pointer and right after that it's very simple we just initialize nums of i to nums of j such that the element goes over there once the entire iteration is over we can simply return i plus 1 because it is the number of unique elements so now let's discuss the c plus solution so in the c plus solution you can see that you are given the vector nums so at the first step we check if the nums dot size is zero that means if the if you are given an empty vector let's return zero because it's not going to have any unique elements right after that i have the first pointer i at the first index that is 0 and we have a second pointer that is j initialized to 1 and we know that j will keep on moving till it doesn't process the boundary so what are we looking for we are looking for an element which is different than nums of i so we simply check if nums of j is not equal to numbers of i if that is that means it's an element which is different so what we do is we move the i pointer to i plus and then we simply initialize numbers of i to norms of j that means we just take that element of j and put it in nums of i so once you have done the entire iteration i can say that we have removed the duplicate and made sure that all the unique elements are right at the front so we know that the number of unique elements will be i plus 1 so you're going to return i plus 1 as the answer so guys i hope you have understood the entire approach along with the code so if you did please make sure you like this video and if you're new to our channel please do consider subscribing to our channel with that said i'll be wrapping up this video let's meet in the next video where we will be solving the next problem from the sd sheet
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. **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,1,2,2,3\] **Output:** 5, nums = \[1,1,2,2,3,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 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,1,2,3,3\] **Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\] **Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order.
null
Array,Two Pointers
Medium
26
394
okay we're going to use this example to expand the dfs algorithm here so initially uh in the dfl level one we have the parameter variable with result and then the current number what's the mean of that okay let's go further um so we have a little global pointer from here uh so when we find is a letter and then we assign the letter here okay when we go for go to the next one is another letter to append to depend on the result and then when we found it is a number here let's say it's two and then we're going to turn this at two and one point is five and then we're going to like um uh to module 10 and then plus five which is 25 so we extract the 25 to this location and then we'll when we find it's a left bracket and then we will go further we have another uh we go to the dfs level 2 and then we have a new result and then the new result as we will have is that what we found is sd right so we get st here and uh we have another caribbean number is to is three okay right and then we go to the next level and then we found that uh we will have another result as and then we will have current number it's just cd in the cd um and then and the current number is actually uh how many um it should be um let me see the code it's actually from zero uh okay so now it is actually zero okay so it is three okay it's a it's zero okay so let's okay so here's the point so when we find the right bracket bucket uh bracket and then it means that we were going to bounce up so it means we will get a result back to here result from level 3 which is actually cv okay so we will have to um attach the cv to um after this however because we have a current number so we need to repeat for three times so it's a first time second time the third time so that's the result that we will have for uh so far for the level two okay so as so now we go back to the level two so we no longer have the levels in the stream now so we have we were going to clean this and then we now we actually exist in the level two now look let's go further and then a and then we attach a here uh s what has s here and then the nine we okay um okay before we clean the level three we actually uh have to reset this to zero because when this number is already used to repeat uh append this variable here okay so um we need to append with zero and then now we find his nine we update him tonight and um let's go further is the left bucket bracket and then we're going to go to the level three again because the left bracket is always which trigger at the next level so we have the result as a and then the next one is so fun a and then the actually the current number is actually zero because there's no number here so when we find the red bracket we are going to bounce up again okay so now the we get the result a from level three right and then we repeat for nine times so that's the reason we will have uh nine is a okay so that's the result that as we have so far at this level okay and then let's now because we finished the uh this one so we need to reset zero and then we clean this and then we let's move forward a asd okay and so this is done okay so now we found another red bracket we finished the asd here we appended this in and broken and we bounce back so what moon bounce back it is what's up that means that we're going to return this level 2 result to level one okay so we have to repeat for 25 times so um yes i can actually uh copy and paste for 25 but for better explanations but to simplify my explanation so i'm going to assume that it's only two okay so it's only two here so uh we're going to append for one time second time so that's what we have for uh for the stream so far okay so yeah initially we have 25 because i don't want to come communicating my explanation so that's the reason i attempt that let's assume that we only need to uh repeat for two times okay so far the level two is clear and then the current number is zero okay and then after that uh we will go further and then to append that let left uh the rest of the letters to the uh stream so that's the reason we need to copy this to here okay so that's the total num total the final result of this uh input okay thank you okay so this is the corresponding code that will that what we have uh based on this uh explanation that i have just have okay so initially we will have a global pointer so this one is the global pointer so you move from left to right okay and then we have a stream builder so the result so this one is the stream builder okay and then we have the uh current number and then this is the korean number here and then we use the just this for loop to uh to scan all the elements here so firstly we get a character here right so let's say take this action as an example so we find the la uh it is a letter right so and then we will uh and then we will append this to the result okay maybe i should expand a little bit again um so let's say it's a it's 80 right so if we can define is a letter so we append this to the result and then we find is two and then we update as two and later we find is a number right so we find a number uh we will update this one to the current number and then later we find the left bracket so we when we find the left bracket so we're going to jump into the next level of dfs i mean next level of dfs okay but each time the i will uh increa increase for one have one inc increase and then we will continue uh is the difference actually we're going to call it call yourself okay for itself and after if so let's say so we have okay so now we have a result as sd right term as three right so this is what we have for this one actually uh this return is actually where go deeper until we have this uh level three which is uh sv and her number is actually zero so what we're using this way to do the dfs and when we have the two like the uh we need to return the see return the cv to this level and then we will have to repeat for uh actually uh two times right we have to repeat for two times yeah so for example so cv will repeat for two times and then we set the three to zero so that's the way we do this uh so somebody asked what if the um so what if the um we don't have the current number then we don't even append the if the cv here no the problem is that if we don't have this even have the current number so in so it means that the cv is already append with in this curve okay and after that and yeah okay another important thing is that uh when we find the um right bracket right so that's the most important part so when we find the right bracket right and then we're going to return right we're going to return this to um to the result okay so that's the total uh explanation for this code you can combine with the uh the video that i had in the first five minutes to check together with the code
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
89
all right let's do this question gray code if you want to make a sequence of two to the power of n integers where n is the input given into your function and every integer has to be within the range zero to the power of n minus one if earth's integer is zero every integer is unique in the sequence and every adjacent integer diffuses by exactly one bit first and last integers also have to differ by one bit so how do we do this well let's take um let's take an example we have n is equal to two that means we have two to the power of two numbers which is four every number has to be in the range zero to 2 to the power n minus 1 so has to be one of these numbers but in some order such that these two conditions are met okay well what are these in binary we have zero one two and one zero one okay they differ by one bit so that's fine these differ by two bits so that's not good and the first and last differ by two bits as well so we have to kind of reorder this such that these two conditions are true i was only able to figure out why a certain pattern worked after i like tried out a certain pattern so i get yeah it is i guess that's why i have so many dislikes it's always good to in these kind of situations to start with the simplest case possible so if n is equal to 1 we have 2 to the power of 1 which is 2. so in that case we could just do 1 0 1 so that will be a sequence we know that's the answer what if we to take this and just reverse it so we have 1 0 so we have this sequence here and what do you notice about this is that uh oh this is valid we have zero one they differ by one bit this is valid this is not valid oh actually yeah this is not valid because they differ by zero bits the first and last are not valid because they're different by zero bits so what if we just prepend a zero to the first two so these still differ by a one bit and add a one to the second half so these still differ by one bit but now because this the first bit transitions from zero to one here now these no longer differ by zero bits they differ by one bit and same as the first and last one so here now we have a new sequence and this new sequence is four has four numbers in it so that's four um n is equal to two so this will be the answer for n equal to two now we just continue the pattern for n equal to three why can't we just like repeat this uh what we just did well let's see if i take this sequence copy it and just you know reverse it so you have one zero one two zero look what happens here well obviously these two the silicons from here to here differ one by one bit because we've ensured that in the previous sequence same as this half here but this the two middle ones differ by zero bits and the ends differ by zero bit as well so if you just add a zero bit to the first half and a one to the second half then that would fix that issue and it's neat in that this is actually um eight numbers which is two to the power three and we just continue that pattern and that's pretty much it all right so that's pretty simple let's try to implement that so we have a base case which is a vector of n's let's call it the answer zero one let's go through uh starting from one and i uh equal to one i less than n plus i we can create a copy of the answer let's call it temp it's an answer we can reverse it so reverse temporary.begin temporary.begin temporary.begin temporary. and i'm going to make sure to prepare a 1 to all of these numbers by going through each value make sure it's a reference to each value in temp and say v plus equals to a one bit shifted i times so for example if n is equal to two then we'll be going through the number zero one here and we'll be adding one bit shifted one time so essentially if you have a zero one here let's just pad a zero at the start we'll be adding one zero here and the ones are here to get a total of one zero and one then we can push back to the answer or insert to the answer's end the temporary.begin and temporary.end temporary.end temporary.end then return the answer that's one let's try the two and 16 is the max all right yeah that works awesome so yeah that works see if we can make it faster actually get the size of how large the current answer is so we get the size and then maybe we could go through starting from s minus 1 all the way to j greater than 0 minus j and do now enter the pushback answer at j let's store the offset one bit shifted i times plus the offset and then that should pretty much do the same thing hopefully oh i should be greater than or equal to zero so let's try 16. cool all right let's see if that uh improved this speed a little bit okay so i'm not still settling for the speed here let's see what happens if i do um answer the reserve so that's the reserve sum amount here what do you reckon so i need one bit shifted end times that's how many num numbers i need answer.pushback zero answer pushback one let's see if that's any faster oh yeah a little better hmm i don't think it can get any faster than this because let's uh let's see what the time complexity is how many time how many iterations will this be run will this be would push back be called will be it will be called exactly uh to the power of n times so this is linear in 2 to the power of n and so it shouldn't be any faster than this because no way you can like avoid pushing back two to power of n numbers to the arrays so yeah this is the optimal type complexity thanks for watching like and subscribe and i'll see you in the next video
Gray Code
gray-code
An **n-bit gray code sequence** is a sequence of `2n` integers where: * Every integer is in the **inclusive** range `[0, 2n - 1]`, * The first integer is `0`, * An integer appears **no more than once** in the sequence, * The binary representation of every pair of **adjacent** integers differs by **exactly one bit**, and * The binary representation of the **first** and **last** integers differs by **exactly one bit**. Given an integer `n`, return _any valid **n-bit gray code sequence**_. **Example 1:** **Input:** n = 2 **Output:** \[0,1,3,2\] **Explanation:** The binary representation of \[0,1,3,2\] is \[00,01,11,10\]. - 00 and 01 differ by one bit - 01 and 11 differ by one bit - 11 and 10 differ by one bit - 10 and 00 differ by one bit \[0,2,3,1\] is also a valid gray code sequence, whose binary representation is \[00,10,11,01\]. - 00 and 10 differ by one bit - 10 and 11 differ by one bit - 11 and 01 differ by one bit - 01 and 00 differ by one bit **Example 2:** **Input:** n = 1 **Output:** \[0,1\] **Constraints:** * `1 <= n <= 16`
null
Math,Backtracking,Bit Manipulation
Medium
717
1,837
okay let's talk about the sum of digits in base k so you so the base is no longer 10 is it could be six it could be anything else and you're going to return the sum of the digits so three and four if the base is ten then it's three plus four right so uh what you need in your answer and then basically it's normal it's pretty standard and it's just plus equal to m mod k and then you divide by k every single times and you return answer that will be your answer and let's check okay it's pretty straightforward so the timing space is all over one you are not using anything for the time is actually the length of the end like if there is two digits or like three digits level your answer for time capacity and others learn that peace
Sum of Digits in Base K
daily-leads-and-partners
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Output:** 9 **Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9. **Example 2:** **Input:** n = 10, k = 10 **Output:** 1 **Explanation:** n is already in base 10. 1 + 0 = 1. **Constraints:** * `1 <= n <= 100` * `2 <= k <= 10`
null
Database
Easy
null
65
hi there so today i want to talk about this question uh 65 value number so it's um the question statement is quite simple uh given a string we want to determine whether the string can be interpreted as a decimal number uh here are a whole bunch of lists of examples about uh what counts as a decimal point what's not uh you know you have your integers fractions uh some abc which is if we are dealing with hexa hexadecimal it might be okay but in this case no a space in between and a invalid character here so that's false 10 2 e 10 which is uh 2000 no not 2 by 10 to the power of 10 quite a big number negative 90 multiplied by a thousand that's also a valid number by the decimal number one e what so it's missing uh digits after the exponent so it's not valid uh e3 but you don't have the number in between before e so it's also false you get the idea so it's your typical common sense kind of a notation for the decimal numbers both you know the mostly used and a little bit more scientific kind of notation here both are supported so the code should support that um just a quick note here i find i guess in the test cases there are case there are situations like 5.0 or 0.1 there are situations like 5.0 or 0.1 there are situations like 5.0 or 0.1 those kind of cases i personally use this quite often for point uh point something i use this for my thresholds uh probabilities in my code uh you know like if the um you know logo if the probability is uh over 0.5 i classify this as something so over 0.5 i classify this as something so over 0.5 i classify this as something so for that the threshold i use point just being lazy not to type the extra zero before that and five point as you sometimes see in the programming languages i want the uh the number to be actually in of type float so but the number is just looking like an integer so i just add a dot to force the force that the programming language to treat this like a float uh the compiler or the interpreter not the language itself but you get the idea so this uh these two are valid the notations and uh the i think the test cases in the elite code actually has those so um i think our code should support those as well um that's uh pretty much the question um here it says that the statement is ambiguous we should gather the requirements and uh you know just asking questions about what should we cover what should what we don't need to worry about ask a lot of questions before we actually code anything but in this um in my setting it's not interactive just me talking and nobody on there you know the other side in real time so i'm just going to take and take all this as given to me uh so here we have the list of the things that could potentially we need to deal with in the string we determine the decimal point so it's just which are the digits 0 to 9 exponent the character e plus and minus sign and a dot uh so that's pretty much the uh i think they're missing one thing that's the empty space are okay if they are placed uh you know in both sides uh so if it's beginning with some extra white space or end with some extra white space it's okay we could either call a trim or in the code we're actually dealing with white space as well and that both are fine so that's pretty much the question um so uh so this is the time that when we pull out the regular expression kind of knowledge if you still have that you use that uh daily uh not daily uh often you might still remember that it's actually quite simple so like i'm gonna just uh note that i'm gonna use regular expression but uh i'm gonna convert that into some other kind of code that doesn't require the regular expression library because in i guess in interview time they may say hey you shouldn't use what if you can't use regular expression what would you do so i'm going to talk about that after the regular expression kind of a solution so just in general what kind of uh string are we expecting i'm just going to use the underscore to represent some empty space here so in the fullest possible kind of a thing the you know the valid decimal number string which contains all the possible elements in there it's going to be i'm just use that as an example here so it will be some extra space in the beginning and we have maybe like a positive sign and then some number a dot some more numbers and exponent character e and some other numbers and then we got a bunch of extra space in the end so that's the um the possible you know valid decimal number string which contains pretty much all the possible stuff in there so let's just quickly look at and the thing here we have extra space in the beginning at the end which are optional you know optional um let me actually use this to indicate that so it's a you know it's a group kind of thing and the plus minor sign here is also optional uh we've got some digits here you know um which can be zero or more actually and it's also optional um it could be optional um and we got a dot which is also optional but if we have a dot then it must have at least a digit so i'm gonna put this here um so the data is optional but if we actually have a dot we need to have a digit uh how do i represent that um yeah it's this the whole the two thing combined it's optional so we either have no dot or we have a dot and the digits afterwards and some more digits sorry and we got a e here uh the e part is also optional so the whole chunk is optional we got an e here we got a optional plus and minus sign and we got some more digits so you know by analyzing the fullest the possible uh valid string that decimal number string will pretty much come very close to the actual regular expression pattern that we're gonna use so i'm just gonna use a new line here to code the pattern so it's uh we begin with some extra space it's uh zero or more white space in there we got a optional sign in the beginning and then this uh i think this is a little bit sloppy i should actually break this down here the digits here um and let me code the easier part uh first and then come back to this so just leave this as open and closing brackets there i'm going to revisit the stuff here later so we're going to end with potentially some more white spaces and we have one optional section for the exponent so it's exponential sign and potential sign and the digits it has to be at least a one and can potentially be many so that's that part here we can have uh zero or more digits but there are two cases here one shoe one should capture the five point case the other one should capture the 0.1 the other one should capture the 0.1 the other one should capture the 0.1 kind of situation so it's a or here and for the first one it will be a digit some digit and a dot but the dot is optional so we can have uh the in you know pure integer cases like a phi zero or something and this first uh first the stuff before this all here it's capturing that like 5.4 55.3 like 5.4 55.3 like 5.4 55.3 you know something like that the stuff before the dot will be captured by this pattern and since we have a you know zero or many digits gear after this or here it should capture all the remainder fraction number there the other case is that we start we actually start with a dot and then it's a mandatory that we have to have at least the one digits after the dot because um if you just have one dot there and then directly followed by e it's not okay so that's what we put here so a dot and immediately followed by a digits so that's the pattern let me quickly check if i made a mistake um yep i think it's uh it's the pattern here and for this co for this problems of purpose we just try to see whether the input string matches this part so that's a that's pretty much the uh regular expression state uh solution uh let me try it around that this is the sum of the test case that i put in there let me actually put more point zero 0.1 um so 0.1 um so 0.1 um so let's submit this um so it works and um and you can see that we actually have quite a few different uh kind of like a state here internal state if you talk about if you think about this regular expression uh whether we are still marching the initial empty space or we're dealing with the possible negative positive negative signs or we are in the bigger big here which is a little bit complicated about the actual number there and or we can once we process the number we find the e then we enter the territory that we have to deal with this whole thing about the um you know the scientific notation exponent stuff here and once we finish that we can if we see an empty space we then uh you know enter the phase that we're dealing with towards the end um so if there's nothing but empty space in the end we can pretty much say that this number is a valid decimal point so there are a lot of intermediate kind of state here and based on what kind of a character what kind of symbol you see you can potentially transform into you know either the intermediate next state or you could jump into the possible next state so if the you know if the if there are options here optional state here so um you know every regular expression can actually be can be understand by making a finite state machines gear so if you don't know finance state machine it's a just think about us think about this as a graph you have a lot of state like the initial state or we're dealing with the possibility of positive sign or negative sign we're doing the actual number there we are dealing with the exponent there those are the state of this regular expression or this code in general and there are the letters are considered to be the edges that can you know that's linking between different states in the program and it's a directed graph and it can tell self loops you know you keep seeing the same digits it's repeating that's what the asterisk here or the plus sign here says you know when you see repeating digits you're just looping back to itself this state itself um yeah so i'm doing a terrible job explaining this but the thing is that if we are not allowed to use regular expression we can pretty much code up the uh this state machine uh you know or you can just think about it as a direct graph and actually in this question since last time last week last night i talked about the topological sword if you think about this one and you ignore those self-pointing edges and you ignore those self-pointing edges and you ignore those self-pointing edges this is actually you can derive a topological ordering on this graph if you build it as a direct graph so um let's talk about how we can code up at this finance league machine basically for the finance the machines you will have a transition function which here i'm just going to use a matrix to represent each row is going to be the state and each column is the input which it's pretty much what you see here the digits exponent sign decimal points and empty space and some invalid stuff like abc so i'm going to lay out the matrix here so just use some comments to see which column represents what input i see they are pretty much the edge in the director graph so we have a space let's actually just use the regular expression thing here i know words might be more readable so we have space we have sine we have digit we have dot we have exponent and we have some invalid stuff so that's going to be the columns for this matrix and which corresponds to the edges in the graph we're going to have a few quite a few different rows each row represents a state and the column represents a by doing that edge to what state we can get you know transfer it into so i'm just going to put it here delta state input rnp is going to tell us the next state so yeah so the next state is going to be by doing this or if you can think about this as a function it takes the state and the input as the two arguments and you return you the next state so that's also a way to think about this i'm going to align this with the column name here some of the state that we have just looking at the regular expression pattern we definitely have a loop here which is before we starting to do any kind of matching um and we definitely have a space here uh oh no we actually have a sign here the space is uh when we see space it's still in the unit part unit state so we have the um this part so when you see or in the regular expression it means that from the previous state we can actually try to go to two different uh paths one is to the states represented by the uh the first uh the left staff from the or the other edge the other kind of option is to go to the other direction so we go to like a digit and dropped two options if we go to the digit route it would be something like a five point if we go to the dot route it's uh it's the number that's starting with a dot so for the dot it's actually required that we have a dot or with a digit there and actually dot was digit those two combined it's equivalent to see that we finished the this stuff here uh i'm just going to call this number state so once we have a digit after the dot it's a valid number and then we enter the optional exponent stage it will be things it's not all it's a sequence of things this should be three different state here we see when we first see the exponent sign that's one state we have in the optional e and sine state and we have another one which is the e with digits so that you can see that the e is a state and there are two different nodes afterwards one is the sign and the other one is a digit so the e would go to both but for the sign it has to follow the it has to have a link directly pointing to this um yeah in interview time we have a whiteboard we just draw the graph there but here i'm trying to do my best to explain this i hope you get idea so e with e sign and e digit i'm just going to call it this to state um and after that we have a end state which i think it's uh when you finish everything and see uh extra space or maybe the end of the string kind of a character indicator we're going to call it a successful ended and let's actually just call it success and we're going to have another state called fail so basically doing this is going to be we start with initial state and for every character we have we're looking up we treat every character as an input just gonna transition into the next state um you know doing a full loop through the input string and in the end we want to find whether we are in the success or in the fail state so that's pretty much the goal of uh by doing this so let's just code on the number of rows that each will represent which will be cos one to one of the state that i laid out up there it's uh if you have the regular expression there it's not difficult to come up with the states we've got init we've got a sign um just kind of popping pieces do some nice formatting so that next time when i see it i still understand what the column and the rule means otherwise all i would say is just a bunch of numbers so this is uh init is zero sign is one two is a digit three is dot four is the number actually i'm just going to call this uh yeah number five is e six is uh e with sign and 7 is e with digit 8 is 6s we got one last line which is the fail so that's the transition matrix delta matrix transition function um the states are called um the status called what i forgot the i think the input i call sigma state i call q right the in the notation um i don't remember it's been so long um so basically we can find that uh for the very last row if we are in fail whatever the input we take we're gonna pretty much just stuck in there so we're gonna have one two three four five six nine in there should yeah i should prepare this a little bit better than this does not look nice yeah i think you get the idea if we asked if we are currently in a successful state uh the only thing that we can still see uh it should be space if we pretty much determine this as a valid uh you know valid the decimal number and we see signs digits dot exponent or any kind of thing it should lead us to the it should transport us into the fail state the only thing that we can accept is empty space so that's uh that's what this here says i'm just going to copy this paste you know what the last row is easy the last column is also easy it's going to be all nine if we see a invalid no matter what state we are in we're going to end up in the field so i'm going to just go ahead and populate that all as well so i do hope that we have a whiteboard for doing this otherwise it's uh quite a pain so let's look at the rest of the stuff from the beginning i guess if we're in the initial state the only thing that we can accept is this three this four uh if we see a exponent it will be the situation is like uh directly e up front it will be uh not okay so this is nine and if we see a dot we directly enter the third state so it's uh here uh if we see our digits we get into the second uh second state number two if we see a sign so it's a it's pretty straightforward you see if we see a empty space we're still waiting for the first uh meaningful stuff to happen so it's a self-pointing loop it's a self-pointing loop it's a self-pointing loop image if we see a sign we enter the sign state if we set digit we enter the digit state we see a dot we enter the dot state quite straightforward so far so good then if we are in the sign state what are we expecting is um we no longer expect a space if we see a space we should go to the fail part and we don't want any extra sign as well so that's what the this example here says if you have a minus or if you look at the expression the we it's a one-off plus or we it's a one-off plus or we it's a one-off plus or minus we're not expecting more than one in there so that's um that's a nine and if we see digits we just go to state two if we see dot we also go there um if we see exponent it's the same rationale it's uh it's not okay so that's the uh transition function for the state sign then is the digits are what are we expecting is an optional dot or some more digits or the exponent so there are three columns here that should be non nine so we will see or we can all the way go to the back you know a single digit number like nine so this first column is actually eight we succeeded if we have something like uh zero space or zero end of the string we should go here for sine so it's a nine four digits we are still with we stay at the same state the dot will cause us to directly go to four not three but four so this might be a little bit tricky here um uh when we see a dot we actually go to four not three um exponent then we go to five so that's the state transformer function for the state digit here then we start populating this for dot what are we expecting when you look at the regular expression the only thing that we want to see is a digits so everything else should be nine only the this column should be something uh it will be the number state it's four here everything else should be nine and for four we're pretty much out outside this or here the thing that we expecting is a digit more digits exponent or empty space so if we see empty space we succeeded so here is the 8. if we see sign that's not okay if we see more digits we stay at the same state here if we see a dart dot that's not okay exponent we go there so that's the state transition function for uh state four and five is the exponent we have two options the plus and minus sign the sign or we see digits that's the only two edges that we have so for this row we're going to have that most of those are nine and two things that's not nine which is the sign and digits so for the sine we'll go to six for the digit we go to seven everything else should be nine and when we are the design the only state that we want to go to is the digit the only edge we have is there is this one so everything else is going to be nine seven and so here they really lost the line here everything that the all the stuff that we're expecting is more digits or empty space so it's a eight here nine this is a self loop self pointing edge everything else is nice yeah so this is the delta the state transition functions based on the current state and the input which is the next character that we have in the string this 2d matrix is telling us what's the next state so with this in hand we should just parse the characters by characters from the in the info string and in the end we want to see whether we are stuck in this success we are in the success state so state is initial state is zero and we're gonna for each of the characters um we're gonna convert that into the uh convert we need to find the columns basically we're going to write a helpful function very soon to handle this convert this character into the column identifier and the updated state so just taking this i'm just gonna name this input um so in the end we should return the state equal to eight which is the successful state we actually have the early stopping if any given time point that we find we get into the fail state we should return false and so i mentioned that this space also function as the end of the string so in the end um to make the case like uh just a regular number there go did in go to the eight here we do one final transition here the input is going to be empty space so it's uh zero so this force the force us to go to the succeed you know in whatever case that we have just uh just a you know good old integer number or decimal number or a number with the exponent or number with some more extra space those four different cases will be forced to go into the success state with this one final transition so that's pretty much it i'm just going to code up the conversion here so if it's uh empty space we should return zero it's pretty much just looking up before this column numbers yeah i'm going to just load with numbers as well if it's a voice space we return zero if it's a sign we return one if it's digits yeah so it's a pretty much uh just to convert the input character into the column identifier and for each of the characters we find the columns we find the current state and just do the state transition and do some final checks on the state so that's pretty much it um let me actually run this through all the examples and uh submit this as well yep so it's working um i'm glad that i'm not messing up with this graph here um so you know ideally when doing real interview time you have whiteboard you can draw this graph it's not so messy and you know actually most of the edges here are nine if you choose not to draw the um you know fail state as uh as an extra state you if you only draw stuff you know from one to seven that's also okay you just identify uh some of the state might be potential you know in the end if it terminates it should leads you to the successful state i guess in the most simple graph it should be eight nodes a little bit better a little bit redundant we just have a one node to sync all the successful paths and uh one extra node to absorb all the fail nodes the fail state it should be ten nodes on the graph depending on how you draw it should be between 8 to 10 and the edges are just the characters and um and yeah that's pretty much it if you use this you will be sure that you cover all the possible possibilities you know compared to try to reasoning through it and try to use if and else to cover all the cases um it's quite dangerous if you are in real stressful interview settings you're gonna miss a lot of things the benefits about writing this transition function is one is that they know that you actually know how to solve this more robustly than writing a hand wrote a bunch of if else statement so even if you mess up some of the number here the interviewer might jump in and actually help you but for if and else if he's not really following you he's not going to be able to help and the other thing is this gives you a systematic way of thinking about what's the state and what's the possible action how i'm transforming from one stating to another so this gives you a kind of like a systematic or framework way of reasoning through all the possibilities so you are less likely to make mistakes in interview time so i personally highly recommend this approach yeah so that's pretty much this question and the my personal preference of how to solve this um i just don't think that uh writing a regular expression is what they are looking for um because if you are expert in gurus in the writing x expression regular expressions you're going to finish this within five minutes and uh that's not good um so yeah so this is what i recommend so that's it for today
Valid Number
valid-number
A **valid number** can be split up into these components (in order): 1. A **decimal number** or an **integer**. 2. (Optional) An `'e'` or `'E'`, followed by an **integer**. A **decimal number** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One of the following formats: 1. One or more digits, followed by a dot `'.'`. 2. One or more digits, followed by a dot `'.'`, followed by one or more digits. 3. A dot `'.'`, followed by one or more digits. An **integer** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One or more digits. For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`. Given a string `s`, return `true` _if_ `s` _is a **valid number**_. **Example 1:** **Input:** s = "0 " **Output:** true **Example 2:** **Input:** s = "e " **Output:** false **Example 3:** **Input:** s = ". " **Output:** false **Constraints:** * `1 <= s.length <= 20` * `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
null
String
Hard
8
367
all right today's question is valid perfect square and this question I'm going to go over two solutions the first one will be binary search that's probably something that I would implement in an interview the second one is using a Babylonian method so if you knew about it and you could implement it I would definitely implement that one because it performs better than binary search but binary search is something that we can you know generally recall and do in an interview setting ok so the first method of binary search okay so quickly the question is given a number if you can square root it and that square root is a regular you know integer numbers or no decimals then we return true so 16 if we square root it's 4 so that's fine 14 is going to give us some number between 3 &amp; 4 so give us some number between 3 &amp; 4 so give us some number between 3 &amp; 4 so that is not a perfect square okay so with binary search what we have is the me reset this up is I came up with some big number so 1 4 5 9 2 4 scroll out here 1 4 5 9 2 4 so it's this blue line right here now if we could use square roots we would discover that it's a perfect square 382 but since we don't we're going to limit our guests between 1 &amp; 1 4 5 9 to limit our guests between 1 &amp; 1 4 5 9 to limit our guests between 1 &amp; 1 4 5 9 to 4 so this between the first number and the last possible number and then we're going to probe the middle so this white line is our probe into the middle and then we get the square of this white line and you can see that it's a really big number way bigger than 1 4 5 9 2 4 so that means our answer is somewhere on the left side so we want to shift our right window down to where the middle used to be so in this case I could just copy-paste 7 2 9 6 2 &amp; 2 here could just copy-paste 7 2 9 6 2 &amp; 2 here could just copy-paste 7 2 9 6 2 &amp; 2 here or I'll just be divided by 2 for now okay so now we have a new middle probe and it's still way too big so we divide it by 2 again or you know shifting the right towards the middle and then we keep on going you can see now we're starting to get close to the answer but we don't know that this is the answer but let's see where around here now and let's see on the seventh we're here on the 8th now we're in a case where the square of this number so 8 1 2 9 is actually smaller than our number so 1 4 5 that means we are under estimating it now and we need to shift the left window back up so what we'll do is this is our middle probe so we'll shift the middle or shift the left window up to the middle so here would be 286 and you can see now our middle probe is a little bit closer to the answer and like that our middle is just going to keep jumping around here until we finally get to this middle answer so binary search is o log n solution so you can see here if we take the log of this number 1 4 5 9 2 4 that means in roughly 17 iterations we'll keep jumping back and forth and we'll hit this middle line or I mean at worst 17 duration we'll definitely find our answer okay let's try coding this out so here we'll have our left window and our right window and while left this less than or equal to right we will probe the middle there's our probe into the middle and now we want to square it okay so we've squared it we want to test if square is equal to num then we're done we found our answer otherwise I've square is greater than them you want to shift our right side down house so that means we underestimated it you want to shift that left side up until we find our exact answer so if we start bouncing around but we never found a number that equaled true and then we get to the point where left is greater than right then that means we can return false we couldn't find our answer now the one thing I failed here is that I didn't check for integer overflow so an integer can hold 32 bits so for a signed integer that means it can hold - this number right here but if I were - this number right here but if I were - this number right here but if I were to just take any number say 50,000 and I to just take any number say 50,000 and I to just take any number say 50,000 and I were to square it I'd get a number a lot bigger than what an integer can hold so that means we're going to get an integer overflow and these equality and inequality checks just go out the window like they're not correct anymore so what we want to do is here is the biggest square possible by the largest integer so that's you know this number and then we squared that gives us this humongous number and then what we want to do is we want to use a long instead so a long holds 64 bit so two to the 63 minus one gives us the biggest number that our long can hold and you can see this number is definitely bigger than this number so I'll be able to hold the biggest integer squared no problem okay so one more thing here we want to also cast one of these two along because mid is an int so mid times mid this will just still be an int we're just growing it's storing it into a loan so we want to make sure that we cast it during the operation here okay that's try submitting this cool all right so on to the second method is called the Babylonian method so the general I mean I'll leave a link for how to do it or the why it works it's on Wikipedia but the general gist of it is that let's see the general gist of it is you take a guess for what your solution could be so for a number like 1 4 &amp; 5 9 - 4 you know usually a like 1 4 &amp; 5 9 - 4 you know usually a like 1 4 &amp; 5 9 - 4 you know usually a square root has around half the number of digits so since this has six digits we'll just take a guess that has three digits and then we'll +1 to be safe so digits and then we'll +1 to be safe so digits and then we'll +1 to be safe so that's a 1000 so this will be our first guess we'll just guess 1000 and you can see if we do 1,000 squared it's 1 see if we do 1,000 squared it's 1 see if we do 1,000 squared it's 1 million and 1 million is much bigger than 45,000 so it's an overestimation which 45,000 so it's an overestimation which 45,000 so it's an overestimation which is fine now the idea behind the babylonian method is if you have this number and you have this number so one four five nine two four divided by this number we're going to get an underestimation so think about it like in regular numbers that say our number is 16 and our first guess happens to be 8 so 8 is an overestimation because 8 squared is 64 but you know that if we take 16 divided by 8 that's 2 this is an underestimation so our goal is to find the average between those two so we have 1,000 plus this and then we'll take the 1,000 plus this and then we'll take the 1,000 plus this and then we'll take the average so 1 over 2 ok so there is our average and that's our next guess our next guest so we started out with 1,000 next guest so we started out with 1,000 next guest so we started out with 1,000 our next guest put us to 5 7 2 and let's see if we were to do this again I'm gonna put in our next Gus of 5 7 2 &amp; 5 7 gonna put in our next Gus of 5 7 2 &amp; 5 7 gonna put in our next Gus of 5 7 2 &amp; 5 7 2 here now we're at 4 1 3 so a lot closer to 382 so that's repeat this again 4 1 3 4 1 2 3 and 4 ones three now this algorithm is guaranteed to converge that means it will converge eventually at some number when we take this to infinity but we can stop a lot earlier we can stop when all the digits before the decimal point don't change any more so here is our fourth iteration and then for our fifth iteration we do 380 to 382 and you can see here we are already correct by this point 382 and then 382 ok and you can also see now we've only guessed one two three four five iterations versus in our binary search version you know we were already on the 8th or the 9th iteration before we even got closer to starting to bounce around so this converges a lot faster than the binary search okay so that's try coding this out so our first goal is we want to get a guess so create a guess so you want to figure out how many digits are in this number so that's digit equal to zero and then this is how we'll find out the number of digits so while temp there's not equal to zero we will divide it by ten and digits plus so you can imagine let's say temp 123 what will happen is we will divide it by ten so that gives us 12 point three but then because this is an integer this gets truncated and now our digit equals one and then we will do one and then digit equals two and then at the very last we will become one divided by 10 which is 0 and digit equals 3 so this gives us that this number has three digits so our guess is going to have digits equals the digits divided by two so half the number of digits plus one to be safe so that we have an over estimate okay so now you want to convert this into our guess so int gasps equal to one and now we will just do four I guess digits greater than equal to zero digits - - you know we can do just x equal ten - - you know we can do just x equal ten - - you know we can do just x equal ten that means let's say digits was three we'd go one and now we go one times 10 which just gives us 10 and then 10 times 10 gives us a hundred times 10 gives us a thousand so this gives us our correct four digit guests in this point at this point okay so now we have our guests so all that remains is to finally run the báb babylonian method so we have our you have to keep track of the previous so that we know when to stop and while previous does not equal to guess what we want to do is we want to set the next guess so guess will be equal to 0.5 so it's a so guess will be equal to 0.5 so it's a so guess will be equal to 0.5 so it's a float times guess minus or plus numb / float times guess minus or plus numb / float times guess minus or plus numb / guess so again guess is the over estimation now I'm / guess is the estimation now I'm / guess is the estimation now I'm / guess is the under estimation and we're trying to get the middle of that so that's the rough intuition for how this Babylonian method works and then if we'll set previous or yeah we'll set previous equal to the guess and then we overwrite the guess ok so a couple of things we should watch out for really I want this to be a float because I want the decimals to be carried over so we're comparing it I'll cast this to an int that way we're only caring about the digit so when we do 382 point zero one test if it equals 3d2 it will return true because I casted this to an int so that the decimals go away okay so there is that and then at this point we've converged at some guess so all we have to do is check if previous times previous is equal to num then I can return true we also want to test if previous plus 1 times previous plus 1 is equal to none we can also return true so that's like if it's three two point zero one we just want to make sure we test 382 and also 383 because we're not quite sure where it is until we run more of this algorithm but since we stopped early we'll just test both sides so 382 and 383 okay so if those two don't work then we can return false here all right let's give this a go that's the previous equals gasps oh okay so we want to also cast this here and all right that's the two solutions I've got for you today and I'll see you on the next one
Valid Perfect Square
valid-perfect-square
Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_. A **perfect square** is an integer that is the square of an integer. In other words, it is the product of some integer with itself. You must not use any built-in library function, such as `sqrt`. **Example 1:** **Input:** num = 16 **Output:** true **Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer. **Example 2:** **Input:** num = 14 **Output:** false **Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer. **Constraints:** * `1 <= num <= 231 - 1`
null
Math,Binary Search
Easy
69,633
1,643
hello everybody today on yeet code we'll be solving leaked code hard difficulty question number 1643 cape's smallest instructions we'll be doing this in the python programming language in this video i will go through the steps that i took to get to an acceptable solution throughout the video if you feel like my patients may be a little bit too slow or too quick feel free to skip or pause on any of the sections that you need let's get right into it bob is standing at cell 0-0 and he wants to reach at cell 0-0 and he wants to reach at cell 0-0 and he wants to reach destination row column you can only travel right or down you're going to help bob by providing instruction for him to reach destination the instructions are represented as a string where each character is either h going right or v going down multiple instructions will lead bob to destination for example destination is 2 column 3 both hhhvb and hvhvh are valid instructions however bob is very picky bob has a looking number k and he wants a k flexible graphically smallest instructions that lead them to destination k is one index given the integer array destination and integer k return to k lexical graphically small construction that will take bob's destination let's look at the constraints uh row one column are upper bound by 15 okay k is going to be between 1 and n choose r where n is row plus column and r is rho so before we go ahead and you know start working on this problem it's important to again understand what lexicographically smallest means in a previous problem that we encountered uh we also have this term show up in the problem if you still don't know what this term means i recommend you going back to that problem or again googling what this term means so let's move on to the question now uh i think it will be useful for us to jot down some notes before we go ahead and try to code things up so let's say this is the uh the ray that bob is trying to traverse this is the top left corner where he starts at and he wants to get to the bottom right corner which is the end uh let's say this array has height uh n and let's say it has with m the final instruction stream is consists of h's and v's right and we know that the final instruction string has to be of length n plus n right and we also know that the final instruction string has to have exactly mhs and nvs so let's just drop this information down real quick the length equals m all right why is this the case well for him to go from here to here while only allowed to move right down he has to move m rights and he has to go and downs right makes sense when i first came across this question what really helped me out was the example that the question gave me specifically looking at this list so what is this list is all the instructions of length five with three h's and two v sorted in lexicographic order h v is the first one and b v h is the last element do you see anything uh any patterns that is hidden within this list do you see any thing related to the h's and v's and how they're placed and how why how a specific way of ordering the h's and v's puts them in the order of the list well let me show you what this pattern is let's just use that example here again so let's say this is that list of sorted uh lexicographically sort of strings right so what do we have strings of three streams with three h's and strings with three h's and two v's and let's say i have a line here that splits this list into two what's on the left-hand side well the what's on the left-hand side well the what's on the left-hand side well the left-hand side will be left-hand side will be left-hand side will be all the streams that start with h and what's going to be on the right hand side well it's going to be the strings that start with v how do i know how many strings are to the left well what is the form of a string here it will look something like this correct it's h followed by a substring consisting of two h's and two v's so how do i calculate the number of strings here well this boils down to a combinatoric statistics question depending on where you come from so what the number of strings that are to the left is basically just four choose two right because you know there's four things that all can change there's two h's that i can do and two v so four choose two what about here well strings that start with v again what are the strings that look like here well it's v followed by three h's and a single v right substrings composed of this form again how many strings are to the right well applying what i did here wouldn't that just be 4 2 3 what are we trying to find in the original question well we're trying to find the cape lexicographically smallest instruction let me just copy that here so we know exactly what we're working with and let's box that okay so remember this list is sorted lexicographically already right so the k lecture graphically smallest instruction will also be the k element in this index that means k has to be to the left of this line or to the right how do i know if it's to the left well if k is less than or equal to the number of strings that start with h then i know that k will have to end up in this left region right otherwise it has to end up in this right region do you see what i'm doing here i'm kind of doing like a binary search of sorts if i know it's in the left region i don't have to look at the right region anymore i know k is in this left region so then i have to focus on this smaller subset right do you see where i'm going that if you still don't see what i'm going at let me explain so let's say that k actually ends up in the right region it's uh greater than the number of strings to start with h then i know k has to be in this list the sub list of the original list right what are the strings here well like i said earlier they all start with v and they are followed by three h's and one v in some order right well since this list is already electrographically sorted and all of these all the strings start with these what i can do is i can essentially remove the ignore the v and this list will still be lexographically sorted right again i'm gonna do the same thing that i did here with the line i'm gonna draw a line down somewhere in this list this line will divide this list into two strings here are strings that start with h and here are the strings that start with v again you see where i'm going at now i'm working on a smaller sub problem every time i know if k is to the left or the right i move to a smaller region so now what has the problem become instead of finding the k element in this list i'm finding the k minus uh let's say okay let's use a variable here instead of uh so we don't get confused let's say k minus a string in this list what is a is just the number of strings that start with h here in the original left region so let me just write that down now you can see the pattern right i can essentially construct my i can construct my final solution one by searching if k is to the left of the right if it's to the left then i know i have to add h to my final string if it's to the right i add v to my final string let's code this up okay so let's have two variables m and n this corresponds to you know the width and the height what would m be well let's see here destination zero corresponds to the number of v's corresponds to the height so that should be destination zero index zero and then my m would be destination one we said earlier that the total number of characters in the stream is m plus n right and we know that the total h is possible that we have to have in our final string is equal to m the total v's will be equal to n so the way up like i said earlier the way i'm going to construct my final solution string is i iteratively add one character one at a time so i start with the empty string and i basically just iterate total times so while total is not equal to zero i have to do some stuff what i do well it's that line drawing right i compute how many things are to the left and i check to see if k is greater to number of things to the left how do i compute the number of things to the left well i have to use this mathematical formula the combinations right and choose r how do the entries are function can be called with and i what is n is total and i what is n is total and i what is n is total and what is r in this case well if i pick what does it mean to be in the left-hand side left-hand side left-hand side i pick an h right so the r would be total h's minus how many h's that i have currently in my string minus one so this makes me i have to keep track of the number of h's that i have and the number of these that are currently in my solution stream okay so after doing this computing left i check to see if k is greater to the left if it's greater than left i know i'm in the right region right so what i do i add one i know there's one extra v in my current string i add that v to my string and remember here you know the prob the sub problem changes oopsies the sub problem changes when i you know when i traverse left or right so i need to make sure that i update my k so k minus equal left which is the number of things to the left otherwise i know i'm in the left region so what is that is just simply equal to current i just need to update my number of h's update my solution and that's it and at the very end what i need to do is just return solution okay the problem is this is not going to work you'll see what's wrong in a bit there's a small caveat okay apart from that is the syntax error there's a small caveat that you may ah okay see here value error k must be a non-negative integer non-negative integer non-negative integer what this means is this value here total h is minus curve h's minus one may be less than zero so what case what hap what is the case when total h's minus curve h is equal to zero well that is the case when we draw this line down the list there is literally nothing to the left there are zero strains that start with h so we have to go to the right we have to pick v so we just simply do this and this will make ensure us that we always pick v if there are no more h's to pick and now i believe the solution will work and it should work because i already did this before so let's see ah okay and it does work so let's analyze the runtime of the solution since m and n are both constants right well yes they are constants they are less than equal to 15 in fact as per here all this whole while loop takes a constant number of iterations and all the operations i do here but this operation are all constant this operation are all constant this operation are all constant operations so it all boils down to how fast this operation will finish uh i not sure exactly how uh i not sure exactly how uh i not sure exactly how uh runs how fast it runs but at the end oh just the runtime of this whole solution would just be equal to the runtime of just be equal to the runtime of just be equal to the runtime of okay and that's it for today uh this is the second problem that i will go through in a series of leak code problems uh i'm just you know this is still a pretty new series that i'm trying to do and i'm open to any you know suggestions or critiques that uh you know i since i don't know how well i'm conveying my thoughts if there's anything that you think that i should change let me know down below leave a like comment or subscribe and as a wise man once said elite code problem day keeps unemployment at bay
Kth Smallest Instructions
number-of-nodes-in-the-sub-tree-with-the-same-label
Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`. The **instructions** are represented as a string, where each character is either: * `'H'`, meaning move horizontally (go **right**), or * `'V'`, meaning move vertically (go **down**). Multiple **instructions** will lead Bob to `destination`. For example, if `destination` is `(2, 3)`, both `"HHHVV "` and `"HVHVH "` are valid **instructions**. However, Bob is very picky. Bob has a lucky number `k`, and he wants the `kth` **lexicographically smallest instructions** that will lead him to `destination`. `k` is **1-indexed**. Given an integer array `destination` and an integer `k`, return _the_ `kth` _**lexicographically smallest instructions** that will take Bob to_ `destination`. **Example 1:** **Input:** destination = \[2,3\], k = 1 **Output:** "HHHVV " **Explanation:** All the instructions that reach (2, 3) in lexicographic order are as follows: \[ "HHHVV ", "HHVHV ", "HHVVH ", "HVHHV ", "HVHVH ", "HVVHH ", "VHHHV ", "VHHVH ", "VHVHH ", "VVHHH "\]. **Example 2:** **Input:** destination = \[2,3\], k = 2 **Output:** "HHVHV " **Example 3:** **Input:** destination = \[2,3\], k = 3 **Output:** "HHVVH " **Constraints:** * `destination.length == 2` * `1 <= row, column <= 15` * `1 <= k <= nCr(row + column, row)`, where `nCr(a, b)` denotes `a` choose `b`​​​​​.
Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Counting
Medium
null
227
Hello hello everyone welcome to days gone back to the family channel live wallpaper have a great time today even before starting video lemon juice compound juice I hope you will have a great time today and join with friends family also want to believe world subscribe More Like Subscribe Now Subscribe subscribe to subscribe and subscribe the Subscribe That Learning Session Option Multiplication and Division Suresh Cleaver Presentation Like Created This App The Basic Calculated To-Do List Code Two to 7 Basic Calculated To-Do List Code Two to 7 Basic Calculated To-Do List Code Two to 7 to subscribe Video Channel Please subscribe and subscribe the Channel Please subscribe and subscribe Loot Siddh Incoming Request Singh Duplicate subscribe for More Video Subscribe David O
Basic Calculator II
basic-calculator-ii
Given a string `s` which represents an expression, _evaluate this expression and return its value_. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`. **Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. **Example 1:** **Input:** s = "3+2\*2" **Output:** 7 **Example 2:** **Input:** s = " 3/2 " **Output:** 1 **Example 3:** **Input:** s = " 3+5 / 2 " **Output:** 5 **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consists of integers and operators `('+', '-', '*', '/')` separated by some number of spaces. * `s` represents **a valid expression**. * All the integers in the expression are non-negative integers in the range `[0, 231 - 1]`. * The answer is **guaranteed** to fit in a **32-bit integer**.
null
Math,String,Stack
Medium
224,282,785
307
hey what's up guys uh this is chung here again so this time again today's daily challenge problem number 307 range some query mutable so this one is very classic a range query problem right as you guys can see from the title so i mean i want to use this problem as an opportunity to revisit the segment tree all right okay so we're given like an individual ray nums and you need to handle multiple uh queries for the following types right basically we you know we can we should be able to update a value and we should also calculate the sum right the range sum between left and right inclusive right so this is exactly the two operations that you know the segment tree is trying to try to improve right so and yeah and you we just need to implement this class okay and so here example right we have a rain we have a array here that's the initial numbers right and then we have range sum from zero two and we update uh index one uh into two and then we do a range sum again that's how we get this output here and some constraints right so we have i think this is a 10 to the power of 5 maybe close to that 3 times 10 to the power 4 so it's on the same scale right i mean obviously a naive implementation will be we simply just maintain a list of numbers right and every time we do the update right we simply just do update by using that the index of that of the list and then we do the to the sum right we simply loop through we use the index to calculate uh to basically to lean to scan this in this array at least from left to right and obviously you know the update is all of one time right but this range some range it's going to be off and time so with the same number of costs right uh can be made to update and arrange some you know update of course this one is one right but the worst case scenario is that you know every cost every car is like a range sum which means that you know the worst case scenario the it's going to be uh of n square time complexity right so that's why it's a little bit too high given this kind of a range this is constraints here right that's why we need we want to sorry we want to improve this time complexity from this one to un log n that's when the segment tree comes to rescue because with the segment tree both the update and the green query can be login instead of a 01 and on right this is because the tree structure right because you know in the tree structure you know uh the login comes from the height of the tree right so if the tree is kind of balanced right i mean both update and the query can only depend on how the height of the tree which is the log n yep so and let's talk about the second tree right and for this one you know uh we i'm going to use the uh the filmic tree aka the binary index tree which is also another kind of the segment tree because the binary index tree used the uh the binary calculation right which is even faster than the regular segment tree okay so let me bring out the blackboard so a simple segment trace like this or a binary index tree so the root is zero and then we have one two three 4 5 6 7 8 9 10. so i'm going to explain why the binary index trade looks in this way looks like this way because the value we're looking at should be in this should be its binary value instead of the orange value which this one is like zero one right so this one is uh zero one zero okay this one is zero one 1 same thing for this one 0 1 0 right this one is 0 1 0 and this is 0 1 same thing for this one right 1 0 okay 1 0 1 and 1 0 right so that's the binary value for each number here from 0 to 10 there could be more right but i'm just using this small one as an example so why we define like a binary the tree structure in this way this is because you know if you look at the parent each parent and child pair so for example three and two so the only difference between uh between the uh the parent and child is that you know there's only one there's only uh if you remove the right most one then the child becomes parent right so for example if three how can you use three to find two right because if we remove the right most one then three becomes a two right same thing for this five for this one if we remove this right most one the five because becomes to four same thing for the six here right if we remove the rightmost one this six also becomes a four right same thing as seven the reason seven is under six is because if we remove the right most one then seven becomes six okay and this crack characteristic allows us to use a certain expression to quickly find the parent from the card node and in the segment tree so the value stored in each node is a range sum so which means that you know in this let's for example this two right so in the two the value stores in this uh in this two is what it's zero it's a this is a some value from uh zero two to two same thing for three right so three stores the value from the current from the parent to the current node which is uh two to three so keep in mind that you know the parent is exclusive and the current node is inclusive right same thing for five right four is like same thing for zero to four right and then this node also from parent which is four to five okay and the six is from four to 6 right 7 from 6 to 7. right so on and so forth so i'm not going to write everything and so if we define like a tree structure this way right and at least you know when we do the query let's say we want to query the value from 0 to 7 right so how can we create the value from zero to seven right as you guys can see there's a path right so all we need to query is that we just simply need to query the path starting from seven and then we need we will go all the way back to zero to the root right and then when we reach the root you know if we summarize everything along the way then we'll get the range sum of 0 to 7 because when we go from 7 to 6 we have the ring sum from 6 to 7 and then from 6 to 4 we have the ring sum between four and six and then from four to zero we have zero to four and if we uh summarize everything together we have zero to seven that's why you know uh the range query is log n right because we only traverse from the cardinal to the root which is log n time complexity right so that's the range sum and we already solve it how about the update right so the update is a little bit complicated because you know uh let's say we want to update the values in uh in index five right index five obviously you know we need to update this uh node uh this index fives node because that's the value it's in right but not only we need to update this one there's more there's no more uh node we also want to update we uh which one because five is also included it in the range of four to six right so this six this sixth note also needs to be updated anything else yes you know this one eight right because eight because five is also included from zero to eight right until we have reached the end of the segment tree basically you know when we do the update there also be some uh nodes we want to update so now we have two requirements right so first one is the uh it's a range query basically given the current index how can we uh traverse back to its parent node right all the way to the end and second one is update basically for update uh let's say from here we need to find all other nodes that's inc that we need update in this case it's six and eight right all right so let's work on the a simple the simple one which is the range query uh which means we only need to find the parent right so if we look at the uh the binary values from let's say for example for seven right every time right we just need to remove the what the rightmost one since we already talked about that right so let's say we have zero one zero right if we want to remove this uh right most one so what should we do uh if we can get this one right if we can get this one you know we uh we can simply do a subtraction right between these two or you know subtraction is the same as xor right basically if we do x or between this two you know what we'll get what we want which is one zero right same thing for this one right for seven if we can get the uh this one and then we can simply do a xor but how can we get this version basically this version is the you know we only have the right most uh value right most we only keep the right most one and all the remainings will be zero and so the way we're getting it is by doing like this i the value uh bitwise end to its negative value so that's how we get that value you know and i'll show you how right so first we need to understand how can how are this negative value being calculated in computer right so in computer you know the way we're calculating the negative value you know this you know is we need to convert it into a into what into a into its uh the true code complemental code so which means that you know because so the reason being is that you know in computer worlds uh when we do the calculation there's only a plus or add there's no subtract because computer doesn't know how to do the subtraction all he knows is to do the add so for example if we have a one plus two of course this one is equal to three right but if we have one minus two you know computer doesn't know this uh this minor sign so which means the computer will convert this one into a one plus a negative two okay that's how the computer does the calculation so which means that we need to somehow find a way to represent this negative too instead of right that's why you know we're going to use the complement to code for the adrenal code when we need to do some calculation with the negative value because you know the complement code the complemental code can represent both the positive and the negative value okay and how can we get the complemental code right so in order to get a complemental code we need to get its uh once uh compliment code first and then we do a plus one so one more thing so you know for all the positive values you know the complemental code is the same as itself so we don't need to worry about that so here we're only talking about an active value and so to get uh the complementary code for negative values so what do we do you know let's say for example we have this kind of uh 0 1 0 i'm sorry 0 1 that's the that's 7. if we want to get the negative 7 how do we calculate that right so we have uh let's just use a eight bit to represent this negative seven because you know actually you know in reality actually one integer has like how many bytes i think eight bytes right eight bytes means eight times eight which is six four bits if we just write all 64 bits here it will be too much too long that's why uh so here i'm only using two bytes to represent an integer okay so for seven you know for negative seven you know the first one is the first uh the first bit is the sign right which means you when it's one it's near it's missing active then we have negative seven here okay so to get the complemental code of negative seven the first step is to is we have to do a one's complement which means that you know once complement that you know except for the first sign bit we reverse all the remaining bit values so that's why we the one stays the same and then we have one and then zero right so this is the ones complement uh of negative seven right and then from one's complement to the complemental code we do a plus one right so now we have okay so let's look plus one here we have one zero one right so that this is the complemental code of the negative seven which is the actual code the computer uses to do the calculation right so now we have this one and so this is the uh the negative i right and then we do x uh n with what is what with the uh which original i which is this one okay zero and then zero one right so we do end with this one so what's the value of this one right as you guys can see so that's the exactly the values we're looking for okay and this one 1 0 one zero oh sorry my mistake uh zero one that's the that's exactly the valid work look we're looking for here right because only the last one is one with this one and if we do a i minus this one right or what you can do x over here right that's how we get the uh the parent value which is six in this case right cool so what uh let's do it for six all right just to make sure it is not a coincidence right that we get the correct value so for six we have again we have six is this right six so the negative six right so the negative six is what so one zero and then zero one zero right so that's an active value so we do we get the ones complement which is one stays the same and then we reverse the remaining one zero one right and then we do a plus one to get a complementary code right so one zero one right so that's the complementary code that's the negative six in the computer and now we do a end with the six itself zero right and then uh zero one zero right so what do we have here to end here zero oh there's a mistake here so this one yeah after doing the plus one uh we have this one zero right that's an active six and then if we do our end with the original one we have this zero one zero right see this is exactly the ones we're looking for right because and then after we're doing this uh subtraction or a bitwise xor right with this one we'll get right okay cool so that's how we get the uh that's how we get the parent right and then we simply just use this same formula right on each node to keep going until we reach the root right soft right and so that's how about the ring how about so we already saw the range query how about update right so for update like i said you know let's say for example we want to update five right so what we need to find six and eight but how can we uh navigate from five to six and from six to eight right if you watch closely and remember this part we get is the uh is this one which is the uh we keep the right most one right and then we set everything else to be zero and then we do a subtract right if instead of doing a subtract if we do a add then we'll get what we need right because take a look so from 5 so what's going to be this that's i x uh and uh minus i it will be 0 1 right because that's how we get this right most one if we do it subtract sorry if we do add plus between these two we'll have what we'll have we have this one right 0 1 0. and from here if we do the same thing right we have what we have 0 1 0 right this is a part of this one and if we do a plus again what we have eight that's how we get eight let's see it's magic right cool and that's how we get how we use this same part and we simply flip this uh this sign here so we can find both the parent and the next node that we need to update and that's about it for the binary index tree and with those in mind the implementation is pretty straightforward okay so now let's start coding then finally so we have first we need to create the tree right so for the tree it's going to be the let's get the length first and it's going to be the length of numbers okay and we're also gonna store the numbers since we need to do the update later okay numbers so for the tree at the beginning everything's zero and the length will be the n plus one so the reason being is because seven plus one because the root note remember the root node zero is a diamond root node basically uh in the binary index tree the root zero doesn't mean anything it's a root for everything so which means you know we will need to do a plus one to reserve that index zero as the root so which means the remaining nodes starting from one okay and then first thing first we need to initialize the binary index tree because we have numbers we so which means we will need to somehow we need to update construct the tree right so we have for i dot number right in enumerate numbers so which means we're gonna insert each the numbers into the tree one by one uh so and here we have update you know let me create like another helper functions here let's call it updates tree okay so here we have a cell and then we have index and we have a value okay so here we do a self dot update tree right so the index is i plus one dot numbers dot num this is a number so here remember uh index zero in binary index three is reserved for the dummy root which means we cannot update that roots node right that's why you know the first numbers the first actual number have in the binary index tree will have the index one instead of zero that's why when we do the update three here we always do i plus one okay and now let's do the update right remember so the update is what update is simply just a loop find the next nodes that includes the card this index right that's why we have this wire ios smaller than the dot n because you know n is the maximum index in the tree right so we have self dot tree dot i we plus we increment by the value and find the next one remember that's how we find the next node we want to update right i and minus i right so that's all this object tree need needs to do now for the range sum right we'll implement this update later on because you know after initializing the update tree that this entire tree we can do the range sum right so the ring sum we have left and right and then let's define like another tree function let's go called get sum right so we have self and i so the sketch sum means that you know given like index i it means that we want we'll it'll get all the value right between zero with an index uh zero and an i right so the answer is equal to zero and for this one all we need to do is just from this current index we need to find uh other parents right until we reach the root so well i is greater than zero because if i equal to zero that's when we need to stop right and the answer gonna be self.3 dot i right self.3 dot i right self.3 dot i right because each node uh stores the range from the parent to the current node and then to find the parent remember we simply uh use the neck the other subtract i and this one right or we can use uh or right bitwise or and b the y is x over here right that's how we regardless okay so and then we return the answer in the end cool that's how we get the sum the range sum and now we have implement this two binary index tree uh function we can start implementing this our class function here so first is the range sum range array right remember so range we want to get the from the left and right but here we only have one parameters right between from 0 to i pretty easy right so we simply just do a ring query twice so the first one is the right so the right we're gonna do a right plus one remember again right so this so every index uh that passed in to this class is zero based and the index uh in the in our binary index tree is one based that's why you know we will do a right plus one here to get everything from zero to right and how can we get the range from left to right so we simply subtract the value from left right actually this one should be left plus one and then minus one right because you know from left to right this is a this is inclusive so we need to uh this one to write minors this one to left minus one right but since we're doing this kind of plus one minus one this one will be the same as that as left in the end and that's how we do the range summary right and pretty straightforward and now the update so the update actually we're updating a value right we're updating the values uh from one value to another okay so how to how can we do this one uh this one actually we can do it in a very similar way as how we initialize the sec uh the binary index tree is we simply need to get the difference uh between the car between the new value and the old value that's why we need to we still need to use this uh array to maintain that right so we get difference and then we do a update right or we update the values in the index to the current value and then we update the tree uh it's gonna be index plus one as always and then the difference right so we just need to update the difference because we have a tree here right i mean so when we do the update right let's say we update this one this is five i remember right so here it stores the range sum because we have if we know the difference we simply just use that difference update all the nodes that include five that will give us the updated range sum for each node and i believe that it yeah i think this should work yeah let me run the code here click accept it and submit right cool it works right and yeah i think that's pretty much it is right i mean the main purpose of this problem is just to implement uh the segment tree in our case it's the it's a binary inductory right and this is the two parts the two most important expression that you guys need to remember right how to how do first is this first one is this one how to get the parent from the current node second one is how can we get uh the next node right that can that include the current i which means that the node needs to be updated and other than that is a field of combiner stuff like the uh the one based zero base and then this update thing right so it shouldn't be too hard after you have implement this tree structure cool i think that's pretty much it is and thank you for watching this video guys and stay tuned see you guys soon 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,525
hey everyone welcome to my channel in this video i'm going to try to solve this problem at the same time i'm going to follow the general interview steps while trying to solve this problem so first of all let's have a good understanding about this question so number of good ways to split the string so you're given a string as a split is called good if you can split s into two non-negative non-negative non-negative non-empty strings p and q non-empty strings p and q non-empty strings p and q where is concatenation is equal to s and the number of the distinct letters in p and q are the same so return the number of good split you can make in s so essentially is something like we can split the string into two parts the left part and the right part and we want to make sure that the red part and the left part have equal number of distinct characters so for example for this one i assume we should have two goods place one is aac and aba and the second way we split is we have aaca and ba so other splits are not uh good splits and for this one i think we only have one split which is in right in the middle and this one we should have all right okay so we should have four of the good splits and so on so forth for the example four so let's see the constraints it says that as contains only lowercase english letters and the length of the input string s is anywhere between 1 to 100k so if the length of s is 1 then we should directly output that 0 because i would treat it as illegal because it says we should make sure that this after display p and q are not empty but um except for that i don't have any other ash case that worse to think about i think okay so after understanding the problem um and the thinking about ash case the next part is about finding solution so how are we going to solve this problem the first thing that comes to my mind is we could use a i mean of course we could uh enumerate all the splits and for each of the half uh for each of the split we can just count the number of distinct characters in the left half and the right half and do the comparison that is going to be a n square solution so essentially you should be we should be able to do better than square so the thing that comes to my mind is we could use a map um so we will have two maps the but each map is essentially the same idea so each map is going to keep track of the uh the character and the corresponding frequency within the substring so the key is the character and the value is the frequency so we have two maps the first map we call it the left map which record the uh character and the corresponding frequency for the left half after the split and the right map uh record the character and the frequency for the right half of the string after the explanation so in this way i would say we need to do two paths through the string first of all we need to do one pass to generate because we need to enumerate all the split we definitely need to do one pass first to generate the map for the right half and then um we go with the left half so uh having said that we are going to do two pass through the string and uh we are looking for like on which is linear and represents the length of the string well we are looking for a linear solution for this one since it says that s only contains location in lowercase english letters i assume the map the size of the map is no larger than 26. so in this way it is going to be on which is linear for the runtime and it is o1 for the space complexity so i think it should be the best solution regarding the runtime space currently so having said that let's start to do some good work on top of this approach like i said um we are going to um well if s is only contains one letter then we it is an ash case but actually it should be able we should be able to cover the edge case in our general implementation or the general coding part so we are going to have a map the character to frequency map character and integer i would call it uh first call it like the right map this new hashbag so we are going to do one pass through this map as for the string um well this will be car s start to car array we go through each of the character within the input string and try to update the right map so write map.put the right map so write map.put the right map so write map.put um this will be c and red i've got get or default this would be c zero or n plus one and after that we have a good write map um we are going to have a map which keep track of the character and the frequency in the left half of the map so during the second iteration through the string we are going to try to increase the frequency of the character in the left map and decrease the frequency of the character in the red map so if the frequency of the character is zero then we just remove the key from the map so during so in each side we are going to compare the size of the left map and right map in case they are the same we are going to increase the we are going to have a variable which is called number of good splats in case the size of the left map and red map are the same then we are going to plus this one all right so let's do it let's go to zero and smaller than uh it should be s dot less well it should be smaller than s l s minus one plus i because like the first split uh for the first split is as we are going to include one character in the left map and the rest is within the right half so we definitely don't want to include every character within the left half so that's why i have i smaller than s dot lens minus one so during each time we are going to say okay left mapped output well this should be so car c is equal to stop car at we get the corresponding character in the place i and we put the character into the left map so c0 and plus one and then at the same time we are going to update our right mic you're going to say okay right map dot put c right my dots get c minus one if um right mac dot c is equal to zero then we are going to write map dot remove the c from the map let me do the comparison if let my dog size his eq size is equal to right math dot size then we are going to plus the number of digits plates and finally we return uh the number of good splits so we are done with coding after coding we are going to do some testing for simplicity i'll just rely on this platform to help us do the debugging work all right so we have character integer new hashgraph it says cannot find the symbol so which symbol are we trying to carry okay so this is a uh this is some syntax arrow okay so after fixing it seems to be good let's run through some other examples okay so it's good let's do a summation for it all right so we are done with the coding for this uh question so that's it for this video in case you have any questions feel free to leave some comments below if you like this video please help us channel i'll see you next time thanks for watching
Number of Good Ways to Split a String
queries-on-a-permutation-with-key
You are given a string `s`. A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in `sleft` and `sright` is the same. Return _the number of **good splits** you can make in `s`_. **Example 1:** **Input:** s = "aacaba " **Output:** 2 **Explanation:** There are 5 ways to split ` "aacaba "` and 2 of them are good. ( "a ", "acaba ") Left string and right string contains 1 and 3 different letters respectively. ( "aa ", "caba ") Left string and right string contains 1 and 3 different letters respectively. ( "aac ", "aba ") Left string and right string contains 2 and 2 different letters respectively (good split). ( "aaca ", "ba ") Left string and right string contains 2 and 2 different letters respectively (good split). ( "aacab ", "a ") Left string and right string contains 3 and 1 different letters respectively. **Example 2:** **Input:** s = "abcd " **Output:** 1 **Explanation:** Split the string as follows ( "ab ", "cd "). **Constraints:** * `1 <= s.length <= 105` * `s` consists of only lowercase English letters.
Create the permutation P=[1,2,...,m], it could be a list for example. For each i, find the position of queries[i] with a simple scan over P and then move this to the beginning.
Array,Binary Indexed Tree,Simulation
Medium
null
190
hey folks today we are going to solve a lead code problem which is reverse bits so the problem statement states that uh we will be given an integer uh an unsigned 32-bit integer so what we are unsigned 32-bit integer so what we are unsigned 32-bit integer so what we are supposed to do we are supposed to reverse all the bits of that unsigned integer for example let's say we have the number four here n equal to four so what we are supposed to do uh we are supposed to reverse all these bits so the basic idea is that the last bit will go first in the result like this one will go first like here this one will go here and the number one is going to go here and this process will keep going until all bits are exhausted in the given input so this way we can reverse the number i think the problem statement is pretty much clear so we can move on to the basic approach so that is going to be so for ease i'm taking in a smaller version of the given input like i'm taking only six bit of it so n equal to four so it's going to be 0 1 0 so the reverse of this is going to be you know this one will come in the first place the last one will come in the first place again 0 1 zero and zero so the output is going to be eight right so the basic approach needs memory space so the approach is very simple uh i'm going to store all these bits uh in an arian and stack and i'm going to reverse it based on the given data structure and then i'm going to compute the two powers for it so let me tell you with that with an right dry run of this so i'm gonna take a stack for ease let's say this is our stack so i'm gonna start from this position what i'll do is uh i'm seeing an 0 here so i'll push 0 into my stack and then i'm going to right shift so this 0 will be gone and then i'll be at this position push 0 right shift it this position 1 this position 0 right shifting it i'll be at this position again 0 right shift it this position lc and 0 in the end so i'll right shift this so i'll be at here and i'll have no more bits here so i'm exhausted so this is my desired stack so what i'll do is we know that this is a six bit uh you know integer i'm going to start with two part six so that's how we actually compute you know convert the decimal to binary to decimal so what i'm going to do is i'm going to pop this one pop the top element and multiply 2 power 6. uh if you don't understand this computation you have to go through the basics of conversion of decimal to binary and binary to decimal so when i'm when i pop this i'll be at here so this represents to par 5. i'm going to pop this also to part 5 and similarly i'll be at here representing to par four so zero into two power four plus pop this one go to here one into two part three pop this one go to i mean we'll go here to part two zero into two part two pop this go here to power one zero into two power one pop this so now we have emptied the stack so that means we are ready for the computation so what the output is going to be 0 plus 8 0 plus 0 so the answer is going to be 8 so we got the basic uh you know we got the desired output so the time complexity for this approach is going to be big of num represents the number of bits and space is also bigger of num because we are storing all the bits that are that represent the number so obviously uh this approach is right but the interviewer will not be happy with this approach and there is room for a bit of optimization in this approach so i am taking the same example for the optimal approach which is number four uh only considering six bits of it and i'm considering a variable result for storing a result and for the optimal approach you just need to follow these three steps to you know get the desired result so the first step is left shift result so irrespective of the you know binary number which is one or zero by binary bit which is one or zero you just have to left shift it which means that you are increasing the number and the second step is going to be check if it is 1 in n or i mean in n or if it is 0 in n so that you can change if it is 0 or 1 in the result the third step is to write shift as we know that we cannot for loop the bits we just have to write shift and left shift to get the uh you know positions that we want so let me you know if you don't understand it's okay i'll try run this approach then you'll get a clear idea about it what we're going to do see the number is 0 1 0 and we have res equal to 0 initially so firstly the step is i'm going to left shift it is going to be 0 initially okay and then you know this points generally here i'm pointing it uh it is not a pointer but i'm just using it for the reference uh so i'm checking that if this is zero or not so it is zero when it is zero i do not perform any operation and i just uh proceed to the third step so i am going to right shift it so this zero will be gone now i will be pointing to zero one zero at this position so i'll repeat the same process so firstly right shift i'm in left shift you'll get 0 and i'll check if this is 0 or not yes it is 0 so i do not perform any operation and move to third directly so i'm going to right shift i'll be at this position so now it is going to be 0 1 rest equal to you know this is right so now i'm going to left shift again so i'm getting three zeros and one so now i see there is a one so what i'm going to do now i'm going to perform an xor with the rest in order to get one in this position so that is what we want we are left shifting because to get a position in the result right that's what we discussed in the you know during discussing about steps so what we are going to do we are going to perform xor with zero one you are going to get zero one so this is going to be the rest numerous okay once this is done i'm going to you know right shift it come at this position uh zero so rests i'm going to right shift i mean left shifted so zero one zero so hence it is zero i'm i do not perform any operation move directly to the third step right shift it go to this position now this becomes 0 1 0 again right shift this position 0 1 0 done i'll get this as my output rest so this indirectly represents less equal to eight right so this is going to be the optimal approach you do not have to maintain an array to do this you just have to perform these three steps until all the bits of your given input are exhausted i hope the optimal approach is pretty much clear so let's go to the code the c plus code so this is going to be the c plus approach so initially we are taking the result as we have already discussed so what i'm going to do is i'm going to perform you know this loop so that i can you know have all the positions of the 32-bit 32-bit 32-bit input so this is the left shift operation so that i can add zeros or ones to the result and then if the number is one like the lsb is one what am i supposed to do i must i am supposed to add one to that result okay so that is what we did the xor operation okay and then we are going to delete that how do we delete the lsb of that integer we are going to do the right shift operation that indirectly means we are deleting the lsb so that we can get the uh lsb which is next to it so this process uh keeps on going for the 32-bit keeps on going for the 32-bit keeps on going for the 32-bit uh till we get the reverse bit reverse number of that given bits so once the loop is run for 32 times uh the output is returned so time complexity of this approach is going to be of num i mean big of num uh so num is number of bits as usual and the space is going to be big of you know one because we are just using an a single variable to get the result we are not using any array or stack though it represents like that but we're not using it so let's just run this code yeah so the approach is very clear i hope you guys like this video if you enjoyed this video please do like share subscribe and do not miss to hit that bell icon thank you so much
Reverse Bits
reverse-bits
Reverse bits of a given 32 bits unsigned integer. **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`. **Example 1:** **Input:** n = 00000010100101000001111010011100 **Output:** 964176192 (00111001011110000010100101000000) **Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**. **Example 2:** **Input:** n = 11111111111111111111111111111101 **Output:** 3221225471 (10111111111111111111111111111111) **Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**. **Constraints:** * The input must be a **binary string** of length `32` **Follow up:** If this function is called many times, how would you optimize it?
null
Divide and Conquer,Bit Manipulation
Easy
7,191,2238
91
hello everyone so today we are going to see another interesting problem decode base and we are given a string yes which consists of digits and we have to convert the digits to alphabets in order like a starts with 1 till z ends with 26 and how many ways we can convert the string to characters or alphabets is the output so let's understand the problem with an example consider if a string given is 226 in how many ways we can convert this numbers to strings for example if we are going to consider each digit separately that is two separately and six separately then the string it can form is b and f suppose we are going to consider the first two digits together and the last digit separately in that case the string is going to be we and f or we are going to consider this two separately and 26 separately then it is going to be b z so these three ways are the possible solution to convert the number to 26 two strings so our output is going to be three so this can be one case there are other situation that occurs in this for example if our number is going to be 2 0 6 in this case you can consider this in one lead one way that is considering 20 together and six separately because you can't simply convert 0 to any alphabet which is invalid also you cannot combine 0 6 and convert it to a alphabet because 6 converts to f but 0 6 doesn't have any value so the only possible way is you should consider this 20 separately and 6 separately and there can be one more case if your example is 2 36 in this case you can consider 2 3 and 6 separately that will be one solution and you can consider 23 and six separately that will be your second solution but you can't consider 2 alone and 36 separately because 36 is a invalid alphabet the maximum value should be only 26 not 36 so final case is going to be 2 96 so in this case if you are going to consider change this to a string then you can consider two separately nine separately and six separately you can't combine any of this because if you combine 29 it is going to be invalid if you come by 96 it is going to be invalid so the only possible solution is considering it separately that is 2 9 and 6. so these are the few cases that comes in our case so how are we going to approach this we are going to solve each step one by one and finally arrive at the optimal solution for the bigger problem so obviously we are going to use dynamic programming so here i'm going to have an integer array dp which is going to hold the results of each sub problem and finally arrive at a solution at the last value so now we are going to have an array of size string plus 1 so the character is given as 4 the size of my radp is going to be 5 so now i am going to start with an empty string so how many cases we can decode this empty string can be decoded in only one way that is another empty string it can't be converted or something so there is only one way to represent an empty string is again going to be an empty string so i'm going to fill 1 here now i'm going to start with my character 2 so how many ways you can convert 2 to a character there is only one way that is 2 can be converted to b in this case since it is a one way i'm gonna fill one again here so now we got solution for our very simple sub problems we are going to use this solution or apply this technique for further problems and finally arrive at a problem solution for a bigger problem so how do we do it our next character is going to be at here that is 2 you can either consider converting this 2 to b or you can consider the whole 22 and convert it to another character so now how are we going to consider this so in this case i'm gonna consider only this two first how many possible ways to convert two to a character there is only one way that is you can convert it only to b in this case if you have already converted this 2 to b and you are appending this 2 to this 2 in this case this can also be converted to b that is it is going to be only one way converting this 2 to b and the other 2 to b is going to be one way so whatever is filled in the previous column i'm just going to retain the same in my next column as well so why am i doing it because already we have converted this 2 to b if we are appending this 2 to this 2 again it is going to included in that single way only it is not going to be a separate solution if you are not getting it just stay with me and decode it you're going to understand by the end so now we have updated 1 here considering we are converting this 2 directly to b if not we are going to consider complete 22 for our solution in that case this cell becomes invalid because if we are considering this two and this two together then the conversion of two at this position will not be considered right so what are we going to do we are going to consider this complete 22 so whatever before 22 that is this step from that step i'm gonna add one because till here i had made some steps and converted the string so from here i found one more way so i am going to add 1 to this from here so this is going to be updated to 2. so now we are done with the 2 we are moving to our 6 so in this case you can either consider converting the 6 directly to f or you can consider the 26 and convert it to z so if you are considering six alone in this case you can possibly change it to only one way if there is no other ways so we are going to just put the same value as that of previous case because till now we have made some changes and it just gonna append f to it in this case i'm gonna put 2 here first so now what if i'm considering the 26 in this case here our array represents 2 6 3 so we are going to consider the complete 26 here in that case whatever we made here at the position 2 is going to be invalid because we are going to have our 26 completely in this position so we are going to ignore this two's calculation and consider whatever here at the first position that is our first two and gonna add 1 with that and put here hope you're understanding that is if we are considering complete 26 then the conversion of 2 is going to be invalid so we instead of considering this 2's value before that whatever value we found whatever solution we found for this first two alone we are going to add one more and save it here then this cell becomes three so we are done with six we are now going to move to 3 so now we can consider only 3 by converting it to c or you can consider the whole 63 but if you observe 63 is not a valid number it is greater than 26 in that case we can simply ignore the second condition and just put a solution for first condition so what i have said if it is going to be a single solution we just gonna up append it with our previous solution now no changes are going to happen so i'm just going to put the same value as the top before so i'm going to put 3 here since the next condition 63 is invalid we are stopping our con till here and three is going to be our solution so simply if you observe a pattern what are we doing here we are just updating the previous value to that cell if there is only one way to change the character if it is a one digit or if the digit is valid if not we are considering previous step and adding one why previous step because so far we have done some results and to that results we found one more solution so we are adding one it is that simple so let's see how are we going to code it as i said i'm gonna have an integer array dp to hold all our values for our sub problems which is of size string dot length plus one so now i'm gonna i'll assign my first value that is dpf 0 is going to be 1 and my dpf 1 is going to be if my first character in yes is going to be 0 then converting 0 to a character is not possible there is 0 ways to decode it if not if it is not 0 then we can convert it and we can put one so i'm checking if here at my string at position zero is going to be zero then i am simply gonna put zero otherwise put one once this is done i'm gonna iterate my dp array from index two so here i'm gonna get my one digit and two digits my one digit is going to be so as substrings i took my one digit and two digits so i'm checking if my one digit is greater than 0 because if it is 0 we can't convert it will be an invalid case so if it is greater than 0 then my dp of i is going to be the previous value if not if two digits is greater than 10 and less than 27 then 3 to than 9 because if it is a 2 digit why we are checking greater than 9 because if there are numbers come 0 6 or 0 7 it is also 2 digits but it is invalid case we cannot convert them to characters so in this case it has to be greater than 9 and it should be less than 26 if that is the case then dp of i is going to be minus 2 so now once the loop is done our result will be saved from the last index of dp so we are going to return tp off this algorithm runs in a linear time there is big go of n where again is the lines of the string let's submit yes so thanks for watching if you like the video do me a favor just hit up like and subscribe thank you
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
509
hello everyone so today I will uh show you how to find the uh nth number of the given Fibonacci series so uh to start with what Fibonacci series is ah it is the sum of the N minus 1 and the N minus 2 number so the first number of the sequence will be zero the second number will be 1 and the third number will be zero plus one as one the fourth number will be 1 plus 1 as 2 and so on so the nth number will be the sum of N minus 1. from plus n minus two Trump so we need to write a function so as to calculate the given number like given n we have to calculate the F of n so let's start so since I already told you that the first number will be 0 and second number will be 1. so we will start a loop for I in range um n plus 1 so if I equal to 0 that means if is the first number then we will store the next number as 0 I equal to 1 next equal to 1 else what we have to do is we have to sum the first number and the second number because the next number will be the sum of the first and the second number first plus second and we have to replace the first number with the second number of the earliest run and the second number will be the next of the current run and we will return next so since uh the next term is always the sum of the first two terms so the next term is always the sum of the first number plus second number and the first number has to be replaced by the second number of the earliest run and the for the current run the first number will be the next number of the earlier run so in this way we have to find out let's see if the program is right or wrong so it has shown all the cases as right so since uh the first number if n equal to 2 the number is 1 that's right if n equal to 3 output is 2 4 3 so this is how we compute the uh nth number of the Fibonacci series so thank you so much and if you have any comment then please let me know in the comment section
Fibonacci Number
inorder-successor-in-bst-ii
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given `n`, calculate `F(n)`. **Example 1:** **Input:** n = 2 **Output:** 1 **Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1. **Example 2:** **Input:** n = 3 **Output:** 2 **Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2. **Example 3:** **Input:** n = 4 **Output:** 3 **Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3. **Constraints:** * `0 <= n <= 30`
null
Tree,Binary Search Tree,Binary Tree
Medium
285
472
hey everyone welcome back and let's write some more neat code today so today let's solve concatenated words while this is a hard problem I don't think it's crazy hard so maybe by the end of this video you will have boosted your confidence or maybe even shattered it who knows we're given an array of strings without duplicates we want to return all the concatenated words in the given list of words and a concatenated word is defined as being made up of two shorter words in the given array so basically we have a list of words like this how do we know if this particular word is a concatenated word well if there are two or more other words in the string that we can concatenate together to form this word so it's pretty simple and there are multiple ways to solve this problem thankfully even a Brute Force solution will actually work in this case but you do have to be slightly intelligent about it and I'll tell you what I mean suppose we're given n words we could create a decision tree that for every single word we choose to include it or not so we have the word cat we include it or we skip it and then the second word we have is cats so we include that word which would mean we concatenate it with cats so we'd end up with a word like this or if we skip it we would end up with something like this and then on this Branch we'd have just cats and then here we'd skip it and we'd basically continue this entire process for every single word in the string what this would give us is by the end of it we'd have every single possible concatenation with all of these words how many would we have well for each word we can include it or not include it and we have n words so we'd have 2 to the power of n possible words now among all of these words we would not want the ones that just include a single individual word so we could subtract n from this but that wouldn't change the overall magnitude but this is the number of possible concatenations and then for each of the those words we would check do these concatenations exist in the word set that we were given the ones that do we would add to the result set and the ones that don't we would not and then we would have a result set that probably looks like this and we could return it the problem here is that obviously this would be the time complexity the question is can we do better yes we can instead of generating all possible concatenations let's go through every single word in the input list and individually ask can this word be made up from other words in the input that's easy enough but there's actually two different ways we could do it one way we could do it suppose we want to know if this word is a concatenated word one thing we could do is go through every single word in the input list of words and check if it's a prefix of this string so we would check cat is that a prefix of this yes it is then we would want to know is this already in the word set if it is then that means yes this is a concatenated word if it's not then maybe recursively this word is also a concatenated word so we would have to check going through every word in here can we find a prefix for this word and then you know continue the process the problem is that for this word we would have to iterate through every word in the input and we're told that the max length of words is going to be less than or equal to four thousand that's not a super large value but there's another way we can solve this problem and that is by instead of going through every word in the input we can instead just check every possible prefix of this word so we could check is C is this in the word set is c a in the word set is c-a-t word set is c a in the word set is c-a-t word set is c a in the word set is c-a-t in the word set and keep going like that now how many possible prefixes of an individual word can there be well we're also told that the max length of an individual word is going to be less than 30. so the length of an individual word is going to be less than or equal to 30 and it's easier to iterate 30 times than to iterate 4 000 times so doing it this way by individually checking every prefix is going to be more efficient that's why we're going to do it this way so at a high level that's basically the problem we're going to go through every word in the input then for that word we're going to check every prefix is that prefix a part of the word set and the way we're going to check that is by converting the list of words into a hash set so that we can look it up in of one time instead of having to linearly scan through every word in the list but otherwise that's it when we do find a word such as cat then we want to know is this a prefix then we want to know is this already in there because if it is then we know that it can be broken up into these two words therefore this is a concatenated word and then we can stop immediately in this case this is not I don't believe but then we check the word cats that is here then we check dog cats is that in here I don't believe it is so then we would have to recursively run the same algorithm on this portion of the word so we would check every prefix d nope d o g that is here dog and then we check is the remainder of this which is cats is that in here yes it is so therefore this is a concatenated word and we would add it to the output as you can see over here now analyzing the time complexity of this problem is definitely not straightforward I will save that for the coding portion which we're going to go ahead and do right now so remember what we want to do is convert the list of words into a hash set that's easy enough so we'll just do it just like that we're going to recursively Define that depth first search that I was talking about that's what I'm going to call it and we're going to run it on every individual word so that's the only parameter that we're going to pass in we could also pass in a word and the index but instead of doing that I'm just going to create substrings for the word as we like break it up but you could do it the other way passing in I would probably be a bit more efficient because you don't have to create copies of this word but I don't think that's like a major deal breaker I prefer the code to be clean uh instead of filling out this DFS what I'm going to do is show you how we're actually going to use it because that's pretty easy we're going to have a result which is going to be the list of concatenated words that we're going to return and the way we're going to populate them is just by going through every word in the input list of words we're going to check if it is a concatenated word by running DFS on it if it is then we can just go ahead and append this word to the result now for the DFS what we're going to do is go through every prefix for the word just like I showed so for I in range length of the word but we don't want an empty prefix so we're actually going to start at one because if we did have an MP prefix we would end up seeing that the word itself is in the word set but that's not what we want to break it up into at least two or more words so that's why we're going to do it this way now the prefix itself is just a substring which is going from the beginning of the word all the way up until the index I but not including the index I and then we want to know if the prefix is in the word set we have access to the word set because it's defined outside of the scope of this function if the prefix is in the word set then we want to know is the rest of the word also in the word set which we call the suffix so we'll also Define the suffix here so word starting at index I and going to the end of the word that's the remainder of the word so if the prefix is in the word set and the suffix is in the word set then we can return true but there's another case where we might end up returning true I could add a second if statement here or I could just include it in the if statement up above which is what I'm going to do so this is one possibility and the other possibility or here is that prefix is in the word set and we run DFS on the remainder of the word because we know that the remainder of the word is not in the word set but maybe the remainder of the word can be broken up into two or more words so we're going to pass the suffix in here can the suffix be broken up and these two possibilities we would end up returning true now you can notice that we don't actually have a base case here because normally the base case would be if the word is an empty string then we would return true but here we're handling that over here if the prefix is in the word set and the suffix is in the word set then essentially we don't even need to run DFS anymore so that is sort of our base case I want to quickly mention that this solution itself actually will work as you can see here we can make it slightly more efficient using a dynamic programming caching technique though I don't think it's really necessary it doesn't change the overall time complexity too much so if all you wanted to do was solve the problem there you go now if you really want to lose your mind let's try to analyze the time complexity of this and then compare it with the memoization time complexity now very quickly I'm going to add caching to this so I'm going to create a DP hash map which we're going to use just like this so if a word has already been passed into DFS so if word in DP then we're going to return whatever the value that we stored for that is otherwise we're going to instead of returning true here we're going to end up caching that value in our DP before we end up returning it and then also here where we actually didn't end up returning false that works in Python because I guess it just returns undefined or something like that but otherwise we can hear say DP of the word is going to be set to false and then return that so it's pretty straightforward to add caching here oh and don't forget here to return DP of the word but now let's run it and you'll see that it is slightly faster than the original solution in terms of run time it's almost exactly the same I would hope that in a real interview you wouldn't have to analyze the time complexity of something like this super in depth because it's really not easy at a high level we know we're calling this DFS n times let's say n is the number of words that we're given and we know that every time this runs on an individual word we'll have to iterate for every character in a word let's say the max length of a word is l but then also creating a prefix for that word also takes time and then checking if that word is in a hash set so it takes time for the length of the prefix which we can also say is roughly l so at this point we're at L times L but it gets complicated because we have a possible recursive call maybe that recursive call Will execute for every iteration of the loop and then each of those recursive calls will also have a loop and those will also be made making recursive calls so I think that will alter the time Galaxy as if this were wrapped in a another like nested Loop so I think that basically changes the time Galaxy of this to squaring this so this is like L times l so L to the power of four that's before we add caching to it after we add caching we know that for an individual word the number of times this DFS could run the number of possible inputs it could have is every possible suffix for that individual word so if this runs and we've already called it with that suffix before it will immediately return so that will change this to being L to the power of three I know that's very much not easy this is what took me the longest just to analyze the time complexity of this solution it's easy to go wrong but if this was helpful please like And subscribe check out neatco.io if you're preparing for out neatco.io if you're preparing for out neatco.io if you're preparing for coding interviews it has a ton of free resources thanks for watching and hopefully I'll see you pretty soon
Concatenated Words
concatenated-words
Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`. A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array. **Example 1:** **Input:** words = \[ "cat ", "cats ", "catsdogcats ", "dog ", "dogcatsdog ", "hippopotamuses ", "rat ", "ratcatdogcat "\] **Output:** \[ "catsdogcats ", "dogcatsdog ", "ratcatdogcat "\] **Explanation:** "catsdogcats " can be concatenated by "cats ", "dog " and "cats "; "dogcatsdog " can be concatenated by "dog ", "cats " and "dog "; "ratcatdogcat " can be concatenated by "rat ", "cat ", "dog " and "cat ". **Example 2:** **Input:** words = \[ "cat ", "dog ", "catdog "\] **Output:** \[ "catdog "\] **Constraints:** * `1 <= words.length <= 104` * `1 <= words[i].length <= 30` * `words[i]` consists of only lowercase English letters. * All the strings of `words` are **unique**. * `1 <= sum(words[i].length) <= 105`
null
Array,String,Dynamic Programming,Depth-First Search,Trie
Hard
140
70
hi all welcome back to tracking the fang interviews today i'm going to be talking about lead code number 17 which is climbing stairs and this question is very popular at facebook salesforce amazon and also microsoft i have seen this getting asked for regular software engineering and also data science slash aiml interviews and let's start looking at the problem i also have a link to the lead code problem in the description below so the problem is asking us is giving us a scenario where you are climbing a staircase and it takes n steps to reach the top so you've been given n steps and each time you climb one or two steps that's the concern you can either take one step or you can take two steps and reach the top step um so the question is asking us how many distinct ways can we climb the top so something i want to emphasize here would be the pattern that you observe whenever the question asks you to find how many distinct ways you climb to the top uh or how many ways um this is a type of problem we typically solve with something like recursion and of course as we spoke in the previous video the fibonacci sequence video you can always optimize a recursive program further using dynamic programming all right so let's look at an example of the problem first establish it so we have been given n equal to 2 the way you can climb two steps let's just solve it uh by hand first uh you can take one step and one step so you'd have one way then you can take two steps uh at once and still reach the top step so there are two ways of solving this problem um now i'm gonna try with the other example i have here which is n equal to three so you have a staircase with three steps uh you take one step that's one way then you take two steps and one step or you take one step and two step um so this is the second way this is the third way so there are three ways of solving the problem now the reason i mentioned recursion whenever you're asked something which has to do with sub problems for example the number of way in this case the number of ways in which i can climb two steps clearly depends on the can be broken down into the number of ways i can solve for one step and the number of ways in which i can stop solve for one step because n equals one plus one equal to two so in this case for one step i can solve it in one way uh for one step i can solve it in one way so in all my answer would be 2. so this is clearly a recursion problem you can break it down into individual sub problems same for 3 the way you break 3 is 2 and 1 or 1 and 2 and so on and you'd still get be able to solve for the entire problem so as established we'll be going with the recursion approach the way we can break down this recursion problem is uh if you're given n equals three meaning three stair uh three steps and we're gonna solve for that uh what we could do here is further break down the problem by taking either one step or two step so if we take one step we make it n equals two and if we take two steps we make the problem n equals one the way we could represent this in recursion is we could say again i'm going to call this recursive step for a given n equals 3 you can break it down into recursive step n minus 1 and recursive step n minus 2 and use this expression solve each of these sub problems as finding number of ways add them and further break it down and so on this is how the recursion tree will look like and this is the most basic approach to solve the problem and again as if you haven't seen already uh watch the previous video which is the fibonacci number video it would give you the fundamental of calculating the time complexity of this approach but in general uh just to break it down the generic way in which you can calculate the time complexity of a recursive algorithm is o of branches our depth so in this case the depth is the height maximum height of the recursion which is going to be you will start with 3 you'll go to 2 1 and 0 all the way where 0 is going to be your base case and 1 is also going to be your base case and the number of branches you're taking is 1 and 2. so this is again an exponential time algorithm we can further optimize this using dynamic programming um so if you were to quickly write code for the recursive approach i'm gonna say def uh recursion underscore climbing stairs and send in the parameter n as i said the base case is going to be if n is less than equal to 0 equal to 1 you return n because if you have zero stairs um the only way you can do it the there's one way to solve for this which is zero you can't climb it given you the options you have is one or two jumps at once and if you have one stair uh n equals one uh the only way you can do that is uh essentially uh climb uh climate one way so the answer is one so we return one and the other this is the base case i'm again i'm writing pseudocode in python but the concept is pretty generic and you can apply it across any programming language and else you'd return recursion climb stairs n minus one plus recursion climb stairs and minus two and as discussed uh in the previous slide this is how the recursion tree would look like and the time complexity will be 2 power n the space complexity time complexity will be to power n space complexity will be of n the reason for this is uh we'll we will have uh n number of call stacks that line up as we solve the problem which is the also the depth uh of the recursion that makes the space complexity of n because every time you call you are essentially making a new call stack before you get rid of this so you are adding to the auxiliary space which will be often if i give you 5 you're going to call 4 3 2 1 and so on now the question is can we do better than exponential time and as discussed in the previous fibonacci number video yes we can do better using dynamic programming and again it's the same concept this is the generic way in which you convert a recursive algorithm into a dynamic programming approach this allows you to go from exponential runtime to polynomial runtime and i'm going to quickly walk through the code this is the code i've written on lead code for base cases uh for n equals zero and one you have one way to solve it as we discussed earlier uh this is the regular program and ah for the recursive steps uh you can break it down in for solving for n you can you break it down for n minus 1 and n minus 2 and once you write the dynamic programming code it's also called a memoized code the word memoized comes from us using memory to store answers to some problems and again what you essentially do is first store your base cases and then you loop through the other cases and you look at the previous two steps the solutions the way i come up with this expression is exactly the recursive expression and once you're done looping you'll be able to find the answer for e of n and the reason we have n plus 1 here is in python for a for loop it goes from the limit starts from 0 if you have 0 there and goes till n minus 1 so it's up to but not including so when we say n plus 1 it's gonna go to n that's why we have n plus 1 here and now this way we can we convert something that is o of 2 power n exponential to o of n which is polynomial i hope this was helpful um thank you for watching cracking the fang interviews again please like share and subscribe to the channel for more
Climbing Stairs
climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps **Example 2:** **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **Constraints:** * `1 <= n <= 45`
To reach nth step, what could have been your previous steps? (Think about the step sizes)
Math,Dynamic Programming,Memoization
Easy
747,1013,1236
1,992
1992 find all groups of farmland so the problem statement is uh you are given a zero index m by n binary matrix land where a zero represents the forest and let and one represents the hector farmland to keep the land organized there are designated rectangular areas of hectares that consist entirely of farmland so there are certain rectangular areas where it is consisting of only form lines these rectangular areas are called groups so groups means it's a group of farmland no two groups are adjacent meaning farmland in one group is not four directionally adjacent to another farmland in a different group a land can be represented by a coordinate system where the top left corner of the land is 0 and the bottom right corner of lan is m minus 1 n minus 1 we need to find the coordinate of the uh we need to find the coordinate of the top left and bottom right corner of each group of farmland so there will be certain groups of farmland and we need to find the coordinate of all those farmlands and our land is starting from the coordinates 0 to the top right corner m minus 1 n minus 1 where m and n are the rows and columns so uh a group of farmland with a top left corner at r1 c1 and bottom right corner at r2 c2 is represented by the 4 length ra r1 c1 r2 c2 so we need to return a 2d array of this four length arrays so let's consider an example so this is a land where a land will be having both forested land and farmland so one will be uh the farmland and zero will be the forester land we are only uh considering about the farmland and a group means uh the a collection of farmlands is known as this group and this will be having a top left corner and this is having a bottom right corner so here the top left corner is 1 here the bottom right corner is 2 so 1 2 will be one of the coordinate and here uh and it's uh it is not sharing any of the other form line groups in the four direction if we consider here also this is a single cell group and here also for a direction here we are not having any other form line so here uh the top left corner is 0 and top right corner is also 0 so let's check this example again so we are having 1 0. and 0 1 so this is a group and this is another group sorry and this is another group this whole one and coordinate of the first group is coordinator of the first group is 0 which is the top left corner and bottom right corner is also 0 since this is a single celled one and while considering about the nest case uh the top left corner is 1 comma 1 and the bottom right corner is 2 comma 2 so the thing what we need to return at the end is a collection of this items that is 0 and ah 1 2 comma 2. so we don't know how many number of groups will be there so we need to find how many number of groups are there and uh we need to output them so how we can do so in uh general case of this uh matrix problems where we are having one zero like that uh we can use either bfs or dfs search we can search inside this and find which are all the farmland uh and which are all the groups and we can uh track the coordinates so one of the observations that we need to make sure is the top left corner coordinate will be the minimum values so consider here also one here one the coordinates of the four ones are one then the other one is one comma two other one is 2 comma 1 and the other one is 2 comma 2 so of all this we are having this 1 the minimum so 1 will be at the top left corner and top and the bottom right corner coordinate will be the maximum values so this must be considered so uh here i'm discussing about the bfs approach so for bfs we needed a queue so let's say this is our queue and in this queue we are storing uh when we encountered a one uh we will start bf as such so uh we will be traversing through this matrix and whenever we encounter a one uh we check whether it is listed or not so for that we can make use of a 2d boolean array to mark it as vista or notification and after that this ij uh will be passed on to the string uh sorry uh ij will be a puzzle here 0 comma 0 will be passed on to our q and this 0 comma 0 will be our top left corner so uh we can make sure that we can take off an array of length 4 and this 0 can be stored at first itself so 0 comma 0 this is the first coordinate and we mark this as visited now we check the 4 directions uh the right directions the bottom directions the left direction the top direction so whenever we see a value other than zero or whenever it is out of bounds then we have nothing to do our q will become empty and the rest of the value can be 0 comma 0 itself it will be as i told it will be maximum of current of zero it will be a maximum of current of zero comma uh this array let's call this array some value array here some array so it will be a array of two because these two and third index are the remaining values that we need to fill so array of two and same way it will be the max of current of one comma array of three so this is what now uh same way we uh go to uh this zero traverse this while traversing this array this is no we only consider about this one so this zero will not be considered the zero will not be considered now we reaches this one and when we reaches this one we also check whether it is switched or not since it is not visited this is a possibility for our top left corner so uh now we are dealing with this one 0 1 0 this is already processed this is visited okay now this one now we are at this one so uh this value is pushed on to the queue one comma one is pushed on to the queue and we also we make use of this array and that ri will be 1 comma 1 which is the possible value for the top left corner and the rest two values need to be found out so let it be zero so one comma one so we take one comma one we make this as visited now we check the four directions we check the left we check the bottom we check the right we check the uh top so these are this is 0 we didn't care about those 0's we care about this one so this is a 1 so we pop this out and this is 1 comma 2 so 1 comma 2 will be added same way 1 comma 3 will also be added and we will just i use this max of current of zero array of two so current of zero is so our other equation is max is equal to uh sorry uh raf 2 is equal to max of current of 0 comma array of 2 and array of 3 equal to max of current of 1 comma array of 3 so initially our array of 3 is array of 2 is 0 and our current of 0 is this 1 so the value will be updated with initially with 1 this will be replaced with one comma one okay so we process this one comma one this is listed now we take this one comma two of as our current now from this one comma two we again visit we again look for do the breadth first search to the top to the right to the left and to the bottom since this is already visited we didn't care about this one this is 0 we didn't care about that one okay then this is out of bound we have nothing to do with out of bounds and this is uh another one and it is not also not visited so this value will be added and it is 2 comma 2 one mistake this value is 2 comma 1 sorry about the mistake this is two comma one okay so uh so now the current value will be updated what is the uh max of current of zero one this will be one itself and this value will be updated with two because array of three current of one is two and it is greater than this one so we process this one now this two comma one uh we will mark this as we start and we will check the left we check the top which are the right and we check the bottom so this is 0 this is 1 and it is already listed this is bottom that is out of bound we don't want to care about and this is 1 and this one is already added here uh it is uh 2 comma 2 here other will be 2 comma 2 so the answer now will be maximum of 2 comma this one so the answer here becomes 2 and this is also 2. now we have this 2 comma 2 and this is 2 comma 2 we check for the left for the top we check for the right and we check for the bottom this is all are uh having no values are either processed this is process this is out of bound so uh the array of 2 will be maximum of 2 comma 2 which is 2 itself and 1 comma 1 itself so we get the answer 1 comma 2 if we also process this one it is s same as that one so it's that value itself so 1 comma 1 2 comma 2 is the answer here and 0 comma 0 is the answer so how can we do this so since we are doing a bfs we need the directions to be taken so let's have a private final in uh directions which is equal to new end off we need the four direction zero comma one comma 0 minus 1 comma 0 and 0 comma minus 1 so ah now let's store rho is equal to land dot length and core is equal to land of zero dot length uh now um now uh let us have list of int arrays this is these are the possible result and this possible result why we use list of in because we don't know how many uh groups of farmland will be there so we cannot uh just uh simply assign some uh a 2d array with some definite size so uh we create this list of indirect which is a new array list now we also make use of a boolean vista array which is of size raw call so now we start traversing the 2d land array and check for one and not listed so that what we are going to do so for int i is equal to 0 i less than rho i plus so for into j equal to zero j less than called j plus so if we encounter a one if not visited of ij and if the land of i j is equal to one this is the time where we do the dfs so we are having the coordinate which is equal to a new end of i comma j which will be our top left corner and 0 comma 0 because we don't know what are the remaining two values that will be filled from the bfs so we then do a bfs off um we will pass land we will pass uh this coordinate we will pass a western now uh after doing this bfs this coordinate will be fully filled and we can add it into the possible result dot add of coordinate finally this has to be returned as a this possible result is now a array list or a list and it has to be converted to a array so it can be done in many ways we can just do it in a single line like possible result dot 2 array of new end of possible result dot size that many number of rows and the column will be four just four elements so now we have to do this bfs function so public void bfs and we passes our land we passes the uh coordinate and we passes the boolean array which is mr which is uh we start so ah also i missed us one thing that we also need to pass the coordinator comma j so into i comma into j so this is the coordinate i j where we find a one which is not already mister so we will make it as visited instead of ij will be made as true and we will be using make use of a queue which is a new linked list okay because a queue is uh required for uh broadfirst search generally and we add q dot add off new end of i comma j okay so now our q dot in this example 0 comma 0 will be added into this queue first so while not q dot is empty we will pull out the current top element or the front element and explore the four directions so that we will be doing so this is our current this is equal to current which is equal to q dot port so this current is same as ah as i explained here array of two is equal to max of current of zero comma r i of two this r i of two is uh this coordinate so current is equal to q dot port now we just explore through the direction four direction so already we define the directions so for int there from uh directions uh we can have the in the interview x is equal to current of 0 plus direction of 0 and in new y is equal to current of 1 plus direction of 1 now we need to uh check for the boundary condition then we need to check whether it is already listed or we need to check whether the value is zero so this has to be maintained because if i is if new x is less than 0 which is uh to the left here out of bound to the left or nu x is greater than or equal to land dot length or nu y is less than 0 or nu y is greater than or equal to land of dot length or whether it is visited instead of i j or whether the value is zero so land of mu x here i made a mistake this is instead of nu x new y so if any of these conditions occurs it means that those are the conditions that we don't want to consider what we need to consider we only care about where is this one whether it is visited or not so if it goes out of bounds which will be deal dealt with these four conditions or whether it is already finished or already visited or whether the land is already a zero so all these conditions will be made here if any of this is made true we will just continue we will just skip it otherwise we will just make it true we will mark it as visitor and we will add it into the queue q dot add off or offer off add off new end off new x comma new one so uh all the uh possible uh other uh farmlands will be added on to the queue now uh we will update our coordinate so coordinate of uh 2 will be mat dot max of coordinate of 2 comma current of 0 and coordinate of 3 will be mad dot max of coordinate of 3 comma current of 1 so this is what i explain here ri of 2 is equal to maximum of the current top element that we pulled out from the queue uh it's zeroth index value and the array of two and uh the same way the next element here from the pop dot problem so uh this is our bs first function so let's run it here i'm getting the correct uh example is uh correct result as expected so now let's check with uh all other example test cases the other example test cases here one here it is a single group and the top left corner is zero and uh bottom right corner is one comma one so we need we must get zero one and this is a single element here uh we only have a zero so uh it must be an empty list so the sample test cases are passed yes it's accepted so uh this uh problem can also be done using the dfs but uh here uh i uh go straight away with the bfs and the time complexity here we are going through each and every row and each and every column that is h and every element so the time complexity will be big of m by n and the space will is also big of m by n here uh we can uh get rid of this uh listed array if we just change the values to some other negative values other than zero or one so thus we can also get rid of this mister values but this is the most general approach that we approach so that's it
Find All Groups of Farmland
sort-linked-list-already-sorted-using-absolute-values
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group. `land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].` Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_. **Example 1:** **Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\] **Output:** \[\[0,0,0,0\],\[1,1,2,2\]\] **Explanation:** The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\]. The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\]. **Example 2:** **Input:** land = \[\[1,1\],\[1,1\]\] **Output:** \[\[0,0,1,1\]\] **Explanation:** The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\]. **Example 3:** **Input:** land = \[\[0\]\] **Output:** \[\] **Explanation:** There are no groups of farmland. **Constraints:** * `m == land.length` * `n == land[i].length` * `1 <= m, n <= 300` * `land` consists of only `0`'s and `1`'s. * Groups of farmland are **rectangular** in shape.
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
Linked List,Two Pointers,Sorting
Medium
148
1,652
Hello friends welcome to my channel let's have a look at problem 1552 they viewed the bomb in this video we are going to share Solutions based on sliding window and we are going to share two formats of solutions first I will read through the problem statement to digest the requirements then we do the analysis and share the codes first let's look at the problem statement we have a bomb to diffuse and our time is running out our Informer will provide us with a circular array code of length n and a key to decrypt the code we must replace every number all the numbers are replaced simultaneously so first if K is greater than 0 so replace the ice number with the sum of the next key numbers and if K is less than 0 replace the ice number with the sum of the previous key numbers and FK equals 0 replace the ice number with zero so as code is circular the next element of code n minus 1 is equal to zero and the previous element of code 0 is code M minus one so given the circular array code and an integer key Returns the decrypted code to diffuse the bomb so here are three examples so example two is the easy case because k equals zero we just need to return these results of list four with all elements being zero so let's look at example one so for example for at index 0 so we're going to return the sum of 714 already so at index 1 so we're going to return the sum of 1 4 5 right that is uh 10. so similarly you can interpret 16 13. so this is example one for example three so the K is negative so for index 0 so we return the sum of none and three that is um 12 and for index 1 we're going to return 2 and 3. so their sum is 5 and you can interpret 6 and 13 simultaneous similarly so before we do the analysis let's look at the constraints so first the length of this list is less than or equal to 100 so this is not very large so we have a lot of freedom to do whatever we feel natural so next we are ready to do the analysis so as we mentioned we are going to use sliding window so here is a remark so this problem is very straightforward however it's important to pay attention to the indexing for this problem so first I'm going to pick up this case k equals zero so this is easy so we just ignore that so for click is greater than zero as in example one for example the code is here and k equals three so we are going to append the code with this key elements so for example this is the original code and then attend append these three elements and then we do sliding window backwards right so for let's say 4K experience then so this is the uh this is the um like this so uh for example we initialize a result and then so results three so we're going to have um the corresponding number is 5 plus 7 plus 1 that is thirteen and then for index uh two so we are going to Sum 4 5 and 7 right so this number is nothing but the previous sum so we ignore the one and at the four that is 16. then for index 1 so what we are going to do is that we use this 16 then include this one and minus the seven right the priest one that is 10 then at index 0 so we're going to um include this 7 but ignore the five so we get 12. so this is the case when K is greater than zero so when K is less than zero so as in example three so the code is here and K is negative two so we are going to append the following two elements uh of uh in the front so this is Nan three right this is the original code and then we do sliding window forwards right so for example result zero will be the sum of these two numbers and result one will be the sum of this three and two right and result 2 will be the sum of these two numbers and the results three will be the sum of these two numbers that's it so with that said so we are ready to present the code so in the first version I'm going to follow through this one so we are going to use this sliding window and to save some computations so basically we do not want to do slicing using a segments of lens K so first let me get the lens information of the codes so this is the original lens right so first I'm going to treat the case when k equals zero so when the k equals zero we just need to return it array or a list of links in with all elements being 0. so this is the van special case next we are going to treat the generic case so first I'm going to initialize a result to hold the elements then we just need to set the corresponding values for the result variable so first I'm going to consider the case when K is greater than 0 right so for this we're going to append this code with code first key elements right and then we are going to do a sliding window in a backwards fashion so for I in range n minus 1 negative 1 right so first I'm going to trace the case when I equals n minus 1 that is adjectives right so we are going to do this result I will be the sum code um I plus 1 to the end right and then in the other case so we just need to do this right so we are going to start from this a window and then we include the code at index I plus 1 and then manage the code at I plus 1 plus key so this is a set for this zero case so we just need to return this result so you can write here or you can write a full return result for the case k greater than zero add key less than zero but no that's first to do this return and then what we are going to do is that we consider the case when K is less than zero right so in this case so we're going to append the K element so in front so here I'm going to use the last key elements so notice that K is less than 0 right so plus the code and then we are going to do study window in a forward fashion so for I in range again so for this case so we're going to set this results to be the sum of code the first key element so that is up to negative key because K is negative right otherwise so here this is for if I equals zero right otherwise what we're going to do is to do this in a forward fashion because results I minus 1 is already set and then we are going to include this number we want to exclude this number and include this one and because K is less than zero so this include this one and minus code I minus 1 right so let me see so this is the result right so this is the um elements in the corresponding position in the appended code and minus I minus one that is that's right so with that said we can do the return right so notice that we write two returns one is here where it's here so we can if we can write here so we just need to write one return so it does that we are finishing a solution format so now let's look at the test yeah it passes a an example now let's look at the general case yeah it passes all the generic cases um uh in the first fashion so this is the van solution format which basically we optimized the length of the code we are working on like here and here however notice that in this problem the length is bounded above by 100 so actually just need to double the code and then do the coding so let me copy this function signature and then put it here read another solution format so I'll call this one V1 so solution V1 will be actually more efficient in substance than solution V2 so we're going to use this one so for this I'm going to initialize a so let me first get in and is a length of code list and then what we are going to do is that we'll make a list this double the code this way we can take the circular structure right and then we just need to set for the course position in the result that is for I in range m so what we are going to do let's see uh first if k equals zero so it just results high equals set to be zero otherwise if K is greater than zero so we just do something in the Brute Force fashion right we just need to sum so list so from I plus 1 and then we use K elements so that's the one otherwise the K is less than zero so we are going to set this next sum so not a list so here is LST so we're going to do this I Plus n plus K right so up to let's see I plus length um code let's move this n right I plus n and so notice that this num this from here to here the difference is uh is K as is negative okay right negative K is positive so there are K elements so then we are going to return the result so notice that in this version we didn't use we are using flooding window but it just computed the sum in a very Brute Force fashion compared with version web so with that said we are ready to do a test it passes a special case now let's look at the generic case yeah it passes all the generic cases so with that done I guess that's about it for solutions to this specific problem so here we emphasize solution event because here we just need to uh do the sliding window in a more delicate way but here the important thing is that we need to pay attention to the indexing right besides this the problem logic is rather straightforward with that said I guess that's about it for this video thank you
Defuse the Bomb
minimum-suffix-flips
You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`. To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**. * If `k > 0`, replace the `ith` number with the sum of the **next** `k` numbers. * If `k < 0`, replace the `ith` number with the sum of the **previous** `k` numbers. * If `k == 0`, replace the `ith` number with `0`. As `code` is circular, the next element of `code[n-1]` is `code[0]`, and the previous element of `code[0]` is `code[n-1]`. Given the **circular** array `code` and an integer key `k`, return _the decrypted code to defuse the bomb_! **Example 1:** **Input:** code = \[5,7,1,4\], k = 3 **Output:** \[12,10,16,13\] **Explanation:** Each number is replaced by the sum of the next 3 numbers. The decrypted code is \[7+1+4, 1+4+5, 4+5+7, 5+7+1\]. Notice that the numbers wrap around. **Example 2:** **Input:** code = \[1,2,3,4\], k = 0 **Output:** \[0,0,0,0\] **Explanation:** When k is zero, the numbers are replaced by 0. **Example 3:** **Input:** code = \[2,4,9,3\], k = -2 **Output:** \[12,5,6,13\] **Explanation:** The decrypted code is \[3+9, 2+3, 4+2, 9+4\]. Notice that the numbers wrap around again. If k is negative, the sum is of the **previous** numbers. **Constraints:** * `n == code.length` * `1 <= n <= 100` * `1 <= code[i] <= 100` * `-(n - 1) <= k <= n - 1`
Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left.
String,Greedy
Medium
null
328
hello everyone welcome back so today we are going to continue with the problems related to linked list so the problem name is uh or even linked list so given the head of the sinclair linked list group all the nodes with odd indices together followed by nodes with even indices and return the reordered list the first node is considered powered and the second one is even and so on note that the relative order inside both the even and odd groups should remain as it is as it was in the input you must solve the problem in overtime complex space and complexity and o in time complexity all right so this is the list one two three four five we need to club all the elements which are presented or indices together and club the elements which are in the even indices together and kind of merge those this example is a bit of confusing so let's take this example 2 1 3 5 6 4 7 right so first index first element is first one index right so it is not similar to those of arrays in which the first element is present at zeroth index so here the first element is present at first index which means it is odd so 2 and 3 2 3 6 and 7 these are present at odd indices similarly 1 5 and four are present at even indices so we have uh clubbed the elements present at odd indices followed by the elements present at even indices right so the problem looks simple like we just have to make some reordering of the node next pointers that said but in the cases of in the questions of linked list right we have to take extra care how do we handle those next pointers and we somehow don't miss any edge cases so i will try to explain like how we can solve this problem and how we take care of the edge cases in this problem so we need to solve it in one extra space and oven time complexity so one extra space they are trying to convey that we don't need to create an extra linked list right so we only need to change the ordering of the elements and one time complexity yeah that we can take care of so let's so i will create one linked list um let me draw five six eight any random list i'm thinking of six again two right let me create one more one right so this element is presented present at first index so this is called this is odd this one is on this is also we need to club five eight six and one similarly six seven and two these two elements have to be clubbed finally what linked list i have to return five eight six one this is one linked list the other linked list is 6 7 and 2 and we need to club these two together such that one next pointer would be pointing to six it's a very easy problem we just have to take care of the ordering of the elements that's it so if we uh see carefully that we need to break down this problem like we need to break this linked list actually into two parts odd and even right so for this we have to maintain some variables so two linked lists would be odd and even so the first linked list which is odd which is present at the odd indices so to keep a track of those elements we need some variables right so keep for keeping the track of the head of the odd linked list we need to maintain one variable called odd head similarly to keep a track of this linked list 6 7 and 2 you need to have one variable which is always pointing to 6 so for this i am creating one variable called even head similarly i also need to i trade over this odd linked list so for that i will create one variable called chord similarly i need to iterate over this even linked list as well for that i will create one variable called even right so let's see how the algorithm would work now so what we can do over here is we would initialize these four variables such that odd head would be pointing here similarly would also be pointing here and even head would be pointing here and even would be pointing to the same location initially right so how are we going to move ahead in the linked list let's see so we need to change the ordering of the elements right so five next node shouldn't point to six it should point to eight so we need to break this link and we need to reorder this element so that it with 0.28 0.28 0.28 so what we need to do over here is odd next has to point to even next right even next is 8. similarly we need to break this link so that six next pointer has to point to seven how are we going to do that even next we need to change this right even next pointer would be pointing to or first we need to reach this right then only we will be able to reach the seven and how we can reach this eight it would be it is nothing but or next that we had just changed in this step right so it would be odd next because if we wouldn't have changed from 5 to 8 then we would not be able to reach this 7 right we can only reach this 7 from 8 so this is also established this link is also established now this step is done now we need to update the odd and even variables so that we can also cover the rest of the linked list so odd would be updated as like we need to move odd from 5 to 8 and what is 8 is nothing but odds next so it is nothing but next pointer of in itself so odd would be updated as here now we need to update even as well even is nothing but uh it should be updated from 6 to the 7 so even comes here how can it come here it will be even equal to even next right so we just have to write this piece of code to make this algorithm work right but there are some cases that we need to handle right so first of the case is like till what point do we need to run this iteration wow yeah one more thing so um we need to we can observe that always the even pointer is ahead of order pointer right so when we are writing this uh algorithm like to mark the break condition we can check whether the even is even pointer is null or not if the even pointer is null we can break that loop right break this load and when this basically this l part of algorithm of a finishes we need to make this connection as well right so this algorithm basically takes care of creating these two linked lists right so let me try run this code and things would be much clearer so when the this code runs for the first step so this link is established after that it runs for the second time so this link is established all would be updated here and this link would also be established even would be updated here now comes third step or next has to be events next this link would be established to here so when i have to cancel these things this step is executed now i need to execute this step even next is equal to or next which is nothing but null so this is established what would be updated as or next what is here even is nothing but even comes here even is none now right so let's make it bit uh clearer so what is the linked list till this point of time 5 8 it is pointing to six is pointing to one similarly this six is pointing to seven is pointing to 2 is pointing to null right so at this point we have created two separate linked lists but somehow we were able to get a hold of their head values because that's where this odd handed board head and even head comes into the picture because they are always pointing to the head of the odd and even linked list so what i just need to do now is we need to update this link like i need to point this one next pointer to this six and at this particular one what i have this odd variable as i can see like odd value has been updated from here to here odd is here right so after everything has been done to join these two linked lists i have to just need to do this condition or next has to be point to uh even head that's it so that in that way we will be able to join these two link list and we can finally return this pointer 5 and we will have our desired link list so let's quickly uh run this code this first and we will run it later let's create uh first let's check if the head itself is none right if the size of the linked list is zero in that case we will directly return then what i'm going to do here is yeah i'm going to create four variables is it is pointing to head only please not start chord is pointing to head only similarly let's not start even head is pointing to head next right that's what we did here like even node has to start from the second node similarly even would be starting from uh hit next that's it right so this is where we have initialized all the four variables now we need to write that while loop in which i am making a check that while even is not equal to null also even next also doesn't need to be null so till this condition is valid i need to make these four operations so what i will do is first i will add next would be updated as even next and uh i need to update the next pointer of the even as well and even next would be updated as or next now i need to update the odd and even variable so that other part of the linked list can also get covered so what would be updated as or next and even as even next right in this way we are able to completely iterate over the linked list and we have bifurcated the linked list into two parts odd and even now we need to club these two together how are we going to do that's what i showed like we need to update this odds next pointer to even head that was the sole purpose of maintaining this even head pointer so that at a later point of time we can club these two linked lists together would be equal to even head all right i have clubbed these two together i can just return head from here that's it let's see if there are compilation issues yeah list node okay or next is equal to even undeclared even head okay got it should be capital yeah compilation is fine and the basic test gets passed let me submit it yeah solution looks fine runtime and memory usage are also fine so like this was a very easy problem of linked list like we just had to bifurcate the link list into two parts and we need to club those right so only issue was like we need to handle some of the edge cases like it might be the case like some of the people might break into two parts but in the end we need to clap the order and even english together right so this was the single line of code that did that purpose so as you can see the code length is also very small this is usually the case for the linked list questions like the code is not very large but how you handle the edge cases it matters right so these things will come while practicing only so like keep on practicing these problems and if you have any queries or improvements are needed in this solution you can definitely comment and also if you haven't subscribed to the channel please do and i will see you next time with another problem of lead call thank you everyone
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
120
some problems can really help you understand how dynamic programming actually works one such example is the problem triangle on lead code and trust me once you are done with this video you will be really happy how you were able to solve this problem hello friends welcome back to my channel first i will explain you the problem statement and we will look at the sample test case next we will see why a greedy algorithmic approach won't work for this problem and then we will see two types of solution using the dynamic programming algorithm the top-down programming algorithm the top-down programming algorithm the top-down approach and the bottom-up approach and the bottom-up approach and the bottom-up approach following it we will also do a dry run of the code so that you understand how all of this actually works in action without further ado let's get started let us quickly try to make sure that we are understanding the problem statement correctly in this problem you are given a triangle of integers and you have to determine the smallest sum that is possible starting from the top now there is one condition though you can only go to the adjacent nodes when you are traveling in the downward direction so what does that actually mean so a triangle is given in the form of a lift right and when you expand this list your triangle will look something like this correct the first element is 2 then in the next level you have 3 and 4 in the next level you have 6 5 7 and so on right now you have to find the minimum sum when you are starting from the top right you start from the top and then you can only go to one of the adjacent nodes so when you are starting from two you can either go to three or you can go to four right but what happens when you move one level down if you come at three then you can only go to either six or five you cannot go to seven right but if you come at four then you can only go to 5 and 7 and you cannot go to 6 right so this will keep on happening as you move down and down let us say i reached 7 then i can only advance to 8 and 3 i cannot advance to four and one right so when you're moving down and when you're selecting elements it is very important that you select these elements in such a way that the sum that you form should be the minimum sum in this particular test case you will find a minimum sum when you select 2 then 3 then 5 and then 1 and this sum will be 11 and for this particular test case 11 is your answer now it is also very important to understand how you are forming this triangle for example if i form my triangle like this now this is also a triangle right but your problem cannot be solved using this because if you look at this case five has three adjacent elements four one and eight however that is not the case five only has two adjacent elements and that is one and eight so in this kind of a problem statement it is very essential that you understand the problem statement correctly now if you want to try this problem once again on your own feel free otherwise let us type into the solution and see what we can do about it let us say you are given this triangle right and i ask you okay find me the minimum sum the most obvious solution would be a brute force solution right and that is to explore each path so you will try 2 3 6 4 then you will try 2 3 6 1 then 2 3 5 8 so many combinations you will just spend a lot of time trying to find all these combinations and certainly this brute force method will not work you need to find something better right the next solution that could come to your mind is a greedy approach right and how does a greedy approach work you have to find out the minimum sum correct and this is your greedy criteria so what do you do about it you start with the first element and that is two next you have to select some element from the bottom level right being greedy you want a minimum sum and what you can do is okay out of these two elements i will select the smaller element so i select 3. now moving on i get to level 3 and this time i have to select from these two numbers being greedy again i select the smaller element and then once again i move on to level four i will try to select the minimum element from the two adjacent elements and then once again i select one and voila i found the minimum sum you are gonna try to write the code for this but eventually it will fail why that is because a greedy approach will not work for this problem let us take up one more example this time my triangle looks like this look at all the elements and let us try the greedy approach once again i start off with element number two moving on to my next level i pick one then i can either go to eight or i can go to nine i pick the smaller element that is 8 and then out of 4 and 1 i will pick one again so what is the sum that i get that is 12 correct but the minimum sum is not 12. if you look closely the minimum sum will be formed when we pick up these four elements from each of these levels so from 2 i go to 3 then 1 and then 3 again and in this case the minimum sum will be 9. so if your input triangle looks like this then 9 should be your answer right so this is how we can say that okay a greedy algorithmic approach will not be an applicable solution definitely we need to approach this problem in some other way right and that is where the concept of dynamic programming comes in right what you do in dynamic programming at every level you are gonna store your results right so if your triangle was only one level what is the minimum sum that is two correct if your triangle just had two levels then what is the minimum sum would be three right because you are picking two and one correct what if your triangle had three levels now what you need to do is you need to store the result for this small triangle at level number two and you are gonna include this new level as well right so this is how you know you have to use memoization next we will add one more level and we will keep on adding levels to find the ultimate solution right let us see how we can actually apply dynamic programming to solve this question now that we have concluded that we need to use dynamic programming how do you actually solve it let us take up our sample triangle once again right this is the second example that we have and what we're going to do is we have to store the results at each level that is memoization correct so i have created this empty triangle where i will be storing all of these results and how do you proceed let us say my triangle only had one level then what is the minimum sum that i can get i can only get a minimum sum of two correct moving on what if my triangle had two levels then from element 2 i can either go to 1 or i can go to 3 correct and what i'm going to just do is i will write down these values so either i do 2 plus 1 that is 3 or i do 2 plus 3 and that is 5. so now if someone asks you what is the minimum sum for a triangle of height 2 then you are just gonna scan these two values and you can say that ok 3 will be the minimum sum right now simply extend this concept let us say this time my triangle has three levels right that means from level two i need to get to level three so how are we gonna fill these values from one either i can go to eight or i can go to nine so either i add a eight or i add a nine so if i'll add a eight to 3 i will get 11 or if i add a 9 to 3 i will get 12 but wait a minute you can also go to the next level from number 3 correct from 3 also you can either go to 9 or you can go to 1 right if i am going to number 9 then i have to add 9 so i will try to add 9 to 5 correct when i add 9 plus 5 that is 14 so i have either a choice of 12 or 14 in this place and in the next place i can add 1 right so i will try to add a 1 to 5 and that will give me 6. this is the interesting part over here when you have 2 values pick the smaller one because we have to determine the minimum sum right so from these two values what i'm gonna do is i will just pick the value 12. do you see how we are approaching this problem now so if someone asks you what is the minimum sum if your height is three then you're just gonna scan this third level and you can say that okay six will be my minimum sum now once again expand this to include the fourth level as well for the fourth level from eight i can either add four or i can add one so 2 11 either i will add 4 or i will add 1 now to 9 either i can add 1 or i can add 8 so to 12 either i will add 1 or i will add 8 right so this gives me 12 plus 1 that is 13 or 12 plus 8 that is 20. for the last one 6 either i add 8 or i add a 3. so 6 plus 8 is 14 and 6 plus 3 is 9. out of these two values pick the smaller one now if someone asks you what is the minimum sum if your height of the triangle is 4 then 9 is your answer correct and this is how we were able to apply the dynamic programming technique and we went from top all the way to down and this is why this is the top down technique similarly we can also solve this problem using the bottom up technique let us take up our sample triangle once again and this is my empty space where i will store all of my memoization right so when we went from top to bottom we started off with the first element right that was two now we want to go bottom up right so where do we start off with the lower most row correct so in the lower most row i will write down 4 1 8 and 3. now what do you have to move up one level right and to determine these values you want a smaller sum right so if you are coming from this direction then 4 plus 8 will give you 12 right but if you come to 8 from 1 then you will get a value of 9 right and since we have to get the smaller value we will choose 9 over here correct similarly if you have to reach 9 how can you do it either you come by a 1 or you go by 8 correct we want a smaller sum right so i will choose the value 1 over here so i can simply write down 9 plus 1 and that is 10. similarly for 1 how can we reach either you can use 8 or you can use 3. since we want a smaller value i will use 3 so 3 plus 1 will give me 4 and i can write down 4 in my result correct now using the similar technique move up one level you have to reach 1 either you can move from this place or you can move up from this place right but the numbers at this place are 9 and 10 and you want to pick the smaller value so i'm gonna pick 9 and then i will write 1 plus 9 and that is 10. similarly to reach 3 either i can use this place or i can use this place and the numbers in this place are 10 and 4 i will choose the smaller value that is 4 so i will do 3 plus 4 and that is 7. once more for the top most value either you can reach from this place or this place and the sums at both of these places are 10 and 7 i will pick the smaller sum and i will do 2 plus 7 and that will give me 9. so in our bottom up approach what do you see that you get your minimum sum at the top and this will be your answer right now although this bottom-up answer right now although this bottom-up answer right now although this bottom-up approach is easier to understand and implement the top-down approach is very implement the top-down approach is very implement the top-down approach is very effective to understand how dynamic programming actually works now let us quickly do a dry run of this bottom up approach and see how it actually works on the left side of your screen you have the actual code to implement the solution and on the right once again i have my sample triangle that is passed in as a list of lift to this method minimum total now what we want to do first of all we want to deal with the height of this triangle right because we were going from bottom to up so what we do is we initialize the height and then we also create a dp two-dimensional array that create a dp two-dimensional array that create a dp two-dimensional array that will store all of these results correct oh and by the way this complete code and its test cases are also available in my github profile moving on with our dry run you know that we go from the bottom up direction right and hence we start a for loop that will start at the lower most level that is height minus one correct and for each iteration what do we will fill in this dp array and what do we do over here we take the element and then we add the minimum of the two bottom adjacent elements right you know that when an array is initialized all these values will be zero correct so when we are calculating for the bottom most row it will try to pick a minimum value out of all of these zeros right since they are same and they are zero the bottom moved row will still remain 4 1 8 and 3. correct things will start to get interesting when we move on to a upper row 8 9 1 as soon as we reach the first element that is 8 what do we do over here we get the element that is 8 and then we try to find the minimum value from the lower level so for eight we will either add four or we will add one since we are picking the smaller value i will pick one and i am going to write down nine over here similarly for nine either i will choose 1 or 8. i pick the minimum value so i write down 10. similarly for 1 i will either pick from 8 or 3. i pick the smaller value that is 3 so i write down 4. so this way you are gonna complete this memoization array and ultimately at the top the zero comma zero element you will have your answer and that will be the minimum sum right the time complexity of this solution is order of n square that is because we are using two for loops and the space complexity of this solution is also order of n square that is because we need to create a memoization array to store all of our intermediate results i hope i was able to simplify the problem and its solution for you as per my final thoughts i just want to say that whenever you see a problem and you feel that this problem will require dynamic programming first of all try to prove that this problem cannot be solved by the greedy algorithmic approach because if there is a greedy solution you do not necessarily want to apply the dynamic programming technique right and to prove that this problem can be solved with the dynamic programming the problem should have a optimal substructure property that means each of the problem part is a complete problem in itself and when you solve the entire problem you will arrive at your answer in our dry run we use the bottom up approach correct try to solve this problem on your own using the top down approach of dynamic programming tell me all the problems that you face can you find any other technique to solve the same problem what is the time complexity how do things change tell me everything in the comment section below and i would love to discuss all of them with you also let me know what other problems did you find which can be solved using this top down and a bottom-up approach so top down and a bottom-up approach so top down and a bottom-up approach so what do you do about it you will be also glad to know that a text-based glad to know that a text-based glad to know that a text-based explanation to this content is available on the website a on the website a on the website a pretty handy website for your programming needs 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 tell me what you want to learn next until then see ya
Triangle
triangle
Given a `triangle` array, return _the minimum path sum from top to bottom_. For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row. **Example 1:** **Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\] **Output:** 11 **Explanation:** The triangle looks like: 2 3 4 6 5 7 4 1 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). **Example 2:** **Input:** triangle = \[\[-10\]\] **Output:** -10 **Constraints:** * `1 <= triangle.length <= 200` * `triangle[0].length == 1` * `triangle[i].length == triangle[i - 1].length + 1` * `-104 <= triangle[i][j] <= 104` **Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
null
Array,Dynamic Programming
Medium
null
881
hey everybody this is larry this is day 24 of the march ooh this quick let go daily challenge hit the like button to subscribe or enjoy my discord let me know what you think about today's farm boats to save people i hope this farm is boat boatloads of fun so yeah join me on discord to let me know what you think about that comment a little bit tired today i don't know why but uh i hope y'all doing all right uh it's you know uh mid of the week hope y'all just like having a good week and all that good stuff okay so let's see so you're given people's i the weight of i person an infinite amount of votes where each per book can carry a rate limit rate maximum rate of limit each bulk contain carries at most two people at the same time providing the sum of the rate of the people's at most limit return the minimum number of both votes to carry uh every given person okay uh let's see um i think greedy is probably the way to go all right um oh excuse me oh man well okay so i mean i think it's so the answer is gonna be the way um uh let's see so the answer is gonna be some sort of greedy right um just because um we're trying to maximize the number of boats and my idea would be that um the key thing to note this is that you can uh the only two choices you can make with a boat which is to carry one person or two people right and then you have a couple of things that you might do which is that it's hard to kind of explain it's what i'm thinking is more like some sort of property where when you take out one or two people um the rest of the answer is still true right so almost kind of like really in that way in that um in that then varian uh when we talk about varying a lot on this channel and also because it's important for this kind of problem solving is that then variant after taking out people will be the same right and i think if we the way that i would think about it um is that um it is basically going from uh the way that we think about is going from large to small and then see if you can fit another person on that boat um because so there really there only a couple there are a couple of ways you can think about this right one is that um there is a wrong way to be greedy right for example if your limit is um so let's say you have two one when your limit is equal to three um if you do one on one boat then obviously you're gonna end up with three boats right and that is all could be suboptimal because you could do you can do uh one two and one two to make it two boats right so however if you get it from uh greedy in a way going from the large person well uh like the largest person um well because that person always going to take a bow anyway assuming that it is on the limit yep um it was always going to make a vote um the question is okay let's say you have the largest person that will always have his own boat uh their own vote um in that case can it fit another person right and also in that case you would choose greedily what is the biggest person that um you can remove to uh to pair in the same boat together and in that case then you would take that person because one is that one is forced and then the other one person on that boat would be almost like a freebie right if you could fit in someone you should fit in someone and so forth um i think that's the idea and i think that should be good um the question is that now how do you implement this right what is the solution there are a couple of ways you can do i think you can i think you could have uh take yeah i mean i think the way that i would do it is just by two pointers um but you can also view a little bit sketch with the two pointers well maybe two point is not the right way to say it because i mean two pointers is precise even though you are going to use two pointers but the idea is that uh or you know you can you also use binary search or something like that but the idea behind the two point algorithm is just having a pointer on our current index and then having a second pointer that is in the middle of the i mean it will start in the beginning but the second point with the middle match these two and then move to the right as you use them uh and that should be good the idea of course is also based on the second observation on variant that for every number that you're looking at you're trying to get the biggest number that you haven't used before that is under the limit three and of course as you go from left to right to make these numbers smaller um oh actually maybe i'm more uh hmm wait give me a second maybe i was wrong this one um as you make these numbers smaller can you deal with two pointers maybe i was wrong i was gonna say that as you make these numbers smaller um you also make this number smaller but that's not true actually so i messed up here in my explanation um well in that case then we can just do binary research um every time i mean that i know is right um you can also use like a hash table or something like that i'm giving a degree is 10 to the fourth but yeah okay yeah let's do that hmm let me think about this for a second oh i do wonder if there's a linear time solution which is what i'm thinking about because as you use these numbers i also wonder if there is a property where so one way to do about it so one way to solve this problem and that is going to be right is that you sort this and then in a sorted list or something like that and you binary search every time and then remove them from the list as you do a binary search um that'll work that'll be analog again and you know that's fun but i'm trying to think uh whether you can do in linear time and i also have a vague idea of a linear time algorithm but i cannot i do not know off my head writer that is correct um and the idea of that algorithm is that let's say you know obviously you still sorted so m433 maybe even sort it the other way i guess it doesn't really matter um i think it's sufficient huh i have a really funky solution and i don't know that i can prove it but the idea is that you just match this three with this four you match this three of just five and you do it for every number um to see if it's right um to see if you need one boat or two both for these pair of people i have some recollection that this may work but maybe i'm wrong all right well i think the first thing i would wow this one is like i know that i just woke up from a nap and that's why you could see that i'm a little sluggish but this one is still for me for loop um because these mathematical things are kind of very tricky um because i have a lot of feelings i love intuition from experience but for me to actually think about the proofs is a way a bit trickier um but that said um if this was a contest let's step back for a second if this was a contest sing to n is equal to 10 to the sorry 5 times 10 to the fourth uh that would be good enough for me to use an n log n solution because then i'll get the solution i know that i don't have to prove right um yeah so let's actually do that and then maybe afterwards maybe not uh we'll see if i can prove this to be better right so okay so let's use sorted list uh let's also import it um i think sorted list you can have a key maybe i'm wrong on this one hang on let me google this real quick yeah okay so then oh basically what i want to do is sort it backwards um and then also let's just do people right all right let's run it real quick so i could see if this key thing is right uh okay well uh something like that i don't remember huh forget how to just get a list of the items and saw the list um give me a second hmm so there was like a dot items without something yeah maybe not i feel like this should work but maybe the key thing is making mucking it up oh no okay it did work it just printed out that out i just kind of miss missed it uh okay because i don't know it's a bunch of stuff okay so yeah so it works like that so then now what all we have to do is um while length of s sl is greater than zero um let's just say item is equal as of zero um also let's keep track of the count of the number of boats so boats is equal to zero um we get this item we remove this item and then we do a bino bisect left on limit minus item is that right so basically everyone yeah so this will give us so i'm because we sorted the other way i'm not used to sorting it the other way so the bicep left i just have to make sure that uh when it goes over it's smaller right so yeah so index is equal to this if index is less than sl the length of the list that means that is a good item then um yeah we can remove that um and then that is one vote and that's pretty much it i know that i spent a long time talking about it but i think this should be right just because it just has to be it's just doing it one item at a time and yeah that's going to submit but i don't want to i do want uh that'll be funny if i get time to exceed it now but it is very slow um i do want to do just a linear time and i'm just not thinking it correctly so let's take a look at past larry oh just in case you want to know this is n log n because for each item we're going to remove the first item and this is you know binary search on every operation um yeah and this sorting so it's going to be n log n um yeah an o of n space for a sorted list did i do a linear time rule huh so i guess well i guess you still need to sort so i forgot about it sorted so i guess yeah huh i mean i guess that's the way it is you just peel what i was talking about earlier pair the heaviest with the lightest and then just walk with the two pointers um yeah i guess that will work um i don't know maybe i'm just really off today apologies my friends but uh but sometimes i want to say it as long as you solve it's fine though this is the timing is much so much slow usually it's only a little bit slower and i don't care about it even if it's like double the speed it or double the slowness i don't mind but this is a little bit slow so it's a little bit concerning but that said it has the same complexity and log n and if you need to sort it you're not going to do better than that you can maybe do some sort of uh quote unquote linear time algorithm with respect to putting everything in a hash table like i mentioned and then kind of walk it up it's kind of like a counting sword so it's not really linear it's like all of um alpha or something like that as you kind of walk up where alpha is to limit um but yeah but in this case that's also smaller than whatever so that's good too um yeah that's what i have for today i'm a little bit off so my apologies hope this was educational though i hope you learned something uh that's all i have though stay good stay healthy to good mental health i'll see you later and take care bye
Boats to Save People
loud-and-rich
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
Array,Depth-First Search,Graph,Topological Sort
Medium
null
1,095
so lead code problem of the day and here we bring solution for today's lead code problem that is called as find in a mountain array this is the most interesting question and I'm going to solve this question in three important steps so I highly recommend you to stay in the end of my video just in case if you're new to our Channel subscribe the runtime error to get the daily solution for the lead code problem of the day so let's start with the today's problem so what does today's question says that they were given an array called as the ARR and that array is called as a mountain array so what do this mountain array says that so here they have given everything about it so a first value will be less than my second is less than third and third will be less than till I minus one and at particular point I start decreasing which means can I say that my first array is strictly increasing and at particular point my array start strictly decreasing and this is called as a mountain array right simply just look like a mountain so this is what they called as a mountain array and at the same time they have told do my size of my array will always be greater than or equal to 3 which means I will not have array of size 1 and two I will be having an array of size strictly greater than or equal to three so what does we need to find is they have given an Mountain array and we need to return the minimum index of Target value what does a minimum index say that say for example I have an array 1 2 3 4 5 3 and one and I need to check whether my key three is present or not so here we can say that the three is presented index 2 and it has also presented index 3 4 5 at index 5 so which is the minimum index so two is the minimum so I need to Simply return two so I hope so you got me that we need to return the minimum index of that particular value and just in case the G value which I'm looking in the array if that value is not present I need to Simply return minus1 and one of the most important and defining part of this question is this section right what does it mean is we cannot call mountain. gate more than 100 times which means we need to call mountain. gate value or this function exactly equal to 100 times or less than equal to 100 times we are not supposed to call more than 100 times therefore if you're calling the mountain. gate more than 100 times it will show us wrong answer it is directly stated in the question and since it is not our normal array we cannot access the value of array like this right like we are mentioning the name of an array and within next no we cannot access the value of array by using an index we have to access the value of my array using the get function similarly in order to get the length of my array I need to follow mountain. length so I hope so you understood the meaning of the question now let's try to Define this section more in detail so what does this section says that what see my first element is less than second is less than third dot until my I point and at this particular point I my start decreasing so can I say that till my 12 my are is in increasing order strictly increasing order at 12 my array is strictly decreasing order so simply I will write here till the year my array is strictly increasing and from this point till end my array is strictly decreasing so I hope so you got the meaning of this section now if you try to plot this number on the graph it will look like this see you can see over here is still 12 strictly increasing there is no duplicate element in it and again it is stly decreasing again you find there is no any duplicate element this so I hope so you got the meaning of the mountain AR this is how it just simply look like a mountain you can see it is simply look like the mountain now let's try to analysis since it contains strictly increasing and strictly decreasing now the question comes will my array contains a duplicate value because the question directly says that it is strictly right it is strictly so with the help of this word we might find that there might not be any duplicate number in my array but the point is will my array contains a duplicate value the answer to this question is yes we can see AR is that till 12 my array is strictly increasing and to this section there is no any duplicate number we can see it's 1 2 4 7 8 9 10 11 there is no any duplicate value but to the right of this 12 I have four which is already was pres in strictly increasing which means if my strictly increasing and strictly decreasing there might be a possibil to z the element which is present in my strictly increasing part that element can also be present in my strictly decreasing part here you can see that I got four in decreasing part I also have the four in my increasing part I have seven in my decreasing part I also have the seven in my decreasing part so one thing we came to know that even though it is strictly increasing or strictly decreasing my array will still contains a duplicate values in my element so let's try to analysis the solution and try to check how we can solve this question now what they have told us they have given one particular array which is called as a mountain array so what does Mountain array says that at particular point my AR is still be increasing and after this point my array strictly decreased and we need to find simply whether my target element is my present in my array or not and if my target element is present in my array I need to return the minimum index of it so what does minimum index says that say for example my 11 is present at index 2 and my 11 is presented in index 9 so which is minimum of this two so I need to return the two so this is how we need to in the minimum index now the question comes will the linear sege work because what we are supposed to do we are supposed to Che simply with man AR contains a Target element or not so if I try to apply the linear search on this array what will happen I will check on this element is it 11 no so I'll go on comparing every single element till I come across the 11 now I find the 11 then I simply return it because it is a first occurrence of el and I need to return the minimum index that is it but the point is do the linear search looks a lot more easier but the question is will this linear search work on this question because the question says that what does the question says that we cannot make more than 100 mountain. gate function calls right but point is say for example I WR this 11 at an index 9 now say for example I get an array of size say for example 400 and this is my 11 present at an index suppose at 500 right then what I need to do is I need to go on checking this till I come across 500 Index so but the point is as I told you earlier that we cannot access the element of an array normally like we do in normal problems we have to use a get function but what we're doing over here is we're calling the get function 500 times which is for sure greater than equal to 100 which is greater than 100 and anyhow we are going to get a wrong answer because we are trying to call the mountain. gate more than 100 times right we're calling it more than 100 times so for sure even though you able to get the answer but it will show you the wrong answer because we are not allowed to make the call of mountain. gate more than 100 times so the question comes how we can solve this qu so the one thing is for sure if we are given one particular array and we need to find the one target element and the linear search is not working on it so what comes in our for sure binary search right so let's try to check how does the binary search works on our problem we know that in order to work the bner SE there is one prerequisite and what does that my array has to be sorted but if you try to look at this array is this array sorted completely no because if I try to observe it I can say that this array is partially sorted because at this particular point my array is sorted and again it is start decreasing so this is not a completely sorted array then the question comes how does a binary search will work on this array so let's try to analyze it can I say till index 7 my array is completely sorted right till 12 my array is completely sorted and after 12 my array is started decreasing which means there is this break point this is a break point up to which my array is completely sorted right till 12 my AR is completely sorted and from this part my array started decreasing so one thing I can make sure that if I find one particular element up to which my array is completely sorted and after that my array is completely decreasing so can I simply say that if once I get this value that is 12 or the index that is seven I can simply apply B your search on this part and B your search on this part because if we try to observe this part is completely sorted and this is what we required for the binary result right I have to keep my array completely sorted so can I say from 1 to 12 my array is completely sorted and I can simply apply binary search on it whereas on the other hand if I try to get the values from 11 to three my is also completely sorted but it is sorted in decreasing order and this is sorted in increasing order but the point is don't matter whether it is increasing or whether it is decreasing what matters is my is completely sorted right so can I simply say that once I find this particular element or the index of an element which we call as a p element now the question comes why we are calling P to 12 because we can say that but 12 is greater than 10 and my 12 is greater than 11 and to the left of my 12 all the elements are sorted in increasing order right it is sorted in increasing order whereas all the elements to the right of my to are sorted in decreasing order so I need to Simply find where is my Peak element what does the peak element the element which is greater than it both the neighbors so once I get the peak element I can simply apply binary search on the left part and the right part now the question comes why do I need to apply binary search on both the part that is on the left part and on the right part because there might be a possibility that element might be present in this part or might be present in this now the question comes see for example if I'm getting the value at this part do I need to search in this part absolutely no because at the end what do I need to return the minimum index and as you can see that here I'm getting the minimum index I don't need to check over here because even if you're able to get the value in the right part it will give you the mag Z index but the point is we need to have a minimum index so what I will do is so let's have to write so first thing we will do is we will find the peak element we'll find the peak element which means the element which is greater than this previous and greater than its next element and the second is apply binary search on both that is left part and right part now if I'm able to get the value in the right part I will not check on the in the right part and if I'm not able to get the value in left part I will check in the right part and in both the cases if I'm not getting any value I will simply written the minus one as it is told in the question so simply what I will do is first of all I will try to check the peak element now let's try to analysis how we can find the peak element let's try to analyze where we can find the peak value it can be present in X or Y or Z so the question comes how we will come to know that in which ction that is increasing or decreasing or at the peak I will find the peak Val so say for example I'm calculating the mid as m is equal to low plus High ided by 2 and now from this that is Mountain do array I'm writing the short form as m a mountain array of mid is less than mountain of array of mid + 1 so what does this statments mid + 1 so what does this statments mid + 1 so what does this statments indicate can I say with help of this statments I can easily adjust that I'm standing at this portion because as I told you my X will always be less than x + 1 since this section is always in + 1 since this section is always in + 1 since this section is always in increasing order therefore with help of this case I can see that I'm present over here but the question comes will I find the peak value at this section absolutely not because all the values in this sections are in increasing order and as I told you my P value has to be greater than its previous and has to be greater than its next value but here I will not find any value Which is less than greater than it previous because X is less than x + 1 I cannot say this is less than x + 1 I cannot say this is less than x + 1 I cannot say this is a Bak value so I can simply say that whenever I occur at this condition I have to shift either at to Z or either at to Y because there is no any such case where I can find the peak value at increasing order so during this first case simply what I will do is I will simply shift my low to its right of mid so I will simply do low is equal to Mid + 1 now the second case say for example + 1 now the second case say for example + 1 now the second case say for example if I'm getting the mid as M of mid is equal to mountain of ARA of mid + one will this case will exist of mid + one will this case will exist of mid + one will this case will exist where both the value of mid and mid + one will always value of mid and mid + one will always value of mid and mid + one will always be equal absolutely no because there are the three cases you can say there is no any case where I'm getting the equal to sign so this case will not be possible therefore we don't need to worry about handling the equal to and now the third case that is possible that what can I say is mountain of array of mid is strictly greater than Mountain array. Gate mid + 1 now what does it mean is Gate mid + 1 now what does it mean is Gate mid + 1 now what does it mean is which are the two cases where I can find this third one can I simply say that these are the two cases that either I will be pointing at this position or either I'm getting at this position but the point is can I say if I'm getting this value then mid will be strictly by Peak value absolutely no because what I'm getting over here is okay I'm getting that X my Z is greater than it next value or my Y is greater than it next value but the point is what about it previous value because as I told you a P value has to be greater than its next value and has to be greater than its previous value so from this section we can come to know that the next value is greater than the smaller than the peak so I need to find do I have the previous value Which is less than Peak so that's the reason why if I'm getting this value I simply transer my high to Mid I will not transer to midus one because say for example I'm standing over here I'm getting the mid there might be a possibility that I'm getting the peak value either at Z or somewhere between here so I simply cannot transform my low high Beyond Z or Beyond M I can find PE over here or I can find pe4 here so I hope so you got the these three sentences really now once we find the Pak value now on this array we can come to know that I got the peak value over here say for example this is my Peak index now what I will do is now suppose I need to check whether the value 8 is present or not I need to check my 8 is present or not now what I will do is since I know that in order to apply the binary s my has to be completely sorted but one thing I came to know that till my Peak index my this array is completely sorted so can I simply apply the B new resarch on this section first and afterward I can apply the binary search on this section so I have to use two binary search that is first from zero to Peak index and my second is from Peak index + one to n minus one that is from this point to this point and later from this to this so once you apply the binary search we will simply check with the help of biner search whether my key is present or not if it is present simply return the index of it and if it is not present simply return the minus one of it so I hope so you got the algorithm very detailed manner now let's try to check the C++ and Java code for this check the C++ and Java code for this check the C++ and Java code for this problem so this is the code for finding the peak value here you can see that I wrote the function that is a peak index and what I did is I simply pass the two parameters that is Mountain array and this is the size of my array and I simply search and I use a two that is start and end to point to se spaces say for example this is my this is will be my start and at the end this will be my end so with the help of these two variables I started searching and I simply found the mid then I checked if my mid is less than mid + one what does my mid is less than mid + one what does my mid is less than mid + one what does it mean is I'm simply standing at this section so I need to Simply move out to either this or this so this is what I did so I simply shied my start to Mid plus one so I came over here and what does it simply says that it says these two condition if I'm getting the mountain that said of Y is greater than this previous I have to come back because either my Peak can be this right these and these are not my Peak value my head is my Peak value so I have to come over here and finally my start will automatically point to my Peak index so I simply return the peak index so this function is all about finding the peak index now let's try to check how we can apply the binary search for it so here is a function that are the two Min firm functions that we need to apply as I told you earlier so this is our basic function that first of all I calculated the size of my array then I found the peak index as I told you over here this is the function used to find the peak index so once I get the peak index what I did is I got the first B SE from the index Z to the peak index say for example this is my Peak index so what I told you earlier that till my Peak index my array is strictly increasing order so first I'm applying the binary search on this particular portion and later on I'm again applying the binary search on the remaining portion if and only if I'm not got any value or the index of that particular value here I can see that if my index is not equal to minus one I don't need to search on the left right part because I need a minimum index so I don't need to go to the right part if it is equal to minus1 what does it mean it at this particular portion I'm not getting the index or the value which I'm looking for therefore I need to check is that value present to the right of my Peak index so again I pass that is Pak + one to nus again I pass that is Pak + one to nus again I pass that is Pak + one to nus one that is from this section to this section I need to search so this was the most simplest question only thing is we need to understand the meaning of question thly so I hope so you understood the meaning of the question and the solution of this question properly so just in case if you're new to our channel are you really like the way I'm teaching you or just giving you the solution for the question do hit the Subscribe button so that you can come across a daily lead code problem till then I'm signing off
Find in Mountain Array
two-city-scheduling
_(This problem is an **interactive problem**.)_ You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`. **You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface: * `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed). * `MountainArray.length()` returns the length of the array. Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification. **Example 1:** **Input:** array = \[1,2,3,4,5,3,1\], target = 3 **Output:** 2 **Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. **Example 2:** **Input:** array = \[0,1,2,4,2,1\], target = 3 **Output:** -1 **Explanation:** 3 does not exist in `the array,` so we return -1. **Constraints:** * `3 <= mountain_arr.length() <= 104` * `0 <= target <= 109` * `0 <= mountain_arr.get(index) <= 109`
null
Array,Greedy,Sorting
Medium
null
844
in this video we will see second solution of backspace string compare and it's lead code problem number 844 and it's also part of day 9 question of 30 days lead coding challenge in my previous video i had given a solution where we used two stacks one for each of the strings and uh here we will avoid the stacks and we will solve it in order one space so when we use stacks we can at most push number of characters uh into that stack so that was the order n solution and we can also replicate the same behavior the stack behavior with string variables so when you push or pop from a stack that is equivalent to adding a character in the end or trimming the character from the string so in both cases we will consider that as on space here we will not use any additional on space or any additional string variable but we will do it in order one so let's briefly recap at the problem again so you are given two strings s and t here this has symbol means pressing of backspace on a keyword keyboard so if there is no character and you press backspace then nothing will be deleted because already there was no character but if there is some character and you press a backspace then this character will be deleted so here a comes then you press backspace so a is deleted then you press backspace nothing is there so nothing happens then you type c so ultimately it results in c similarly here you press backspace this is of no use then you type a then backspace so a is gone and then you type c so c is there so you see that these two denote the same character after typing a backspace c you get c after typing backspace a backspace c you can get c as the final output so these are same so we should return true here but let's say we had one big backspace here also in that case it would be empty string and we would return false so the approach that we will follow here is that uh we will start from the end so we have a pointer here one pointer is here and if none of the characters are hash or backspace we will check if they are equal or not so if they are equal we will move this pointer to 1 less minus so initially it will be 2 4 so if index starts from 0 to 3 initially it will be 3 then both are equal so both i will decrement by 1 so it will become 2 it will also become 2. this can be of different length as is the case here in this case it's same and now we encounter hash so whenever we encounter has we don't compare hash because there are multiple cases which can happen with it maybe that there are lots of character before this but before this there is no characters so you will not compare this but instead when you encounter hash you need to check to the left which characters will be deleted because we are pressing a backspace here but you need to consider how many asses are there how many backspace keys are there because you will you cannot treat this as a character so if you see backspace and you delete the immediately preceding character you see that this will be deleted but this is not the case in fact we have two backspaces here so we should delete two digits here if we don't have two digits then we will just delete one and we will get empty string so what we will do whenever we encounter a backspace we will keep track of how many backspaces are there in a variable called count so whenever we encounter backspace we increment the count and whenever we encounter a non-hash or encounter a non-hash or encounter a non-hash or normal character we will decrement the count so this will be when the encounter has this is when normal character and when we reach 0 so let's say there were two has characters followed by c d e so plus one because one has then again has so plus two then these two will delete two characters so we encounter one character we delete it we will not compare these with the second string because these do not exist we are just trying to find which key which characters will finally exist after the sequence of these steps so we will not compare c with some character in second string first we need to arrive which character we should compare so here we have two backspaces so we need to delete two characters or it may be possible that there are not two characters after this two maybe that we have hash has then just one character followed by another hash then d e f so here we have two asses so this should delete two characters but we encountered just one here so one of them will delete this and one is pending and this is another backspace we have added so now we have two more backspaces than characters so one deleted one of these and two more so this will delete these two so the result of this whole part is an empty string now the count has become zero so whenever we encounter backspace we increment when we encounter character we decrement and you know the reason now our account is balanced now so nothing from this part and this is the character we need to compare to the to a character in different string in the different string also we will do the same thing if let's say this is the variable the position is i this in this second string the position is j so here we had encountered none of them was backspace at inj initially we compared they are equal fine if they are not equal we will return straight away that they are not equal but if they are equal we will decrement both so here we encountered hash so we now need to figure out what is the character to compare and similarly if here also we got hash we will again do the same thing and here let's say we arrive at another character c1 and this is c2 and again we will compare if c1 is equal to c2 or not if they are equal then we will decrement both i and j and do the same in the remaining part and if they are not equal we will return false and when should we stop let's say we reach to zero and once again we decrement we reach to minus one then we will stop when both of them goes beyond minus beyond zero so uh let's walk through this example so here g is equal so it will be here and this will be here inj so here we have plus 2 back to back and then minus 2 so 0 again plus 1 minus 1 so the next character after g is straight away z now find the next character after in the second string so plus 2 minus 2 0 plus 1 minus 1 again we will reach z so after comparing g we will compare z they are same we decrement we reach n again none of them are hash so we compare they are equal so we decrement both here it reaches minus one here it doesn't reach less than zero we reach here but we will not stop here uh this is just one case it may be possible that we have titrated this whole string but in the second string whatever is remaining uh we have not reached -1 does not mean uh we have not reached -1 does not mean uh we have not reached -1 does not mean that there are some extra characters maybe that character from here till the beginning don't contribute anything so this is just one extra case uh the same way like this these set of characters don't contribute anything they are empty string so if one of them reaches less than zero but other has not then we will continue this logic count plus 4 has and minus 4 character and if this is the special case where everything from this j till 0 contribute nothing then automatically count will become 0 when it reaches -1 count will become 0 when it reaches -1 count will become 0 when it reaches -1 if there are some more characters like a here then count will become 0 here when we reach at b because here we did plus 1 then here minus 1 0 but still it's not minus 1 then we will return false so let's see the code for this it should be more clear when we see the code so this is our earlier solution where we used two stacks so whenever we encountered a hash we popped out from the stack and whenever we encounter non hash we pushed into the stack and finally we compared both of the stack by popping one element at a time from the top the same behavior is replicated with using string with the same logic that i told earlier that pushing into a stack is same as appending a character in the end of string and popping from the stack is same as trimming out the last character from the string so both are same now we will use we will write our today's logic without any extra memory in the form of stack or string so let's denote the first index by i and our strings are s capital s and t so s dot length minus one t dot length minus 1 and while i greater than equal to 0 or j greater than equal to 0 and why we are using or here because of the same logic that maybe one of them has reached negative but other has not reached but we have to check just one case that everything from here till 0 should be empty string in that case it will automatically count will automatically become 0 when it crosses 0 if it doesn't cross 0 then we will return false now we will keep track of count here will be the count of backspaces initially it's zero while i greater than equal to zero this we have to always check within a while loop and count so if count is 0 we have not found the character which we are looking for in order to compare or count has become 0 as is in this case so let's say here we had a here before b not here let's say we have a b then hash then again has so here count is one count is 2 then count minus 1 so 2 minus 1 is 1 then here count becomes 0 so we decrement but again we encounter a hash so in this case also so that's why so either count is greater than 0 or s of i is equal to this character then what we will do if s i equal to hash then we do count plus else count minus so if si is not has that means we reached into this while loop because count was greater than zero so we encountered a non-hash otherwise it would have a non-hash otherwise it would have a non-hash otherwise it would have entered this part so we decrement the count is greater than 0 and we encounter a non hash so we decrement the count and finally we do i minus irrespective of this because we have to after comparing a character we move to the left and uh this loop will end when either we have reached beyond zero or our count has become zero and also the current character is not hash so we are ready for comparison the same thing we will do for second string we need to find the character in order to compare here just that we will use j and in place of s it will be t and here also and j minus now we have both the characters so first we will check if i is greater than equal to 0 and j is greater than equal to 0 then if uh if the character in a string s is not equal to character in string j t then we will return false else that means they are equal then we will decrement i we will decrement j and if any of these is less than zero then we will check if and the other one is greater than zero or not so this condition will be executed when either one or both of them are zero if both of them are less than zero it's fine we have compared everything of both the strings if just one of them is less than 0 then we will return false and finally if we did not encounter any of these false situations we will return true let's try to run it on our example and it passes for this simple case let's see on submitting if it passes all the cases or not so it does and it gives a very good result even better somewhat in space as compared to our earlier submissions so this was the submission for using two stacks and this is our current submission and it's better than 100 percent uh of the submissions in terms of time and space we can clearly see why although there is not much difference because these in the test cases these would be smaller values not very large values in order to make difference uh on the scale of megabytes so i hope you liked the problem and you also understood it using the stacks seemed to be an easier solution but without using the stack it was somewhat tricky
Backspace String Compare
backspace-string-compare
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t become "ac ". **Example 2:** **Input:** s = "ab## ", t = "c#d# " **Output:** true **Explanation:** Both s and t become " ". **Example 3:** **Input:** s = "a#c ", t = "b " **Output:** false **Explanation:** s becomes "c " while t becomes "b ". **Constraints:** * `1 <= s.length, t.length <= 200` * `s` and `t` only contain lowercase letters and `'#'` characters. **Follow up:** Can you solve it in `O(n)` time and `O(1)` space?
null
null
Easy
null
500
hey what's going on guys it's illa bell here i recording stuff on youtube chat description for all my information i do all liquid problems uh make sure you subscribe to this channel give me a big thumbs up to support it and this is called keyboard raw you know list of words return the words that can be typed using letters of alphabet on only one rose of american keyboard like the image below we got the regular one and let's look at this example we got those uh words right there and we return the final outputs you may use one character in the keyboard more than once you might assume the input string will only contain letters of alphabet you can see that all those letters are on the same row that's why we include those uh words to the final output we can solve this problem using the features of java 8 that are streams and landers and i'll show you how to do that all you need is the stream of words dot uh filter and we use the functional programming here w2 lower case then you call match and uh the first row that is q w e r y i o p star or then the second one asd l star or and the third one the last one that xc and m and star then you call to array and you construct an array of the type string and use method reference new let's run this code accepted let's submit okay success what do we got those words then we create a stream of words then use a filter method and we turn all those letters from each word uh in words in two lowercase ones and then we take the characters and we check in the case when all those uh characters uh are on the same row match to any of those rows we include um an initial uh word to the final output alaskan dead for example that's it thank you guys for watching leave your comments below i wanna know what you think follow me on social medias um follow me on instagram add me on snapchat give me a big thumbs up to support my channel have a good one i'll see you next time thank you bye
Keyboard Row
keyboard-row
Given an array of strings `words`, return _the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below_. In the **American keyboard**: * the first row consists of the characters `"qwertyuiop "`, * the second row consists of the characters `"asdfghjkl "`, and * the third row consists of the characters `"zxcvbnm "`. **Example 1:** **Input:** words = \[ "Hello ", "Alaska ", "Dad ", "Peace "\] **Output:** \[ "Alaska ", "Dad "\] **Example 2:** **Input:** words = \[ "omk "\] **Output:** \[\] **Example 3:** **Input:** words = \[ "adsdf ", "sfd "\] **Output:** \[ "adsdf ", "sfd "\] **Constraints:** * `1 <= words.length <= 20` * `1 <= words[i].length <= 100` * `words[i]` consists of English letters (both lowercase and uppercase).
null
Array,Hash Table,String
Easy
null
903
hey everybody this is larry this is me doing the bonus question a little bit early to be honest on august 13 2022 uh before my daily prom the reason is mostly just because of logistics and i want i today i do want to mix it up by still trying to do it one i haven't done before but i wouldn't do a difficult one that i haven't done before maybe there's still a lot oh it seems like maybe that'll be okay um and i also just want to give myself enough time because um you know the contest is later today so you know i don't want to start later and then you know maybe once in a contest time i'm stressed whatever so i have time to rest a little bit uh because these things are exhausting for me i'm old um okay hit the like button hit the subscribe button join me on discord and let's see if we could get a problem very quickly wow that was very quick actually as you know from watching my channel there's a lot of uh the ren the rng is not always super fast but today it is anyway uh yeah be sure to hit the like button hit the subscribe button join me on discord show me some love and we'll see how these things go and i haven't done these before at least not on lead code but hopefully we'll get through more of them now you know one day at a time anyway today's bonus problem is 903 valid permutation for d i sequence you're given a string s of length n where s of i is either d and i uh a permutation is d to do if it's a implementation if for all right i okay so has to be okay um hmm well okay first is the mod song my mod i think one thing i've been really bad about is also just reading the problem i think i skipped ahead a little bit and looked at the example you can't i don't know if you could see my eyes but or at least in a way that you know uh tracked my eyes but i was looking here and i and maybe it's very easy to kind of i keep misreading stuff so maybe i need to focus a little bit better don't you know so d you have decreasing i have increasing and number of valid permutations um the first thing to notice is that n is 200 so we can do some uh in terms of complexity we can do n square or something like this or maybe n cubed if you have a very fast n key but at least n choose three which is n cube over six so uh something like that right um at least in python um the other yeah i mean i think that's the thing i would notice um the other thing is that this is permutation um and oh i think and i forgot to mention that the first thought that comes to my mind is going to be dynamic programming um just because you know random permutation this seems like a cometorical thing maybe technically i guess i'm not always sure but you know um okay so by default one number this is kind of why is this something okay so i missed so you're given the string and you have n plus one string okay i mean they actually tell you that but i think i just mis write it a little bit let me actually write this as well down here for now um so the way that i think about these things is try to figure out how to um and because n is less than 200 we can just do some loop that's like maybe something like the suffix and then just count put in a brute force way or 200 or something like that and i and then some formula based on that relationship right uh one thing that's kind of you know the first observation that you need to make uh and i don't know i mean this isn't uh an absolutely needed net uh observation i don't know if it's enough by itself but the idea here is that okay let's say we move first on the first number right then here i'm going to copy your page a little bit let's say we move first on a first number here technically um the way that we can do this permutation let's say we remove the first number then right as you know thinking about suffix then actually uh on first number then it'll be 0 to one right zero two one as well actually um and then this will be one two zero right and what am i doing here is basically um well this is just yeah these are just ones basically what i'm saying is you don't have to actually program this per se but in my mind that's just how you think about the recurrence or the transitionary state is that basically after you pick a number you re-index and after you pick a number you re-index and after you pick a number you re-index and then you have a suffix based on that right um okay i think i have an end cube solution very quickly based off maybe i don't know at least that's my intuition from and to be honest like you know i'm just trying to talk out loud and trying to communicate my understanding of the problem as i'm seeing it i'm solving this live and this one for the first time at least that i can remember i don't have a good memory anymore um so i could be well in these things but you know these are lives of definitely you know but here i'm you know already and sometimes i may be wrong but when i say these things it's just from years and years of experience and solving thousands and tens of thousands of problems so you know there's a build up subconscious almost understanding of some stuff but sometimes they're wrong right it's just like uh you know but that said you know that's what we're doing here uh okay so for example you could let's say we could keep track of the last number right i think maybe that's it but well um how do we structure this right let's say we can move force on one number like basically with a for loop then how do you want to represent the rest of the state because it doesn't it's not uh because it's not uh maybe because it doesn't partition the sub problems i think that's why i'm like maybe that's not quite right but what does the dream mean to me the three means that um maybe that is good enough you just kind of keep forcing it as n cube is n cube fast enough though 200 cube is always a little bit sketch we'll give it a spin all right so okay let's do it a little bit and then we could do something like say um i don't get count number naming is hard um and then we have the index and then we just have the last number right and of course we have to kind of be really careful is it the last number or we have to be really careful because we also want to make sure that we index the numbers um i think another way to also think about it is there that there's another dimension that's like x numbers left so that when you re-index it just goes that when you re-index it just goes that when you re-index it just goes from n to n minus one and an n minus two dot but also um and i kind of talked about this in another thing uh or in the past um they're not independent of each other right so you could represent this x in terms of index so i think in that case um that could be done like for example left is equal to n minus index or something like this right maybe minus one but maybe it's off by one but so like that's the highest number you can go right uh and then you just pick a number from me i think that maybe that's fine uh oh at least i'll i think we have a correct algorithm but as i said and as i'm worried about is n cube so it may be a little bit too slow uh one other but maybe that's good enough because the other thing to notice is that n is less than 200 right meaning if n cube is too slow all we have to do is run this locally generate all the numbers and oh wait you can't because uh you're given an input sorry i was thinking of another thing but okay i think one thing i am gonna do is just write it out and then see you know if it's too slow we'll see if there's one for optimizations but um but yeah so okay so if s of index is equal to d then we have to be smaller than last rate so then that means when x is less than uh less it cannot be you know uh we have get count of index plus one um what's it uh i right yeah uh okay and let's do some basic things like total 0. uh um else we want it to be greater than last so it starts at last plus one to left maybe inclusive no because we're doing zero index so and should be okay so this may be off by one like i said but that's fine we're just kind of sketching it out for now and then just return total right i think this is correct ish so let's try but i was trying to think about uh a better optimization but uh yeah i guess we have to actually do a follow-up on this the first number in range of n uh let's see now we want well it goes to because the index doesn't isn't the index of the array but it's the index of s so we have you know also i forgot a base case whoops um yeah i let's kind of give a spin i know i didn't memorize but i just want to see if it at least gets it right for well something okay that's not great let's see if i get it right for just this case it is also possible that i'm off by one or something oh uh this should be plus one because it should be inclusive because wait should it should be zero and one because it has n plus one numbers okay yeah oops okay so at least we fix the d but we didn't fix the d i d okay how do i fix the d i d uh i know that i usually go more explanation but i'm still exploring right now so i will go over the dynamic programming part a little bit later because this one is maybe kind of you know tricky so and i'm not super confident about it because this isn't as standard as whatever um if you are looking to learn about dynamic programming uh try and use your problem first and also check out my videos on those because i usually do a better job explaining but this one i think maybe you're getting more of a of seeing my thought process and solving process versus like an explanation process uh maybe i'll do it later once i get there but nonetheless uh yeah so okay i think this is this right or am i off by one is this white or am i off by one okay that's too much so that's not it um okay let's try an obvious case of ddd and let's see if i could at least get one i should just like trace this okay so that's right and also maybe iii just in case that part of it is weird okay i mean i expect this to be wrong otherwise you know well kidding zero is a wrong in a weird way what was my last one is id which is zero trying to think whether this gives me like an off by one in a weird way because as we do that we're indexing right so because now when you take away the i and you go smaller all the numbers that were bigger should be okay huh okay but actually got a lot of things wrong like the last seems like my eye so okay so we did identify that the eyes are the issue so okay let's just so maybe that loop is wrong uh yeah i mean hopefully it's just off and off by one or something which is fine oh maybe that's why um it wasn't that i have to do this but this one because after we do the re-indexing last doesn't exist anymore re-indexing last doesn't exist anymore re-indexing last doesn't exist anymore so we don't have to do last plus one okay that makes sense uh i was just being a little bit careless dude let's won this i know i still have a print statement as well okay so this looks better i don't know if this is fast enough okay i mean so now i'm confident at least in the correctness but whether this is fast enough is another story so let's give it a submit i know that i usually don't do cash on these videos um but yeah okay um that's the thing right is that on lead code specifically 200 cube is 8 million and that's not always fast enough it always is depends on how they want to do it like for example if you just give me oh jesus i get so much spam phone calls and now it shows up on my uh my friend i need to turn on like do not disturb sorry friends that was kind of scary actually focus mode let's set that a little bit i don't know i also maybe just need to set this knot to be on my phone anyway uh sorry friends um what i was gonna say is that because right now i'm just playing guess how leeco likes it right and that's a game that's like been very tricky lately uh for me anyway because for example you have 83 test cases all right let's kind of one something like i don't let's just do this i think that should be fine this is 6. so 12 18 just make it 20 this is a hundred so 200 right let's run it real quick see how fast this is so this is three uh 15 milliseconds which is not fast not slow right but if you do like i don't know 200 test cases of these or something maybe not even 200 right just like 30 right 40 whatever right then you would time out and there's no way to kind of figure it out from just anything and the distribution of how many test cases depend on even there are test cases because they don't do the timing based on one test case they want the timing on all the test cases and combine the time uh yeah but okay that's why i wasn't super sure maybe if i did i would have gotten this one a little bit faster but the idea here um so cache maybe is a good time to talk about this anyway uh i do not so if you're new to um if you're new to dynamic programming and memorization and if you are studying for interviews do yourself in favor uh and don't use it um i mean look are you able to solve problems using cash yes can you explain why or how cash is implemented can you implement can you explain what's the complexity and it may surprise you uh can you explain you know all these other things about it right if the interviewer if i'm an interview and i saw this that's what i would ask you about it right i'm gonna make it really annoying for you to be honest um because my thing is that let's you know like from as an interviewer the goal of interviewing is not to see if you know you got a problem correct right if i wanted that we'll just give you an online assessment you know just hear it here's a link take a test right the pro the id you know the point of having an interviewer is so that they or in my case me um i can see how your problem solving skills are how your things and so forth right the first thing i would say to you maybe depending how i feel i suppose um if i see something like this um i mean actually i'm actually pretty you know liberal about these things to be honest i would just ask you like hey what's the complexity how can you prove the complexity etc right but i would also just think some people might like if you like one of your interviewer doesn't know what it is right because i actually know what this is so maybe i would be like hey you know hear the questions but if you get an interview who might not even know what this is then you have to explain how it works if you know at best right and you might not know at least they'll just make you do it another way anyway which is fine if you practice another way instead of just putting this everywhere which a lot of people have been doing uh so yeah so and i know that today because i wanted to focus on understanding um though it turned out easier than i expected so because i think i thought that i had to do some n square thing but that said yeah uh if you do want to watch like uh something that's more interviewing funny find another dynamic programming problem and check out uh my video on it because especially and this is unless it's done for a contest because you know that's my contest code is different from my interview code and my production code right makes sense uh and in that case then um you know i you'll see me explain a little bit better but in terms of complexity let's think about this so what can index be right index can be from 0 to n fair enough what's last lag could also be from 0 to n so yeah and how do you find the time complexity well time complexity is just equal to roughly speaking because there's some sometimes there's amortization but this time it's okay which is just total number of inputs times in uh time per input right this is like basically like you know let's say how long does it take to get there is to go to um total number of miles or kilometers for those of you in a country that uses reasonable si units times miles uh or you know hours miles per hour right wait what maybe i did this example wrong but anyway hours per mile but in this case this would you know you could do unit analysis and get rid of the maya uh the miles to get the total hours right that's basically the same ideas here is that the total number of inputs times the time per input is how you get this and total number of inputs and the idea behind memorization is that for every input the output is exactly the same right so yeah so you get the same input every time it'll always give you the same output so you just save it down to use it for later uh just like a cache outside of cs i guess but i don't know anyway uh total number of inputs is just n square and each input takes o of n time because that's the way that we did it um i think you can you optimize this i think so i think there is a way to actually get it down and that'll be kind of cool and the thing to notice there is that you're basically summing like let me i'll show you in a second but um i think there is a way to optimize this and it's maybe pretty cool uh but i could be also be wrong because that's probably so you're seeing larry at its expiration state so sometimes it's wrong sometimes it's right but yeah me think about it uh so total time is just all of n cubed right um and space is same thing total number of inputs but each input takes all of one space so total space is o of n q squared okay so that's pretty much all i have for this explanation but one thing that i would think about is if you implemented bottoms up for example right well if you implement the bottoms up because the idea here and i'm not going to write real code-ish and i'm not going to write real code-ish and i'm not going to write real code-ish or like you know as real as tight as i usually go but basically you have something like you know for each index you know you might write something like uh you know dp is you go to some two-dimensional array two-dimensional array two-dimensional array uh you know times n or something like that right someone like that and then you might have something like for index in range of n you know and then for um for last in range of index for no for last is you go to um n minus index i think because basically yeah something like that uh i mean this may be off by one like i said this is meant to be more pseudo kodi um and you should observe it at home if you're a few child you know but the idea here is that now we have another loop of for i in range of last or like you know based on if s of index doesn't go to d you know dot for now dot for i in range from last to n or something also dot right well uh and here the dot is this thing right so we have you know total we increment it by um dp of index minus one of some i or something like that i mean i could like i said i uh i'm doing a lot of hand wavy here just for teaching purposes um or like illustration purposes right um so basically if i were to but this is the optimization that i would be thinking about if i was um this would be the optimization i would be thinking about if i was um uh if i if the en and cube solution timed out then this is what i'd be thinking about i'm just trying to draw it out for you so give me a second uh basically for example you know you could think about it as having like a lot of cells you know uh this is bottoms up but we could actually do this tops down as well uh we'll see in a second all right dot right so basically but the idea here is that you know maybe i need a standard grid to paste onto here so i don't have to draw this every time but basically let's say you're here and depending on whether you get a d or an i you basically sum off here or off here right someone like that roughly speaking so what does that remind you of um for me what that reminds me of is prefix sum right so here this input takes off and time because of this loop right and of course it's not all of n it's a little bit faster than that but uh but the big o is all of n right but if we could reduce this to o of one using prefix sum then it becomes um then it becomes much you know then it becomes uh o of one and then this total time becomes n squared let me see if i can up solve this now since i do have more time so that's one benefit of doing this early is by doing it that way right um and sometimes for me it's hard to visualize these things until i type the code out a little bit use whatever you need for visualization you are you know how you make these process you are the sum of your experiences with practice you're able to do it better but once i wrote this out you know i could see oh huh i just you know do all these things right so here maybe the way that i can write is um you know get a sum of cap you know given some index um from okay so this is all right something like that basically i'm trying to you know here and also we want to catch this as well but here the way that you think about it is that if i is equal to zero do we return one no we just we return get count of uh index on i else i guess we're nothing else but we do get count of index of i plus get sum of count of index i minus one right so this is just prefix sum recursion um again i'm not going to go over the use of cash in this one because we're going with advanced topics um i do you already know how to do this um you can write this also a little bit differently but that's the same general idea right and then here in this case then now um and we maybe should have mod this as well but and then now in this case instead of writing this we have total plus get count or get some count from index plus one i right oh and then mod i guess but i mean you're only doing one so it should be already be modded but just for reading sake right so now we reduce this to one and you can kind of prove why this is all one um you know uh amortized or one because now we're not we're skipping the for loop right um and also some you know some stuff about prefix and we're using substates but yeah and now we reduce this to n squared of course you want to do the same to here before i mean okay so we didn't reduce it n square yet because we have to do it here and here if you have experience of prefix sum you're probably already ahead of what i'm about to say if you haven't then the idea is just you get the sum of count uh plus one we get it to left and again maybe this is off by one but that's going to be the general idea uh left minus one because we want to do it inclusive minus get sum of count of index plus one um we come from last so we want to subtract from last minus one um and this last is zero yeah um okay so if i is less than zero then we return zero just to make it easier so i think this is roughly correct maybe i'm off by something here but now this is how we get it to um okay well mistakes were made how am i off by so much maybe i subtract this one okay uh well no i'm just doing the ddd right yeah i missed this one let me double check all right let's start with something more basic the idea should be right or maybe not maybe i'm making a four on myself but we'll see how they even how does 35 even come up or d is three oh it's is it because i did it this way um oh no let's see well uh let me think about this for a second so i'm surprised that this actually gets to work with d but okay so it goes okay zero one okay maybe just point it out well that's the idea that i would have maybe my implementation's a little bit off clearly well it's not it's definitely not very right but uh from zero is one and then zero one is three so it's not giving me zero for an impossible case so it's overcounting something so for zero this should be zero and this should be one so it's adding one to some stuff um why is that okay so if this is zero oh why do i have i here that's well that's at least something it should be last and what was the oh loop that was just a bad typo i think but listen my i'm trying to think where there's now minus one yeah i think this is minus one uh okay i mean it's easy to get these right but at least but it's embarrassing to get those wrong so well that's just a typo though okay cool wow um yeah so before it took like we i didn't see the timing but before when we had the n-cube algorithm it took 300 the n-cube algorithm it took 300 the n-cube algorithm it took 300 milliseconds so now you could see that we reduced it to n squared um let's see how fast that one's cool wow i mean i'm pretty happy about this uh i mean i think this is probably as fast as you can get it at least with this style but i'm happy that we reduced n cubed and square i think this is also one of those things that uh leeco is kind of dubious about because i feel like if this was in the contest today uh maybe this is just my commentary if this was in the contest today um if this is on the contest today like i feel like nq might not be fast enough ex in python but it may be fast enough in java or something right uh and n is a little bit too slow or too like you have to do n square in python but not in other languages well um i would also say that if and i get this comments from time to time about this percentile thing um i wouldn't worry about it to be honest in general um especially in this case we use stuff like cash and we don't get top down instead of bottoms up um that's going to be you know slower just from that but i wouldn't worry that much about it um cool uh that's pretty much all i have i think i explained this pretty okay um this is obviously live and a little bit tricky but especially if you have to make this optimization but hopefully this is you know somewhat new and instructive uh in terms of finding this new hotness because this is something that i don't even i on my skill level whether you know however you want to think about it uh you know it's not an optimization i make it a lot so yeah but this is the progression on how you would think about it so cool um yeah uh that's what i have for the bonus question uh stay good stay healthy take your mental health i'll see y'all later and take care let me know in the comments if you like these bonus questions bye-bye
Valid Permutations for DI Sequence
implement-rand10-using-rand7
You are given a string `s` of length `n` where `s[i]` is either: * `'D'` means decreasing, or * `'I'` means increasing. A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` is called a **valid permutation** if for all valid `i`: * If `s[i] == 'D'`, then `perm[i] > perm[i + 1]`, and * If `s[i] == 'I'`, then `perm[i] < perm[i + 1]`. Return _the number of **valid permutations**_ `perm`. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "DID " **Output:** 5 **Explanation:** The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) **Example 2:** **Input:** s = "D " **Output:** 1 **Constraints:** * `n == s.length` * `1 <= n <= 200` * `s[i]` is either `'I'` or `'D'`.
null
Math,Rejection Sampling,Randomized,Probability and Statistics
Medium
null
1,425
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screen cats of the contest how did you do let me know you do hit the like button either subscribe button and here we go q for constraint subset-sum here we go q for constraint subset-sum here we go q for constraint subset-sum yeah so this one I had a little bit trouble with or a lot of trouble with high refresh and someone already finished which is yeah it's pretty impressive but we had this one I was just having well I just didn't well I mean here I think I understand what I had to do but I just wanted to make sure and I didn't would at first I was gonna do a dynamic programming to be honest that's why you sort of spaces I was gonna write import func tools or from input and thumb from totem for ru cash and I was like go away K is actually 10 to the 5th so you can't do n square so dynamic programming for the N square it also might have been easy to write but then now I'm trying to think about like okay there must be a greedy type praying and I was also trying to figure out what a subset means because subset actually means a little bit weird the way that they have in here because usually subset does not mean leaving the remaining elements in there already no order usually I don't know maybe that just made my reading thing better right away so I do we double check that one and understand it again we've only spent a couple of minutes here just reading this one and I'm just thinking about how to do it I think at this point I start to have an idea of how to do it however I was just trying to figure out the data the right data structure to it and they said what I wanted to do was a sort of a rolling window type thing yeah and at this point I yeah this deep in thought about how to sow this at all and I don't for now maybe I'm not into the solution yet because I think what I was trying to do now is just thinking about like how to prove it correctly like I wasn't sure like I was trying to convince myself that the rowing window makes sense and then and this is you know the time that you spent here it is time that it's time that if you had practice enough you bring not have to spend and that's you know or like me not practice now but you also if you have done similar forms I maybe more recently than you have to do this because then you will display Gaia's you know I did this similar file for ever for me I was a little bit positive of these kind of going window problems lately and I was just trying to prove to myself that this sort of greedy makes sense and I think actually at this point it's kind of actually I had an interesting God is that I just thought because I was still thinking about dynamic programming and the dynamic programming is there a couple of ways to write this dynamic programming but one way that I was thinking about at this point because initially I was just like oh yeah just dynam you know why the dynamic program on N and K and then you could do this sweeping through the N and the K and if we can square and so forth and in the second way that you could do it is that actually looking at each index you can look at it as a sort of a longest path in the tag and from that yours is still n times K so it's no longer well I mean it's still n times K because you have to do a look back on the previous K so that was my dog process about it and then from and I still know that n times K is not gonna be fast enough obviously for 10 to the fifth and then from here I think I was beginning to think well when you write out that dynamic programming what are you doing right well you're just finding the max of the last K items and then getting the max of that and then added to the current element right so from that I was trying to figure out like okay that makes sense so actually what you really want it is a sort of a sliding window so that's how I did the deduction or that's how I deduced the answer I guess I don't know now I feel like I'm Sherlock Holmes but that's how I arrived at this solution well it was like okay and then from that it was a little bit implementation details so I'm even about garnet now so I'm trying to be a little bit careful about it I was trying to look up so one thing that is unfamiliar for me an API was dead I was insured that uh like given an ordered set or like a sets ordered in Python and the answer is apparently no I don't think so in the way that I just wanted to maybe get the main item from or in this case the max item but yeah the max item oh yeah so yeah what I wanted to do was give me a party queue or giving it a bag of stuff or a set get the max item from that set so that you kind of argue insert stuff and when you process a number and you remove something that you've seen before so that's kind of idea and then instead I did things from a party queue because oh well because I was like huh I don't think sent us this and I spent too much time googling when I knew I was like okay I could just do in heap I mean you lose that in the setup and lock area you get n log n but that's okay like you know especially for a decimal and I haven't been keeping about so there's some bustiness there about their actual exact syntax and I think so here I misunderstood to prom I thought you had to choose the first element so that's kind of that leads to the yeah I mean I'm still thinking if you just try to I think I'm still having a little doubt I'm thinking about how to exactly implement this and that again is something that can be practiced and if I was more practice on this farm then I would have done it but that's okay I mean you know contests good practice too so yeah but now I just keep track up to index and we're just making sure that so my idea here was that it's this way of doing it so I was trying to figure out a way to remove it like okay like what we talked about earlier there's a bag and we're trying to remove elements in the from the middle as they kind of drop out of your growing window and I was like okay item there's no data structure to it and then what that reminded me was of tight rows album so one implementation time is rounding them dice true it's an album is that uh well you know when you relax a node you take yeah you remove we move that note from the dice to a heap right I was like well the hack around that one is that instead of getting really like we you do a real ugly type thing which is you could prove that log years you know since years at most we squares it's two times whatever anyway not getting too much in the texture for the idea of that is that you only get slightly worse performance but here so what I did instead was that yeah instead of getting an end lock a performance I get a we and like and performance and that's the way I did it but I misunderstood this problem a little bit in terms of different boundary cases I knew when you think about it that much I thought I was washing a little bit probably mentally I'm about 16 minutes in now if I had finished now and got it correctly I would have been still top 20 so that would have been really good but I'm I did try to put I so I did have an issues here because I forgot for a second that python is Maxie or python is min-heap instead of max-heap so that's min-heap instead of max-heap so that's min-heap instead of max-heap so that's where a lot of my issues that uh that you're seeing is two right now so that you know I mean I knew that but I think I just like and I think some of that was that I was a little bit like trying to wash it a little bit and from that out I was like I distinctly remember that in beginning I was like that just in pipeline heaps are no different so I knew that because I've done it enough but I think in the moment I was watching a little bit too much and then I did in and then yeah now I'm looking at it go I'm like huh why does that not make sense why is it ticking to zero instead of you know whatever yeah whatever it is yeah so now I was like okay well I was like still just doing that right so yeah I had to index and the previous index swapped right when and it was I was like okay let's go this would have been about 19 minutes in I still good for the top 25 if I had got it right but I got wrong in tops I got really sad and then took a look at this and I was like go so I took the wrong lesson from this which is no set what I thought was that you need the first element from the previous thing but I was like I actually don't need I don't know I that line also was a little problematic but in that interpretation so I was just a little bug you know in a weird way yeah so now I set it to the first element because I just misunderstood it but after testing it yeah we should try to think oh so what I died at this time and I still misunderstood it but what I thought was that the first element has to be K distant from the beginning of the matrix or from the beginning of the array which I don't know why I got that now looking back but at the time I was like oh that makes sense why not so that's why I will I created this like said no value from the beginning so that it fixes that case like yeah I just misunderstood it I really thought that it was just that you had to get something from beginning otherwise I have solved it another way where these I got tested a little bit but that's the tricky part about contests sometimes instead you know and I might submit I was I got this I thought it was sad I looked at this example I was like huh let me try to understand this that's one the code that's linked back to debug and I was like oh that is a lot of negative numbers how do you get 16,000 and yeah and I eventually to come to my senses and that found out data or figured it out that you can actually start from any index and then I rewrote it was a little bit sad because like that was ten minutes of penalty like the time spent was like okay like I did actually just didn't I just have to walk while I'm kind of but the ten-minute while I'm kind of but the ten-minute while I'm kind of but the ten-minute penalty kind of hurts I wish that I think if I had gone like the first one answer was this one then I would have just gone in then I would have understood it and then you have saved me five minutes a decent penalty so it's kind of a little unfortunate but sometimes you know like to do well in a car to do consistently okay on the concert contest you just have to be consistent you have to be you know have salad and you have to be you know but to do really well like something at least for me well needs a little bit of luck and maybe today I just didn't have that on my side as much but like I said if I misread a couple things and kind of things couple of things wrong and I'm still 110 you know I'm not gonna complain that much about it but uh but my only kind of complaint is that a waste opportunity because on the first three forms I started in eight minutes which is fast for me and I just got an arched maybe like even a decent time maybe not average like actually even like the current time if I got the current time but without the to penalties I would have been tough 50 or something like that wait so sometimes you know it is what it is but yeah right how you hang out gadelle a be ask questions and I'll see ya well yeah that Larry will see you minute this one took about five minutes to read in general catches really quickly what mad props to them but yeah but I think I well I mean the 23 minutes was okay like I don't feel that bad about it's a problem that I just feel like I haven't done before so it's okay or like I've done I had an idea they took a little bit of kind of formulating it and that's okay well you could you know not gonna be amazing every time well I'm not gonna be amazing every time that's okay but yeah what did I get well one of them was that you can start the way anywhere so he didn't have to start from the point zero but yeah I don't know hmm I forget what my other let me check my other submissions and then I'll go will my explanations bit of it but my second solution yeah well it was my first one yeah now the first one was me being dumb on no this was actually this end up being right it's just that I think I just misunderstood I mean this was still warm with this line is right it's just that I think well at this point when I wanna go fix this I misunderstood what it needed to be fixed which was there everything with an example case was now like something was this case where oh yeah where you don't start from the first so the issue that I thought I was having was that you don't start from the became a like you could do to offset from the beginning and then I fixed it the wrong way so I like I've say five minutes without not being dumb still three minutes I'm not gonna tell you but oh yeah the idea here is actually a sort of glowing window with you well a sliding window even though it's not intuitive I was thinking a little bit about a ways to go and go about a sliding window but the idea is that you just keep track of all the sum of all the previous case of this so and then you yeah so you keep the and you could think about is keeping a bag of you will of the last case of the sums and then actually this one I could buy just to max up did if I just in this it were private well I had to do some like negative things around it but something like that maybe because he piss max but then that would been good enough but uh but I what I think I just misread that one a little bit or at least I misunderstood two constraints a little bit yeah let me think about our window yeah what I was to say about it they have been punched so that's what my do de Partie to you and I did I was thinking of trying to figure a way to almost similar to Dykstra if you think about Dijkstra algorithm where you know there's stuff in the priority queue or a bag or something like that and then you remove it and then you know the quality kid would automatically jiggle itself but instead I did this other thing where and it's no economy and lock-in and I think that's their big yeah and again you don't get it and lock a but that's okay and he's for this problem I think I had got it right but the idea is that we take the max element that's in the bag and as long as that at max element dirt and then we keep track of the index as well as long as the Delta index is smaller than K then we you know play around with it otherwise you just keep on popping until that's the case and I do want to open weird thing because in Python heaps maxed sorted by Max so that's why I have something like real negatives here which also threw me off a little bit cuz I always forget
Constrained Subsequence Sum
weather-type-in-each-country
Given an integer array `nums` and an integer `k`, return the maximum sum of a **non-empty** subsequence of that array such that for every two **consecutive** integers in the subsequence, `nums[i]` and `nums[j]`, where `i < j`, the condition `j - i <= k` is satisfied. A _subsequence_ of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order. **Example 1:** **Input:** nums = \[10,2,-10,5,20\], k = 2 **Output:** 37 **Explanation:** The subsequence is \[10, 2, 5, 20\]. **Example 2:** **Input:** nums = \[-1,-2,-3\], k = 1 **Output:** -1 **Explanation:** The subsequence must be non-empty, so we choose the largest number. **Example 3:** **Input:** nums = \[10,-2,-10,-5,20\], k = 2 **Output:** 23 **Explanation:** The subsequence is \[10, -2, -5, 20\]. **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Database
Easy
null
1,701
hello everyone let's look at lead code question 17001 average weight time so in this question we're given a two-dimensional array called customers two-dimensional array called customers two-dimensional array called customers and the individual values of customers at I is the arrival and time the arrival time of the I customers are sorted in non-decreasing order and the time is the non-decreasing order and the time is the non-decreasing order and the time is the time needed to prepare the order of the customer note that we're given only one Chef to complete every order so there must be an overlap between waiting times and starting times of every customer's order we need to return the average waiting time of all the customers so how do we do this well before we look at the examples let's look at the constraints there must be at least one customer and one arrival time and preparation time for each customer array and the arrival time of One customer must be less than or equal to the arrival of the next okay so let's look at the examples okay so as provided in the first example we have the two-dimensional array customers where two-dimensional array customers where two-dimensional array customers where each attribute of customers contains the start arrival and the time required to prepare the customer's order so the first customer is starting at time one and it takes two to prepare his meal so the chef will not be available until time three and so the next customer arrives at two but we'll have to wait an additional one before his order is being prepared because there's an overlap and there's only one Chef the five is still the same it takes five to prepare plus the one there's a total of six for wait time of the second customer and if you look at the last customer the same here applies but this customer arrives at Time 4 and we'll have to wait 4 before the chef is available because the chef must prepare this large order of five and is available at time 8 the three for the time is the preparation time and it's the same so it's three plus the additional four so customer number three will have to wait seven and now to calculate the total weight time we have 2 + 6 + 7 this is 15 weight time we have 2 + 6 + 7 this is 15 weight time we have 2 + 6 + 7 this is 15 and since there were three customers the average wage time is five now in this example the same applies the customer number one starts at 5 and it takes two to prepare however the second customer also comes in at time five and must wait two before the chef is available and then the preparation was four so 4 + 2 is 6 six preparation was four so 4 + 2 is 6 six preparation was four so 4 + 2 is 6 six for the weight time of customer 2 and the Third customer arrives at time 10 and the chef is not available until time 11: so this customer Waits an additional 11: so this customer Waits an additional 11: so this customer Waits an additional one so a total of four and finally we have an idol customer here that arrives much later with no one else at the restaurant and it just takes one to finish his order so then the total weight time would be 2 + 6 + 4 + 1 average weight would be 2 + 6 + 4 + 1 average weight would be 2 + 6 + 4 + 1 average weight time is 13 divided by the total customers 4 that is 3.25 so first we initialize the 3.25 so first we initialize the 3.25 so first we initialize the variables total weight and current weight to zero next we can Loop through the customers and each customer is represented by their arrival time and their prep time the current weight is updated to the maximum of arrival time and the current weight this checks if the chef is already busy with the customer arrives so if a customer has arrived and the chef is busy then the current weight will not be arrival time but current weight itself however if the chef is not busy then the arrival time will be the current weight because the chef will immediately start working on your uh order and the starting value of your weight will be this current weight so then we can update the current weight value to be current weight plus prep time and uh it's incremented by prep time of the current customer so that the time they need to wait and the prep time is combined then the weight time is calculated by subtracting the arrival time from the current weight this gives us the total weight time of One customer and then we can accumulate it to the total weight once we have looped through every customer we can calculate the total weight divided by the length of customers to give us the average and as you can see this solution works so the time complexity is O of n where n is the length of the input list customers and this is because the code involves a single Loop and iterates through each customer exactly once and it's performing constant amount of work the space complexity is O of one besides the input list customers only a fixed number of integer variables are used for calculations and they don't depend on the size of the input and the scale with the input so regardless of the number of customers the space used is always constant and that's it for this video thank you and see you next time
Average Waiting Time
remove-max-number-of-edges-to-keep-graph-fully-traversable
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**. Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted. **Example 1:** **Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\] **Output:** 5.00000 **Explanation:** 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. **Example 2:** **Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\] **Output:** 3.25000 **Explanation:** 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. **Constraints:** * `1 <= customers.length <= 105` * `1 <= arrivali, timei <= 104` * `arrivali <= arrivali+1`
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use Type 3 edges first, and connect the still isolated ones using other edges.
Union Find,Graph
Hard
null
13
hey everyone welcome back and let's write some more neat code today so today let's solve the problem roman 2 integer this is an easy problem but i would say the difficult part about this problem is really trying to understand the problem itself and the requirements that they want even though it's easy i think it's a pretty good problem too you know to practice your problem solving skills so as you may know roman numerals are represented by seven different symbols they give us each symbol and the mapping value and so what i'm just going to do is it's a pretty long explanation i'm going to summarize it to you in a few sentences so we have this mapping of symbols to values we're also told that roman numerals are typically written from left to right in the largest to smallest order meaning the largest symbol will go first and then the smaller symbol will go next so if we wanted to write 1000 uh 10 or 1011 we would get the thousand first which is the biggest one we put in m and then we get the tens place which is next we'd get a x and then the one would be the i so then we'd write it like this right from largest to smallest and that's how they're typically written but there's a special case where you might put the smaller one before the larger one for example what happens if we do this i and then m we know m is a thousand we know i is one so what does this mean is this a thousand and one no because remember they're supposed to be from largest to smallest so what happens if you do put a smaller one before the larger one well you can only do this by adding a single smaller one before the larger one but basically when you put the smaller one first you're basically subtracting the value of the smaller one so what we're really saying here is this i is gonna be negative so it corresponds to a one it's going to be a negative one the m is still gonna be positive uh so it's a thousand so we get a thousand minus one so really this value represents 999. now you're probably thinking what happens if we put two i's before the m is that gonna be 998 nope because you can't put multiple smaller values before a larger value if we wanted to write 998 we would have to do it differently i think you know this written from left to right would i think be 998 or not left from right i think i did it backwards so this would go first uh then this would go next and then this would go next so but that's not really important if you care you can you know read that it's not too important just letting you know that those are the main rules and i think that's pretty much it once you know this idea that okay if a smaller value goes before a larger one and we can only have a single one of those happening then we're going to be subtracting that otherwise we're going to be reading from largest to smallest then this problem becomes very straightforward literally all you have to do is read the input string so actually i took this and rewrote it in the correct way so this value equals 998 so how would we determine that well because that's what the problem is about we're given a string like this one a roman string we want to know what value does it actually map to right so how do we do that let's let me show you so we're gonna read character by character right we're gonna see okay is this character uh followed by a larger character because if the next character is bigger than this one that means this value is going to be negative this one value is going to be subtracted right because normally it's supposed to be from largest smallest we get the value of this one it's not a thousand it's a hundred right what's the next value it's m its value is a thousand right so that is the case that means this hundred is going to be negative so far we have minus a hundred to our total value then we go to the next value right it's a thousand what's the value that comes after it's only 10 so that means this value is actually going to be added because the larger value comes before the smaller value so we are going to add this value so we're going to say plus 1000. so far we're at 900. next we go to x it's followed by a character that's greater than this is 100 this is 10 so this 10 is going to be negative so minus 10 puts us at 890. then we get to this value and it is a hundred the next value is just five so the larger value is actually going to be added so we're going to add a hundred to this puts us at 990. uh then from here on i'll just it's pretty straightforward because this is five this is one so since this is from largest to smallest right it's in decreasing order that means all of these are going to be added uh obviously if we have two consecutive ones both of the values are equal right so if they're equal of course they are going to be added together they're going to be positive they're going to be contributing to the result in a positive way so 5 plus 3 that's 8. so if we add 8 to this result we get 998 which is exactly what we wanted i screwed up this 8 i think but hopefully you get the idea so it's as simple as that we're just going to be reading through the string and potentially comparing adjacent values and the way we're going to you know get these values really easily map the symbol to the value the easiest way to do that is just a hash map so that's what i'm going to be doing overall time complexity is just going to be big o of n because we can just scan through the entire input string we're not really needing any extra memory the memory is going to be big o of one yes we are going to be needing a hash map but that hash map is just going to have seven values in it right it's not really going to be really big or anything so it's definitely not big o of n so now let me show you how trivial the code actually is once you understand the problem so you can see that i basically summarized the problem in two comments up above this is basically what we're going to be doing basically what i showed you also we have a hash map i didn't want to show you like i don't want to waste your time typing it all out so i just kind of uh wrote it beforehand so we're going to be maintaining a result initially it's going to be 0 and then we're just going to start iterating through the entire input string right so in python you can just iterate through whatever the length happens to be so this i is going to be our index and remember so the first thing we're going to check is are we going to be subtracting this value so how can we know if we're going to be subtracting the value we're going to check okay first of all does it have a character that actually comes after it because if it does have a character that comes after it then we'll actually compare the values so first we'll check if i plus 1 is in bounds so that'll make sure that we don't go out of bounds so if that's the case then we're gonna check okay what's the value of the character at index i we can get that from our map which is called roman so roman what are we gonna pass in the key value which is the character s the character at index i and then we're going to check is this actually smaller than the next character we can just get that simply with roman s of i plus one so if it's actually smaller right that's wrong that's not supposed to happen remember it's supposed to be in decreasing order but if it is in increasing order that means that the smaller value has to be subtracted so this value has to be subtracted from the result so that's exactly what we're going to do subtract that from the result if this is the case yes we subtract otherwise the else case is the simple case where yes we're just going to add the value instead right we're going to add roman whatever the value is of this particular character so that's all we need to do that's the entire code he had just a simple if else statement with a hash map and a for loop so it's definitely a good fundamental problem to understand your basics so with that we can just go ahead and return the result and i'll submit it to make sure that it works and yes it does this time it was 48 milliseconds uh greater than 65 percent but by our elite code is pretty random with these run times so i wouldn't honestly pay too much attention to these i ran it a couple seconds ago and it was 40 milliseconds so it's really not that big of a deal hopefully this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, `2` is written as `II` in Roman numeral, just two ones added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. **Example 1:** **Input:** s = "III " **Output:** 3 **Explanation:** III = 3. **Example 2:** **Input:** s = "LVIII " **Output:** 58 **Explanation:** L = 50, V= 5, III = 3. **Example 3:** **Input:** s = "MCMXCIV " **Output:** 1994 **Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. **Constraints:** * `1 <= s.length <= 15` * `s` contains only the characters `('I', 'V', 'X', 'L', 'C', 'D', 'M')`. * It is **guaranteed** that `s` is a valid roman numeral in the range `[1, 3999]`.
Problem is simpler to solve by working the string from back to front and using a map.
Hash Table,Math,String
Easy
12
342
hey guys welcome to code circle and today we'll be covering the lead code problem number 342 power of four it is marked as an easy and it is quite a light problem okay so first of all i'll read out the problem statement here which says that given an integer of a sign 32 bits write a function to check whether it is a power of 4 okay so first of all the main thing to notice here is that we are given a signed 32 bits number so this basically means that the largest number that can be in this question the test case that can be formed is offer 32-bit number so can be formed is offer 32-bit number so can be formed is offer 32-bit number so our range is 32-bit our range is 32-bit our range is 32-bit now we have to write a function and check whether it is a power of 4 or not okay so now how to do that now there is a there are a lot of ways to do this thing but one of the best ways uh or basically one of the easiest ways i will say is through bit manipulation because you know it is very intuitive and it is easy to understand okay so let's begin our tutorial and i'll first of all explain the logic behind the bit manipulation and then i'll explain how like in a very short amount of code you can you know solve this question okay so now uh let's first talk about our intuition okay the intuition basically says that if we look at the first 3 powers of 4 let them be 4 to the power of 0 4 to the power of 1 and 4 to the power of 2 so 4 to the power of 0 is 1 4 to the power of 1 is 4 and 4 to the power of 2 is 16. here i have written the binary representations of 1 4 and 16 b's which are basically the first 3 powers of 4. now if you can notice the pattern somehow here it is that like each power 4 is basically at the even position is that like if we consider like an array which goes from 0 to 31 basically storing all the 32 bits inside it then every zero with every uh even index starting from the zero with index it cont like it is basically the power of four like if they are any of your if like any of your even bit is set then it is basically a power of four so if you at any point find that your uh your like even bet even bit is set and you like each time you find that even bit is set you just you know check with the number that is given to us in the question now if it is uh like if it is set and if the number is equal to that number then we definitely know that okay this number is basically a power of four because power force only exists in the even position and they are only like there is there will be one set bit and it will be in the even positions okay cool so now coming back to our uh let's see the code for this okay now first of all what i've done here is i will go through since we have a 32-bit number here so since we have a 32-bit number here so since we have a 32-bit number here so basically this for loop is basically checking for all the even bits i will check all the even bits in our 32 bits number like whether they are you know set or not if any of the bit is set basically means that whether you know that bit is 0 or not that bit is one or not okay so what i've done here is since i want to go through and you know loop through only the even bits i have incremented this by two so my loop will basically i will have value 0 2 4 6 8 10 12 like that okay and then for each even bit i will check that uh that if okay let me first explain what left shift basically means some of you might not know what left shift is so left shift is nothing but as you can see here 1 left shift i is written it is nothing other than 2 to the power of i like in the first case scenario we will have 1 left shift 0 like i s initial value will be 0 so what is 2 to the power of 0 it is 1 right so i'm going to check here that so if i if we left it abc even if we left shift 1 by 0 then basically we're not moving it so 1 is 1 so as you can see so basically left shift is 2 to the power of i we are basically just shifting our number like let's say for example in the initially 0 will be r1 will be something like this if i left shifted by 2 then what it basically means is that i am basically adding two zeros and i am removing two zeros from the left side adding two zeros on the right and removing two zeros from the left side it is just a way to like you know imagine this initially our one was here and now i have just shifted it two times so as you can see this is now four and now if it if i shift it uh two more times then it will become 16. so that is how our logic is working so now if at any point if my ix bit is set which is which will be tell through this if my ith bit is set and that is equal to the number then it means that it is a power four and i will uh you know straight away return true now if my entire group learns runs through and still i have not found the power of foo then it basically means that i have not found a power of 4 because as soon as i have found find the power of 4 i will return it i will return true and i will you know my question is but if i have not found it then i basically return false so if we run this code now it will be as you can see this is like 100 faster than like all of the other submissions and like it is such a basic concept and through such an easy concept a question like this can be solved so yeah thanks guys for watching uh stay tuned for more videos like this if you have any specific questions you want me to solve one lead code please just write in the comment section and please do like and subscribe thanks
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
5
hey what's up guys in this video we're going to solve this coding interview problem longest palindromic substring given a string is written the longest palindromic substring in s what is a palindrome a string is a palindrome when it reads the same backward as forward for this string aba these strings read the same backward as forward a b a and a b a so this string is a palindrome string for this string is not read the same backward as forward a b and backwards ba so they are not same so this string is not a palindrome all right guys this is the definition of palindrome now let's take some example if you're given string equals to b a d you have to find the longest palindromic substring so in this string this is longest palindromic substring or we can say aba is the longest palindromic substring these two strings contains the same amount of character we can written any of them so our answer could be b a b or our answer could be a b a all right for this given input we should written bab or aba if you're given s equals to c b d in this sketch this is the longest palindromic substring bb reads same forward as it's backward all right so for this given input you have to written bb if you're given s equals to a we have only one character and this character reads the same forward as backward so for this given input you have to written a now how we can find the longest palinderic substring we can solve this problem using managers algorithm that takes linear time complexity but managers algorithm extremely difficult and that's not expected in an interview settings in this video we're going to solve this problem by expanding around center all right let's see how we can solve it now i'm going to go through the intuition to this problem for second understanding let's assume we're given string equals to b a d first our goal is to find the length the l is max of length 1 and length 2. length 1 equals to length of substituting when i is the center here substrings means palindromic substrings length 1 when i is the center length 2 when i plus 1 is the center for each iteration we have 2 center i and i plus 1 all right for first iteration i point to this character b we have start and end and this is our center so the length of our longest pandemic substring at this center is 1 because we can't expand to the center on the left we have no character so length of longest palindering substring at the center is one and here we have start and end with start and end we can return the longest palindromic substring initially we have this start and end equals to zero so initially our longest palindering substituting is this first character and here we have this if condition will find out the perfect start and end for a palindromic substitute our next center is this okay when we have the center our start is pointing to this character b and end is pointing to this character a and we see that start and end are not equal because they're different character so the length at this center of longest palinderic substitute is zero so max of one and zero is one all right if we have the length is one the start and ends remain the same you can calculate that using this code for next iteration i is pointing to this character a we have start and end and this is our center at the center we can expand around it we have on the left b and on the right b so we expanded it and we can't expand anymore so here the length of longest pandemic substring is three then our next center is this okay when we have this center we have start equals to a and equals to b and they are not equal so the length of longest palinderic something at the center i plus one is zero so max of three and zero is three in this case start and end will be changed start will be 0 and end will be 2 you can calculate using this formula now for next iteration i will point to this character b and this is our center in this sketch and we can expand around this center if we expand it start will be shifted to this character a and it will be shifted to this character a all right and we see that they're equal if we expand further we see b and d that not a match so we can't expand it and the longest palinderic substring at the center i is three then our next center is this and at the center the longest palindering substring is zero because b and a are not the same and the maximum of three and zero is three in the sketch the start and end will be changed start age 1 0 1 the index and end is 3 and you're going to calculate using this formula then for next iteration i will point right here and this is our center in this case the longest valentine's up string is one if we expand we see startle point here and in dual point here and they are not equal so we cannot expand anymore the length is one then the next center is this and here we have the length of longest valentine's substituting is zero all right the max of len one and len two that means one and zero is one length is not greater than eight minus start so it will not change the start and end pointer then for next iteration i will point right here at d and the longest polynomial substituting here is one and we can't expand start and end at this center because on the right we have no character then our center will be this and right here we have no element on the right side so the length of longest ponytail substring at this center is zero so here one for at i and for at i plus one is zero so max of zero and one is 1 and that is not satisfies this condition so start and end will not be changed here and our longest palindering substring is this from 1 to 3 and that will return to our function this is my solution to this problem for the worst case scenario it will take speed of n square time complexity and it will takes constant space complexity since we're not using any additional speech this is my solution to this problem i'm not going to go through the code i'm going to leave the code for you and i'll attached the code in this video check that out thanks for watching this video i will see you in the next video
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
145
hello friends welcome to joy of life so today we are going to look at another medium level problem from lead code the problem number is 145 it says binary tree post order traversal so previously we have done videos on pre-order in order and level order as pre-order in order and level order as pre-order in order and level order as well i'll leave a link at the description and this is a continuation to it so we are going to cover all the traversal algorithm before we move on to the other problems so it says given the root of a binary tree return the post order traversal of it nodes values okay so here are some examples given and i guess they have also given us a constraint over here that it will be off between the range 0 to 100 and we'll have minus 100 200 values in the node though it doesn't matter to us what values it contains so it says that we should do it in an iterative way and we should not use the recursion and call stack are the same before we move any further let's understand what is a post order traversal so in post order traversal what happened is we start going towards our left as much as we could and once it is done then we start going towards our right and once we have done exploration of both left and right subtree we are going to process the node or we will call that will process the root right so in this example where we have a node like 1 2 and 3 will start from the root which is 1 and we'll try going its left there is nothing to its left so we'll go to its right so as soon as we came to the right it becomes our current node and we try to go to our left and from left we cannot go any further left or any further right so we'll process it means our processing includes just printing the value of it so we'll print a three and we are done with the node three right we come back to two so left of 2 is done we'll try going to its right but there is nothing to the right so right is also done we'll consider it done and we are going to process this node so processing means we are going to print the value once again and then we come back to 1 for 1 left and right both is done so what we are going to do is we are going to process the node so we are going to print the value again so we will end up having a result like three two and a one so here also you can see in the example that we have the similar result three two and one so yeah we'll look into the solution in much more details but as i always recommend uh to give it a try yourself before you look at the solution so this is once again a very important traversal algorithm that everybody should need to know and we will head over to the board and check out the solution don't miss out the solution understand all of them i would highly recommend that you go through all the videos for the traversal in this channel and it would be of great use for you so let's move over to the board and let's check out the solution so i've taken a tree over here this is the same tree that we have used earlier as well for the in order and the pre-order example and we are going to pre-order example and we are going to pre-order example and we are going to use the same tree for the post order what happens in a post order traversal is we try to go left as much left as possible and then once we are done with the left then we try to go to the right subtree so this is the right part and then we process the node or visit the node whatever you say so processing includes printing the node for us in this case and in the code it will be to add it to the array list right so we are going to see how this entire algorithm works in recursion and we are going to build a call stack and see how it all comes into effect so i have taken a call stack over here and we are going to see how we are going to use this call stack to come up with the answer so we will take the current context over here the current is nothing but our root node in the beginning so we will have one as our current or which is the root right so what do we do from here we go towards our left so going to the left means we are talking about this node 2 over here so we'll go to the we'll call the same function with the left child so what will happen is the current function which is a 1 will get pushed into the call stack so don't think that we are pushing the value one but the instance of this method is getting pushed inside it and what happens is one is replaced with a two over here so two again tries to go towards this left that's the first statement of our code so what happens is 2 gets pushed inside the stack over here and 4 comes into current for since 4 doesn't have a left or the right so these statement will not be applicable for it because in the real code we'll have a null check before calling these functions right so we are going to process this node for so what does processing means we are for us the processing means we are just printing the value so we are going to print four so the instance for the note 4 is done with all the three statements statement over here so note 4 is completely done right it has tried its left right and it has print printed or visited it um node and so it's going to go out and 2 will pop back out from the call stack since it's on the top so 2 went into inside the call stack because of this line the first line we try to explore the left so now we'll try to explore the right once again so in the right we have a five so two will get pushed again inside the call stack over here and what will happen is five will come into the current right so again five does not have a left and right so these statements are not applicable so five is going to get processed so processing once again means printing the node over here so 5 is completely done so what will happen is 2 will pop out again and once we pop out 2 we unlike the first time it went for this line this time it went for this line right so the only statement remaining for two is to visit the node and in our case it is just about printing the node so we are going to print two right and then we are going to pop out one from the stack so for one we saw that the left this statement is completed this is still pending right so one will now call its right child which is a 3 and put himself back into the stack right now 3 will try to go to its left there is no left so this statement will not be executed but it has a right so what will happen is three will get pushed inside the stack over here and three will be replaced by the six so for six what we see that it does not have a left and the right so it will just go ahead and process it itself so it will print its value which is a six so six is completely done so what will happen is three will pop out from the stack once again so three has completed both this statement the only thing remaining is the visit node so three is going to print itself and three is completed and now one will get popped out again and for similarly for one also we have seen that these two statement has been completed so only thing pending was to print the value so we are going to go ahead and print the value and what will end up over here is nothing but our post order traversal right so this is our post order result over here right so if you see for every subtree like if i take a subtree over here so let's take about this sub tree which has a root starting from 2 right so what will happen is you see that the root will come at the very end so this is our result if that is the subtree right so this will be our result this part so you see that the left is processed first so four came first then the right so five came and then the main route of the tree so the two came so the group for any subtree will be at the very end and the left most node will be at the very left so what we can say is that this is the this is our leftmost node and this is surely our root of the tree or the subtree similarly if you check for the main tree also you will see that the root is at the very end and left most node continues to be four so four is at the left right this is how this entire post order traversal works so we are going to understand that how we are going to do the same thing iteratively right so the solution that we are going to look over here is a dual stack solution right we are going to use a double stack over here it could be two approaches over here one is using double stack and the other is to add it to your list and then you reverse the list at the end right will be the result stack and the other we will call it the processing stack right we have a current and the current points to your root note right so we are going to put that so this node is yet to be processed right so we are going to put this node inside our processing queue what we can say but it's a stack i don't want to say queue and confuse you guys so it's just a stack it's a processing stack so one is not processed yet so i put it inside and let me put the algorithm over here at the same time so that it becomes easier for you to understand so the first thing that we are going to do is add root to the processing stack so the second step is to second step is that we are going to iterate until the processing stack is empty and it's never going to be empty because we as we go on we are going to continuously add the left and the right child to it until we hit a null so until the entirety is complete this is never going to be empty right so now what we are going to do if you remember that our route always stays at the very end in a post-order traversal so what we do is we post-order traversal so what we do is we post-order traversal so what we do is we take this one that we have already over here so the first thing that we do is so i'll call it p stack for simplicity i have to i don't have to write it again and let's say we get it in e right so we are going to add this to the result stack right we are going to put the value of it inside the result stack so we are going to put this one into the result stack why we are putting the root at the very beginning is because we are going to take the result out from this result stack and put it back to the list and if you remember if we take things out from a stack the first entry to go in comes out at the very end right so one will be at the very end for us right and what else we are going to do is we are going to add to the processing stack the left and the right so what will essentially happen because of the statement is we are going to add the left and the right so you see that again over here what is important for us is that we maintain the right order the left goes first and the right because if we take out things right should come out first and then followed by the left so what happened is we popped out one at this stage at this state and we added it to the result so it came here and we added the left and the right node of the one so two and three was added in the process now we are going to pop out things back from the stack again right so let's get out three from the stack because that's the next element for us so as we get the three what happens is three goes inside this deck right that's what we do always and we add the trees left and right to the stack so 3 is left is not there so right is a 6 so we are going to add the 6 over here right so 3 is done so we pop out again and we get a 6 over here right so 6 is again added back to the stack and there is nothing so we can't proceed any further so next time we do a pop what we get is a 2 so we get the 2 over here and now what we are going to do is we are going to put 2 inside this process result stack and add 2s left and right to the processing right so we are going to pop again and this time when we pop we get a 5 right and what we do is add the 5 to the stack and 5 doesn't have any left and right so nothing to be added so we pop again what we get is a 4 sorry this 2 was also done so we get a 4. so we add the 4 over here and we are done with this tag now this stack is empty for us right and now if i take this take out this result over here and start putting it into a list right so let me put that algorithm part over here so let's say we are going to iterate until the result stack is empty and let's say we have a list over here which is of type integer and let's say it's called res so let's say what we do over here is to add to rest and what we do is we do a result stack dot pop right so what will happen things will start coming out of this stack so what will come out first four will come out and get inside this list four is gone we get a five next five is gone then we get a 2 is gone then we get a 6 is gone then i get a 3 is gone and then we have a one so we just got the same result as this guy we what we just did is we stored the result in a reverse order so that's why you see that we put the left first and the right because we are using double stack so if i take the right and process the right first and then put it inside the other stack and then i put the left on top of it so when i take out so what happens over here is visual like let's do a visualization let's call it root left and right and let's say we have two stacks over here this is my result stack and this is my processing stack right so what we did was we put the root first over here and we started right we so now we get the root out and we processed it and added it to the result now we put the left and right our target is to do left then right then root right so what will happen is we need the left first and the right so if i put it like this over here in the reverse order so when i take out i get the right first so when i get the right i put the right over here first and then what happens i get the left and i put the left over here and now we are taking and popping things out from the stack and we are building our results so what will happen is left right root right because of the nature of stack so what will happen is this and this will become equal right so what we are going to do is we are quickly move over to the lead code and check out the solution for the same okay so at the end what we need to send is an integer list so let's build that first and let that be a array list and what we are going to do is we are going to populate it and send it back at the end and also we are going to return an empty list if we see that we are passed with a null right so in this case also we are going to return the result right so now we have talked about two stack over here so let the both be so i'll take a stack of three nodes over here and we need a stack of integers that we are going to reverse at the end so our route has not been processed yet so what we should do is we are going to add the root of this tree to the stack and we are going to say that we are going to continue processing until the processing is empty right so here we are going to pop things out and now we are going to check if left is not null then we are going to add to the processing stack and similarly we are going to do the same thing for the right as well so let's get that done okay so at the end of this loop what will happen is we'll have our nodes inside the value stack and our processing stack is empty now what we are going to do is we are going to iterate until the value stack is empty and we are going to pop things back from the stack so until it is not empty we are going to iterate and we are going to add back to the result dot pop run and check yep it's good so let's do a submit and check for a wider range of test cases yup we are better than 100 of all the submissions which is pretty cool so i hope you understood the solution over here whatever we have discussed and explained so far you have understand the simplicity of the solution and why we are basically using multiple stacks over here in order to come up with the result right so yeah this is the algorithm all about us now talking about the complexity so basically all your element will be touched over here the way we are traversing right we will have all the element touched right so you will have a runtime of order of n right where n is the total number of nodes we have extra loop over here this is also going to contribute to order of n because we are processing we are coming up with the result right over here so a post order traversal should include all the nodes so yeah it will be order of n so order of 2 n which is equivalent to order of n and coming back to the space complexity over here so we are building multiple stacks over here right and in the worst case what will happen is you can end up holding all the nodes that's present for your tree into your stack space right so either your node will be present on this stack or in this stack it will not be present on both the stack at the same time right either it is here or here all could be present here or none could be present here so if you add them at any time you'll have the total number of nodes that's the maximum that's going to be so your space is also going to be order of n so you will require in the worst case you will require n spaces so if you have a tree which is skewed to the left so what will happen is your stack will have all of these nodes present inside your stack right and again for the other stack also for this result stack what will happen is you will eventually store all the nodes here right it's a good case of the bad case whatever case it is you will end up storing all the nodes over here so again you'll in the worst case you will have an order of n for that stack as well it is again going to be order of 2n right we can drop the constant and it still becomes order of n right so yeah this is uh the solution all about do let me know what you think about the solution um do like and subscribe if you think the solution was helpful for you and i should be creating more videos down the line it would be of great encouragement for me as well if there is any particular problem that you want me to solve it's an online problem offline problem whatever problem it is or any concept you want me to create a video on do let me know i'll surely give a try it's good that i have started hearing from people in facebook or in different platforms where people are approaching me with problems to solve for them and definitely i will create videos for them as well down the line so let's have more engagement on this channel let it be interactive i just don't want to create videos on whatever i think i should be creating but i should be creating videos on what you want me to create so that even i get to learn new things i need to explore new things along with you i should also be growing i feel at the same time so do let me know and let's keep it as interactive as possible so yeah i'll keep this short so that's all from this video see you guys soon again and have a great day bye
Binary Tree Postorder Traversal
binary-tree-postorder-traversal
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,776
1,650
hello and welcome to the cracking fang youtube channel today we're going to be solving lead code problem 1650 lowest common ancestor of a binary tree 3. let's read the question prompt given two nodes of a binary tree p and q return their lowest common ancestor according to the definition of an lca on wikipedia the lowest common ancestor of two nodes p and q in a tree t is the lowest node that has both p and q as descendants where we will allow a node to be a descendant of itself and we can see that we're given a node here as a data structure that has a value it has a left and a right which are both nodes and it has a parent which is also a node so we should keep this in mind when we solve our problem now let's look at an example okay so we've read the question prompt and we've understood what a lowest common ancestor in a binary tree is now let's look at our example and try to see how we might solve this problem so if we're given that p equals four so this node here and q equals eight this node here what would be the lowest common ancestor well we see that the node where both of these converge at is going to be three why so we go here and then we go here so we hit the root and then this one will go up to the five and then the three so this is the first node when traversing up for into the parents that we meet right from both sides and obviously eight can't go any higher because um you know it would just there is no parent of the root so this would have to be our node here so this gives us the idea that perhaps we want to go up the tree and then find the first point where we have already visited from the other side so in this case you know this one is actually a shorter side of the tree so we'll actually reach the three first so one approach to solving this problem could be the set approach where we will start at you know p and we're going to traverse p all the way to the root and we're going to keep track of all the nodes that we see along the way so for example we would see the node 4 we would see the node 2 we would see the node 5 and eventually we would hit the root and that's when our iteration is done because obviously the root doesn't have a parent so this is what we've seen so far cool so now we're going to do the same thing except we're going to go from the 8. so now the 8 is going to go it's going to kick off so it's going to see the value 8. it's going to then see the value 1 and then we're going to reach 3 but we've already seen 3 before so this would be our lowest common ancestor because this is you know this is a node that we've already seen and this is the first node that we see that's in both trees when traversing to the parent so that's one way to do it and certainly this is you know possible in your interview you can definitely solve it this way but your interviewer is probably going to push you to solve it in a way that doesn't require extra space of course this approach is going to require you know um you know this is gonna be a two a big o of two n um time complexity algorithm because we have to traverse all the way through the parent of the first node and then potentially all the way up to the parent to the second node um in the case that the root is actually lca and then for space so this is the time complexity and then space wise we're going to need to potentially store you know all these values this is also going to be a big o of n solution so this is actually just going to be big o of n asymptotically so we can actually solve this um without any extra space and i'm going to say now that the solution requiring no extra space you're probably not going to come up with it on your own unless you've seen it before it is quite you know one of those kind of aha trick solutions that you know if you haven't seen it before or if you don't have like a genius level iq you're probably not going to derive it yourself but once you've seen it's so simple it just like it'll blow your mind and let's go over that solution now okay so we've seen what the naive solution to this problem is but i did tell you that there is an optimization where we can actually remove any sort of space allocations and do this in constant space how are we going to do that well i just want to preface that this solution is one of those trick solutions that if you've seen it before it's super obvious how it works and it will just click if you haven't seen it before then the first time you see it'll click you'll realize what it is you'll have your mind blown but the chances of you actually deriving on your own are quite slim unless you have some like genius level iq in which case you know you probably wouldn't even be watching this video because you'd already be working at google um anyway what we're gonna do here is quite strange and let's try to follow the logic and hopefully it's going to make sense if not we'll write it out and then kind of derive it as we go so what we're going to do is we're actually going to create two new variables the first variable is going to be called p copy which is going to be set to p in the beginning so we're going to define it to be p and q copy is going to equal to q so if we draw this out this in the beginning p copy will be four and q copy will be eight and what we wanna do is if the two nodes p copy and q copy they don't equal each other so if they're not the same node then what we want to do is go into the parent um if it exists so what we want to do here is we're going to start at four and eight right so we're gonna see okay is four equal to eight no it's not so we're gonna go into its parents so that means we go up the tree so now p copy is gonna be equal to two and q copy is gonna be equal to one okay does two equal one no it doesn't okay so let's go into the parent of each one so now p copy is gonna go to the five and q copy is gonna go to the three cool does five equal three no it doesn't okay that means that we have to keep going into the parent so p copy is going to go into the parent so it's going to be three and q copies parent is actually none because it's the root so this is going to be equal to i guess null right it doesn't have a parent so we're going to say okay does three equal to null no it doesn't so we need to go into the parent so three will go into its parent which is null right and we're gonna be at null for here and obviously we can't go to the parent of a null node because you know it doesn't have a parent so what we do in this case and this is where the trick of the problem is we need to reset our cue copy and when i say reset you may think oh we're gonna set it back to eight actually what we're gonna do here is we're gonna reset it to p and you're gonna see in a second why we do that so we're gonna reset it to four and we're gonna continue with our iteration because we're going until p copy um equals to q copy right so okay does null equal four no it doesn't so we need to go into the parents and because null does not have any parents we need to reset p but again like we did with q we're not going to reset it back to p no we're going to reset it back to q so now we're going to be at this eight and remember we need to go into the parent of the four so now we're going to be at this two here okay so now we're at two and eight does two equal eight no it doesn't so we need to go into the parents right so that means that p copy is going to be eight so its parent is gonna be one and then q copy is going to be this 2 and its parent is going to be 5. now does 1 equal 5 no it doesn't so we need to go into the parents again for both notes so the parent of p copy which is the 1 here is going to be 3. so we go to the 3 here and here's where the magic happens q copy's parent is also three so now we've hit the point where they're actually equal so we know that we found the least common ancestor which is this three so why does this work let's think about this well the reason that this works is because when we iterate through the tree one will reach the parent faster right there'll be some gap between the nodes in terms of like how many steps it takes to get to the parent in this case for the four it takes one two three whereas the eight will get there in one two so the difference between them three minus two is going to be one and why is this significant well if we know that one got there faster by one well then if we reset the value right so if p got here in three but q got here in two and that means q will be one ahead so instead of setting it back to q we set it back to p which means that now it'll take three times and then the q the p will catch up it will get reset to the original q and now the distance between them the gap will have been bridged so that now they have uh equal time to reach the note the lca and apologies if that's a little bit of a rough explanation it does take some time to wrap your head around it but let's think about it and kind of like draw it out again so we know that we start from four and eight right so it's going to you know it's gonna be one iteration to get here on the next iteration we go to the five on the next iteration we go to the three now remember we go up again so this you know goes to its parent and this goes to the three which is like null here so now we reset this down here uh and then what we're gonna do is this is now gonna go to you know null here and what we do on the next iteration is we then go up here for the this is now q and now p will get set to this thing and we can see look now there's a gap of two and they're gonna reach at the same time so it's gonna take one two to reach the three and then q it's gonna take one two so that's how we've like equalized that you know three minus two equals one gap um by resetting it to the other node again it takes a little bit of time to wrap your head around this and it you know once it hits you and it clicks that's it you get it's a very strange solution we'll code up both the naive solution and this one um probably if you don't understand the solution better to just go with the naive one and then you can maybe like cheese your way through the um you know the optimal solution hope your interviewer doesn't really ask you to explain too much but you can kind of walk through this and hopefully this has made sense so let's go to the editor and actually code this up we're in the editor let's code up both solutions and we're going to start with the naive solution so like we said we're going to maintain a set to keep track of the nodes that we've seen so let's define that so we're going to say scene equals set and what we're going to do is we're going to go up through p get all the nodes that we see and then we're going to go up through q and the first time we see a node that is already in our scene set we're done so we can simply return that node so we're going to say while p we're going to say what scene dot ah scene dot add p and we're gonna say p equals p dot parent cool now what we can do is we can go up through q so we're gonna say while q and we're gonna say if q in scene return q else we're going to say scene.add else we're going to say scene.add else we're going to say scene.add actually we don't need to do that at this point we know that we're going to find the lca we're just going to say q equals q dot parent and then what we're gonna do at the end actually that's it we don't have to worry about the node not being in there because we are told that um they both exist in the trees so we will find an lca so that's really all we have to do so let's submit this make sure it works and cool it does work so like we said this solution is going to be a you know big o of n in the time and then big o of whoops uh space wise it's going to be also big o of n now let's code up the solution for the you know little trick that i told you about and it's actually super simple so let's reset our editor here and remember what we said we're going to make a copy of p and we're going to set it equal to p and we're going to make a copy of q and we're going to set it equal to q so what we need to do is remember while p copy does not equal to q copy we're going to say that q copy is going to equal to its parent if you know q copy exists so basically as long as we haven't hit the root and gone to its parent because that in that case it's null and null nodes obviously don't have parents we'll get some sort of like access error here otherwise in that case where it is null we need to reset it but not back to q we need to set it to p so we're gonna say p and we're gonna do the same thing for p we're gonna say p copy equals p copy dot parent if p copy else q and at that point this while loop will break when they're equal which is going to be the lca as we saw from the drawing and all we need to do is either return p copy or q copy it doesn't matter because at this point they'll be the same and that is it so let's submit that make sure it works and we can see that it does so we did not improve anything on the time here it's still going to be a big o of n algorithm but on the space since we're not actually um defining any sort of data structure to keep track of where we've been we just have these two pointers it's going to be a constant space solution so this is the most optimal solution and obviously you know it is a trick solution because i think that personally if you've never seen the solution before you know whether you read the leak code comments or you know you saw the worked out diagram or you watched someone else's video you're probably not going to know this or figure it out on your own it is one of those like oh duh like it makes sense once you've seen it and it's so simple why it works but if you haven't seen it like it's just ridiculous uh although it is quite easy to explain so hopefully you know this video did a good job of explaining to you how it works you know you can kind of watch the diagram hopefully it didn't get too messy because there is a lot of things going on but just re-watch the explanation but just re-watch the explanation but just re-watch the explanation portion if you didn't understand how i actually derived this solution and why it works and then you know maybe just try it out with your own tree and see how it works uh and then realize that they will eventually converge after you know uh two iterations through the tree they'll eventually hit um the point uh that finds the lca and at that point you're actually done so we've solved this question in two ways one being kind of the naive solution one being this like strange obscure trick solution but it is the most optimal solution so you should probably know it for your interviewer um you know you're going to probably get hit with this as a follow-up if you hit with this as a follow-up if you hit with this as a follow-up if you solve it the naive way your interviewer is going to say okay can you do it without extra space so you're definitely going to want to know the solution anyway if you enjoyed this video please like comment and subscribe and good luck with your elite coding bye
Lowest Common Ancestor of a Binary Tree III
find-root-of-n-ary-tree
Given two nodes of a binary tree `p` and `q`, return _their lowest common ancestor (LCA)_. Each node will have a reference to its parent node. The definition for `Node` is below: class Node { public int val; public Node left; public Node right; public Node parent; } According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow **a node to be a descendant of itself**). " **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[1,2\], p = 1, q = 2 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` exist in the tree.
Node with indegree 0 is the root
Hash Table,Bit Manipulation,Tree,Depth-First Search
Medium
1655
126
hey everybody this is larry this is me going with the july decode challenge um word ladder too i'm not gonna lie i a little bit lower in time today i didn't i mean i didn't solve this i saw this previously so you can actually find my video from before but i'm just going to do a quick going over the solution there are a couple of solutions here the way that i did it was by doing breakfast search so hit the like button hit the subscribe and join me on discord let me know what you think about this problem uh and also little dog is here you can see on my lap so maybe my typing is a little bit ringy say hi donkey okay maybe not anyway so for this problem the kind of nautical solutions can be breakfast search um but some of it is just keeping track about the bounds and stuff like that the only five characters which makes it a little bit good but you can also kind of think about all the graphs right um so two words are connected if they're different by one character um they're only a thousand words so you can actually build that graph out and then kind of do an exhaustive breakfast search um and you're trying to get the shortest transformation so what i did here um let me make this smaller so i could see this quicker um what i did here was that i basically i um you know i put the word list here and you can actually see my video as i was doing this but yeah the short answer is to be honest just breakfast search and for each one being able to kind of get the breakfast search um and with a breakfast search you can look at each node which is each word having a parent and the parent is just the previous um the previous note in the sequence and then once you do that you just go through the entire list and then reconstruct them from the bottoms up um so for example the way that i did it is that you know you do a breakfast search you do hit connects too hot and maybe just hide right so now after you kind of create this breakfast search tree of things that you visited and the parent of that node um now that you have this shortest path tree um which is a thing look it up if you have the shortest path tree then you just have to reconstruct the path going from bottom up and which is what i did so i'm gonna go over the code real quick and this may time out and if it does time out um there are other techniques to kind of play around and optimize depending on how you do it in this case you know the ending condition and any condition there's only one word so in that case what you do what you can do is having a bi-directional by do is having a bi-directional by do is having a bi-directional by breadth first search and where you kind of meet in the middle it's a good prac this is actually a good practice for that so this problem is a good practice for that so definitely get into that um yeah that's pretty much it um yeah let me know what you think i will see you later have a great rest of the weekend bye oh yeah just doing a quick going over the code so yeah so here we just basically created the graph um we created a graph for the problem and yeah and then here this is the breakfast search part you can kind of look through it and see and then at the very end after we did the breakfast search and calculating the parent we it going backwards and you can kind of see this reconstruction by looking at it and then you just literally append stuff to the answer and then going backward this code is very old to be honest um i did it a couple of years ago so it's a little bit rough and a little bit less readable but you know let me know what you think and this is accepted as you can see but yeah i will see you next time bye oh wait target you want to see bye okay maybe tomorrow bye
Word Ladder II
word-ladder-ii
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that: * Every adjacent pair of words differs by a single letter. * Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`. * `sk == endWord` Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _all the **shortest transformation sequences** from_ `beginWord` _to_ `endWord`_, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words_ `[beginWord, s1, s2, ..., sk]`. **Example 1:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\] **Output:** \[\[ "hit ", "hot ", "dot ", "dog ", "cog "\],\[ "hit ", "hot ", "lot ", "log ", "cog "\]\] **Explanation:** There are 2 shortest transformation sequences: "hit " -> "hot " -> "dot " -> "dog " -> "cog " "hit " -> "hot " -> "lot " -> "log " -> "cog " **Example 2:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\] **Output:** \[\] **Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence. **Constraints:** * `1 <= beginWord.length <= 5` * `endWord.length == beginWord.length` * `1 <= wordList.length <= 500` * `wordList[i].length == beginWord.length` * `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters. * `beginWord != endWord` * All the words in `wordList` are **unique**. * The **sum** of all shortest transformation sequences does not exceed `105`.
null
Hash Table,String,Backtracking,Breadth-First Search
Hard
127,2276
653
Hello guys welcome to my video report to dhigri school administration subscribe our Channel and Share Thank you number ke liye aapko return rules are subject to market ok so lets you want to know the limits for example 99690 subscribe and placid in the problems and 252 Those Who Are Very Selfish Tablet Se Bigg Boss Are Like A Look At This Time - At This Time - At This Time - Festival This Info You To I Love You To You Same To You Can Solve Problem They Used To Give Me To The Number Se Left Right Left Side Will Increase Or Decrease Computers from the left parties where left currently value to airtel will right now value 7 Plus eligible to know what you have not but I want to meet you want to make it right you want to make sure you have no Greater Noida and Greater 9.1 Option to To-Do List To-Do List Subscribe Now to Receive New Updates Reviews and Order Ascending Order to Increase Your Holiday Need Not To Increase Live Wallpaper Deposit to Reach a Great Subir Will Be Tempted Option of Mohammed Ride Point to Humble and Ride Point Want This will decrement and prosper pimples and survey santu decrement side effect I myself there I don't know way ride point is point to 10 element what is my son toot classes stomach and sorry to places at midnight properly take flu sweet servi subscribe convert in Too Difficult For Kids Are Converted By Doing Something In Traversal Preorder Traversal Rule And Left Right Always Used To Travel To Convert Binary Search Tree For True Love Quote 10 For Swear Sorry Late Straight Invert Traversal Such Wearable Top Ten That Our And Not Pregnant Student Reversal Now That Latest Right to See Betacarotene Assembly Election Results for Lord and Will Visit the Left for Residents Next 9 From the News Room Like a College Kid with Logic subscribe The Video then subscribe to the two Children Also Starting Thursday Use Free Here Nau Will Go To The Price Aka Jordan Left Right From Wrong Again When They All Will Return Gift Heroic Value After Writing Trade Will Go To Right Side Left Right Left To Return Back To What Is The Value Values ​​In What Is The Value Values ​​In What Is The Value Values ​​In Children Also You Can Store Video then subscribe to subscribe our Loot Songs Problem Agar Song Aapke Inorder Traversal Let Me Write In Northern And Western Toilet Reversal Play List Declare Option Point Se And Me To The Inorder Traversal And Latest First World Tour And Travels Simple Do The First School Child Rights Will Give The Value Of The Current Wali Hai 15910 Avadh Logic Surya Starting From Root Set Will Keep Falling Asleep Channel To Subscribe Cost Of Students In The Written In The First Box [ Sangeet] Sangeet] Sangeet] Daily And You Will Notice A Simple Technique 10 Inch Right To Reach is equal to a Shree Ram and minus one race rigid maybe now actors - but question decision standard size actors - but question decision standard size actors - but question decision standard size absolutely english speaking to find the advantages and specific 2.1 a 2.1 a 2.1 a 500 index medical seems that you have to do that gift only year old right is equal to Do You Do The Same To You Can Just Did n't Find You Ok Eat How To Get Spinal Arthritis Emergency Features Working On A Positive Final Lakers Vs Even More Of Us No Entry For Android Video Player And Simple Difficult Volume Increase The Satanic Vs Delhi Don't Have Opted Are Elected For Simple And Easy To Three 6946 Want To Know What Will U Still Love You To Write Your Story And Have Subscribe Now To Receive New Updates Reviews Lu He But Set The Alarm Set Will See The First China Want To Make water security system of any two elements which give you please tell what do you for entry into this number 66 to give you want to give a new set of water in the body used simply for the number 66 as minimum which add to back side Reaction Viewers 79 You Too Make You Strict You Too Hot Scenes Him Emphasize Meet You Have Three Already Requested University New Founder 797 Plus Re-Tweet Android Fennel Powder Number Plus Re-Tweet Android Fennel Powder Number Plus Re-Tweet Android Fennel Powder Number And Western Dresses Of Value Edition World Tour K - And Current Of Value Edition World Tour K - And Current Of Value Edition World Tour K - And Current Volume Friend In This Country In this example deposit pimple 2327 approach will love this point or invented whichever way they will just user name of us will start with five states will not mean that resides simple defense or bloody mary like and you can not to vanish in the sense software visiting this site Needs To Find Good Quality To-Do List For Pilots Quality To-Do List For Pilots Quality To-Do List For Pilots 8th 10th Seed 354 323 The Effigy Of Solid Evidence Act To We Want To Make 8 And How Can Eradicate Using Free Play 25 Give A Try With Destiny Satisfy Solid F5 Solidarity Screen The system inches plus back you for Middle Provinces particular's undeniably simple logic will decide to rights in the England vs HHH agree with oo and 509 a slave and apply them and avid fans looting replay example which aims to set up that and events and applied Difference Album Play Kar Do Is Ped Chaat With Us And Su Tags English Meaning Of Cases Roots Life But Can Never Give Answers And Objects And Reasons For School Students Should Not Mean That You Will Find The Value Of Root Subscribe Thank You Should Not Give Subscribe Now To Receive A Wise Discrimination Sequence Rot And Us Avoid Food And Finally Bigg Boss Not Equal Distorted Means The Set N Album Samrat Shift Delhi From West End Retention Million Students To Notice Connected Find A Significant Collect Daily Subject Next Same Time In Element With This Will Be Used Oil So You Can Share This Content Volume Minimum Set Love You Can Find A Little Water While Returning To All Left Side And You Can Follow Us On Ke Andarch Mein Yogendra Ke Andar Subscribe To Mere Ko Tere Se Smile At Summit Food And it's working that regional transport is very loose function because finally after taking rest parameters of cancers shift everything near and is not simply declared number function Sudhir and Cody sensitive research into a that had become compiler speaking position ODF in that is that point Diner target in your net Next 9 Caller from news room Obscene material on internet N o k laddu Switch off I can see it Publication admission
Two Sum IV - Input is a BST
two-sum-iv-input-is-a-bst
Given the `root` of a binary search tree and an integer `k`, return `true` _if there exist two elements in the BST such that their sum is equal to_ `k`, _or_ `false` _otherwise_. **Example 1:** **Input:** root = \[5,3,6,2,4,null,7\], k = 9 **Output:** true **Example 2:** **Input:** root = \[5,3,6,2,4,null,7\], k = 28 **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-104 <= Node.val <= 104` * `root` is guaranteed to be a **valid** binary search tree. * `-105 <= k <= 105`
null
Hash Table,Two Pointers,Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
Easy
1,167,170,1150
242
hi guys welcome to algorithms made easy in this video we will see the question valid anagram given two strings s and t write a function to determine if t is an anagram of s in the example one we have two inputs string s and string t and the output is true now why is the output true you can see that the set of characters in s and t are same the count and the character both things are same in both the strings and so we can say that these are anagrams while in the second example if you see string s contains r a t and string t contains c a r that is this t and the c are different in both the strings and so the output is false for this question you can assume that the string will only contain lowercase letters so now how can we solve the question the first thing that we know is count of characters must be same so we can also say that s dot length is equal to t dot length so this would be a base case and all the characters in s would be there in t so how so one of the ways that we can solve is by taking the character array for both the strings and then sorting that character array if after sort both the character arrays are equal we can say that these are anagrams so let's just write the code for that approach so we'll take two character arrays which would hold the characters for our strings s and t now we'll perform sorting on them and at the end we can just return whether these two are equal and that's it we can write a base condition of length that is if s dot length is not equal to t dot length we can return false let's run this and it gives a perfect result let's submit this code and it got submitted the time complexity over here would be o of n log n as we are using a sorting algorithm and we can say that our space complexity would also be of n as we are using this character array but it depends on what language you are writing the code into so now let's optimize the solution to bring it to o of n time complexity so instead of doing this sort what we can do we can take a count array and as we know we are going to have small case letters we can take that array of length 26 and now for the string s we can keep on adding the count in this count error for each character so let's just remove this first and yeah so in this what we are going to do is we are going to add the count for this particular character which will be c minus a as we wanted 0 indexed with this loop we have all the counts for s in this count array we will again run a loop for t and here we will start deducting the count and whenever the count is 0 and we still have a character we'll have to return false because there is a mismatch in the character count so we first check whether count of c minus a that is at this index if the value is equal to 0 we return false as if we deducted it would go into minus which we don't want and otherwise we just deduct it count of c minus a minus so every false condition would be actually caught into this and this if everything runs successfully we can simply return true and now let's run this code and it is giving a perfect result let's submit this and it got submitted the time complexity over here reduces to o of n as we are just looping on the characters in the string and the space complexity becomes o of 1 because we are just using an extra space for the array of 26 characters to store the count so that goes to o of 26 which is equal to of 1. so that's it for this question guys hope you like this video and i'll see you in the next one till then keep learning keep coding
Valid Anagram
valid-anagram
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** s = "anagram", t = "nagaram" **Output:** true **Example 2:** **Input:** s = "rat", t = "car" **Output:** false **Constraints:** * `1 <= s.length, t.length <= 5 * 104` * `s` and `t` consist of lowercase English letters. **Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
null
Hash Table,String,Sorting
Easy
49,266,438
1,531
hey everybody this is Larry this is day 15 of the October Lego day challenge hit the like button and the Subscribe button join me on Discord let me know what you think about today's form 1531 strain compression two rle is a string compression method that we place okay one length obviously uh I know how to do this though yeah I was gonna ask usually this is the point that sometimes it's different uh on the rle algorithm I mean it's a very thing that comes up from time to time okay so yeah given S and A K the most K character such that the one length encoded version of s has minimum length Okay what does that mean so well I remember just being hard this is a heart yeah it is a heart I'm I don't know if I remember this particular problem which I don't know if I remember this I feel like I remember a something variation of this either on binary or something like this binary or something like this binary or something like this maybe even our need code to be honest but it's been a while I do remember just being tricky so let's kind of see if we can get it oh well I guess the easier part is the end is less than a hundred so that actually changes thing right um not adding to one actually changes things a lot so then that means that there already only three cases for each character right for each length comparisons uh spec or especially once that fits into n is less than 100 that means that you have well A Single Character you have uh you know a character that shows up to nine and then a double digit character and basically those the double digit characters will give you a cost of three uh cost of Two and a cost of one right in terms of contribution to the final answer so okay so you could lead at most case and most K but of course you don't need to delete all of K because if you delete all of k um how do I say this if you delete all of K sometimes you may have some sub-optimal answer right for is that sub-optimal answer right for is that sub-optimal answer right for is that true actually maybe not I'm lying on that one I was thinking about another Edge case where maybe that doesn't apply here okay so let's see right oh I guess technically also I lied a little bit because I think technically it could be 800 right um so we have to be okay so there are four cases um yeah uh okay I mean it's still the same idea um okay so maybe one way to do it is just and this is gonna be recursion and kind of Brute Force which you can memorize because there's indexes right but okay but what is the right way to do it right so let's say you have some um I don't know uh was it meant get main function say index is an obvious uh dynamic programming thing for getting the suffix um I don't even know if I want to do it quite this lazy but we can see my left is equal to K left right so indexes and I'm not gonna lie I'm gonna skip I wouldn't say skip is not the right word but I am going to go with this part a little bit fast because I don't know how to solve this yet um as well oh I mean I know how to solve it per se but I don't know what the edge cases so I may be a little bit off but um here I would say that because this is a hard problem and this is the weekend I do urge that if you if my I've done a lot of dynamic program problems I actually usually explain them pretty okay but you know this is a harder one so I want you to if you struggle this one try a easier one where you have to do the index meaning this uh dynamic programming where the function um the optimization function is a function of the suffix and then kind of play around with that maybe add a dimension to an additional Dimension to it so yeah so you know um because we expect that there's almost four cases let's do an analysis first right because I think one thing that I usually do is that I write out the code and then do analysis but to be honest I do it the analysis first to see if it's feasible and then I write the code bit but um but I do it really quickly in my head so yeah so I suspect that in the worst case this is going to be the thing and then we can maybe there's a couple of ways you can do it meaning that okay so these are number of inputs right so number of inputs is going to be n times k um and then what is the O of the of one operation right so um each operation or each input takes how long right um ideally all of one but maybe it could be okay um in theory if you do it you know not in a good way um I think the way that I want to do it is all one but it takes a little bit more work but you can do it okay as well in theory maybe um I just want to double check that there's no um okay yeah um yeah so and in that case you know given that uh let me right here if is it is okay then you have n times K which 400 should be fast enough if not then we'll kind of play around with it so yeah um and the first thing I would say is I actually want to do the compression first right um I want to actually convert this s string into something else just because I don't I um and this is just off-cut instincts um and this is just off-cut instincts um and this is just off-cut instincts and that gut instincts is obviously uh hung by years of practice so but sometimes I'm still wrong so don't hold me to it um so don't hold me to it but I do want to process in a way such that I have fewer edge cases and that's something that I hope to do um and actually it should be a very easy Group by function it turns out it is in Python uh yeah so for GT and uh what's it called length of t uh length of a ray of T list of T there you go and then we don't even care about actually I was going to say we you know we could use the G but the character itself doesn't matter so we don't even care about that so then actually we can just do something like um yeah something like this right to auto is annoying and I think that'll be okay let me just kind of make sure that this is what I think this does what I think it does I actually messed this up because I didn't convert it um length of the list of it oh geez the auto stuff is kind of bugging me out uh I don't uh I still cannot turn on all I cannot turn off autocomplete Okay so what's the print oh this is a stupid point okay so this is three one for this one which is what I expect uh this is 222 for this one should be yep and then yeah I don't know how long this has been I could say okay so that's the only thing that matters right um okay so yeah so then now we can do this memoization based on this instead and then here we can go um and this is maybe just excessive right so yeah um and then here maybe let's just do n is equal to length of ah and if index is equal to end and we return zero because that's we um this is the length of the remaining suffix or whatever right so and indexes are D and then is silver otherwise we can do something like what do we want to do um so we have argue of index and then we just have to do cases on it right meaning that okay um let's say uh I'm trying to think about a easy way so obviously I can do something like yeah well like this but in a better way I just ought to write good thing I is that I think that one you could turn off right now uh maybe not I don't know okay fine so I'm just gonna do something like this to get to oh geez get the length I don't know if that's the Queen's way though what do you think um sorry someone was someone's messaging me and I don't know I'm really padded side friends um getting distracted um okay so this is the length right um and this the length is the cost and well it means okay this is a c as you go to this and actually we could probably just pre-calculate this anyway probably just pre-calculate this anyway probably just pre-calculate this anyway right so let's do that so that I don't okay because it does feel those squishy yeah but right uh oops all right something like this right and then now I can just do c as you go to I guess it gets cached anyway but once for each left so we would have done so we saved like o of K time we kind of I mean it's a constant thing so it should be okay uh okay but okay so then now um now we just kind of brute force in how we want to do right and basically what we want to do is um and we have to kind of Express this but the idea is that we want to use enough left such that you know we calculate um such that we kind of go to one few digits and maybe there's a cleaner way to do this but yeah okay so let me think maybe I'll just write a function right so okay so well let's do the base case first so base case uh or not base case but just like uh we don't do anything case then we have index plus one um we have left and then we have C because that's the length of the thing plus one I think um yeah I mean this is not quite right but um but that's the cost of it right so okay we have to figure it out a little bit um it's okay what I mean by digestive C is equal to one then it costs as one if C is oh wait uh or rather if okay this is annoying okay fine uh something like this course if you go to C which is the length of the thing but the autocompress if uh our sub index is equal to one then uh cost is equal to one right because even though it will be also actually sorry so the length of the suffix is going to be just plus one otherwise if the array itself is so like I said this is very uh just being careful about it right okay so this is just a thing of doing nothing and then now we're trying to figure out okay what how much left does it take to get to each digit right so maybe we have something like Target in uh one ten a hundred one thousand just for completion uh right uh yeah if a is greater than or you go to Target and we say it this way because if it's smaller than we just skip it anyway um so I guess maybe we could just continue I don't know right if Target is bigger than whatever then we just continue right and then what are we doing otherwise we see you know uh Delta is equal to um the because one moral one sorry I've because it's a oh you don't get down to two so if you're 11 you get down to 10 if you're at eight you get down to one that doesn't make sense right the single digit one is a little tricky also this is kind of wrong because we want to get down to 999 we won't get down to 99 and then we want to get down to nine and then I guess that's it right so yeah actually maybe this is a better way of doing it right if Target is greater than away then we just continue yeah because then we don't want to we can't go up anyway but yeah downtown is there now the current amount minus Target right because that's the amount you need to go to 9 999 or 999 so then here we go okay uh oh we also want to actually go to one so actually we won one at one there so I mean we could maybe just special case that out because we have to special case out the cost part anyway so yeah okay fine okay so that here we also maybe just to enumerate oh geez total bracketing stuff uh and then just maybe see and it will be C plus one but that's fine I think you'd actually add a thing to a normal way but maybe I'm wrong here uh okay so that means that the cost is going to be one two three to go to there um yeah so then here we go best is equal to min uh men right yeah men of pass or get men of index plus one because we process this number left minus Delta and then plus C for the cause plus one for the digit okay yeah um we want to of course check that left is greater than or you get the delta just to make our memo a little bit easier maybe it doesn't matter I think you could either put it here or here it doesn't really matter to be honest or like you know check that love is greater than zero or greater than equal to okay right and then now we have to do the case for one maybe so that now we do something like Delta as you go to R of index minus one because that's pretty much it right if left is greater than Delta then best is equal to Min best get min and X plus one um left minus Delta again and then this is just plus one because now you have a single digit thing oh I did miss the case actually the other case is zero right meaning that there's an empty string you get rid of all of it this is if you have so much k then it doesn't matter so then I guess the other one is then um Delta is equal to index um if left is greater than Delta then we just do the same thing again but now you don't have to add zero okay and then I'll return best oh this is uh obviously like I said it's gonna be a little excessive that's why I was worried about it in terms of I don't know if I got disappointed so maybe I shouldn't say it that early but that's basically it uh zero and was it okay I'll make sure that I sometimes I mix my variables but okay I know that I haven't memorized this yet don't worry but I just want to see if it works for at least like the first case um okay it works for the first case and there's last case but it fails for this case why I'll put four instead of two hmm oh huh well maybe I made a mistake huh maybe I made a mistake I didn't consider this case actually maybe I should have read the input um okay so I kind of reduced this to a problem that I was wrong about and unfortunately 16 minutes in um this happens from time to time and yeah wow can I Salvage this I don't think so because this is almost like if I'm thinking about it then this is basically like um uh with some balloon pop right or whatever pop balloons and I don't think you can kind of get around it so as you can see even if someone have experience gets it wrong so maybe this is disturbing their heart so I would also say if I actually look at the example more cleanly I might I mean this is a edge case that they give you so it's a little bit uh kind of sad and whatever to do to kind of discover this way okay but honestly the reason why I feel it was silly only because I did it this way because I thought that this would be fewer edge cases right ironically because I definitely could have done it the other way but I thought that with this way then I could you know I don't have to worry about um other complications but otherwise okay let's start over let's say we solve this other farm that is not quite this Farm but okay let's get on over I mean let's get into the memorization part but it would have been okay so let's see let's think about this again then right um huh whoops I this has been my life lately kind of just been uh you know almost white which is almost sad enough but uh yeah okay so now how do we want to do this uh people keep on pinging me when I'm you know um yeah uh okay thank you yeah sorry so the hardest thing sometimes is to refresh and reboot your mind um definitely sometimes especially when you watch my contest videos you'll see you see as well um but I think the hardest part about rebooting is that you don't know that you don't always know that you're on the wrong path until you know um I think this one well sometimes and this is that sometimes you're faced with no choice but to have to do it right in this case I you know there's this test case you know this one where it's clear that I cannot do it or I cannot do that when I have to restart and restart is kind of hard because I still have that like you know um interior whatever of like oh but maybe I could still do it this way so yeah so okay let's reboot let's think right so these things I'm still gonna think um before us to begin with an immunization and then think about how to kind of reduce the states or dimensionality so that we can solve this in good time uh but yeah as you can see this is hard so you know uh yeah whoopsy daisies okay so again we're still gonna probably go index then and then here we want to do something like the last um last character um and then maybe like one for the length of the Run and then K left um so what would be the complexity if I just do so this is the most naive thing that I think would work um this is just off my head so I don't know just a zero to end so this is gonna be all bad nice try it's gonna be well one of the 26 so it's gonna be all of 26. I don't know if I say oh 26 but all of our first say um and then one will be because I mean it's clear it should be so to end but I'm trying to think whether um yeah I don't know it's a little bit iffy and then this is gonna be zero to K um this is gonna be 26 million which it sounds a little bit much I'm trying to think already which is why I'm pausing because this is easy to fill out per se is how many of those states are not possible right like I mean I know that Most states are not possible there's no way I can narrow it down and prove it in a better way right um trying to think maybe not but this is the most naive but double Bank scares me not gonna lie I mean you could say that by symmetry index N1 will only be at most N squared over two so it kind of direct over 13 maybe last character um definitely most of those dates are not possible still so it's not you know whatever and left well I guess left could be anything really hmm can I do a little bit can I do better not naively Last Choice 26 should be okay foreign I don't know let's kind of get started on it right and then we can maybe see um I think um I'm trying to think about this one thing actually um what I'm trying to think about is can I optimize this a little bit maybe this is premature to be honest but the only one that matters like okay so the idea I have is trying to abuse the attributes a little bit right and the idea that I'm trying to think is um just flew my head well once it hit they're really like similar to what we've already did right which is um you know there's the empty string there's one character there's you know two characters there's three characters and then maybe four but this is a case in which like it's not really possible or like there's only one case where that's true right times 26 of your will but so that means that if we let's say we special case this out right that means that we're only left with these four things and then now that means that after nine we have 10 right and after 10 it doesn't really matter we can just eat characters for free basically right so that means that here instead of zero to n it could be maybe zero to ten or 10 so do you love and say right something like this maybe just 10 actually so because 0 to 10 has 11 states right I think you can reduce it that way and then now instead of having a fact of 100 you have a factor of 10 right um okay so then that means that this is 10 times faster and now I think I'm it is more comfortable doing it I'm honestly don't know if it's fast enough because this is lead code and Lead code is kind of terrible to python especially lately if you ask me I don't know if this is old enough I have this issue so we'll see but uh but yeah I think this is good enough for me to start and of course we have to special case after a 100 case which is that if K is equal to zero and um S Sub Zero times a hundred is equal to S then we returned uh four right yeah s 100 right something like this something like that right if I'm wrong then mistakes were made but um yeah and you can maybe write it another way actually like uh length of as you go on right they're all the same characters okay so then now we're able to just by doing this check we are able to um reduce this by tenfold say and at least in the worst case well the new I guess this is the worst case I was gonna say near worse but it depends how you want to say it um okay uh that's it right so again that's where did my question go and we don't need this anymore do we let's do base cases of index is equal to n then we have let's see weather one so actually we have to process one whenever one ends so yeah let's just go uh F of one right two ways to name these well like my I don't have the points out to name these so uh yeah so then here we go if x is equal to one will be turn one if x is equal to zero we turn zero uh if x is less than nine return two I always return three right because we already returned four here just so I say again um yeah okay otherwise let's see right um if s of index is equal to last char um well we can choose whether we want to delete it or not so okay yeah so this is again and another extra exercise in being excessive um so you can do it in you know these are just all if statements uh oh that's how I imagine it so you know there are many ways of doing it I don't feel strongly about in particular case so let's keep doing it uh yeah and then yeah so if this is equal to the last character then we do um okay so we want to remove let's just say best is equal to in Infinity right now just be a little lazy on this one uh we want to remove so we want to keep saying because I'm let's do the obvious one first so here is get min index plus one we've removed this we keep the last charger meaning that we don't you know we don't change it um well I mean I guess either way it's going to be the same character and left yeah because the one increases and then you do left right um and then we remove then best is equal to Min best get min of index plus one uh we remove it the last chart doesn't change we keep the same one and then we have left minus one right there's no cost yet the cost is when you have to start two things where when you end a sequence is when I calculate it if it's the same you don't want to end this or you can't end a sequence anyway that's my logic um okay so then now we've got different then we do keep uh if we keep this new character then it's going to be as sub index right um yeah and then one is going to be one big for a new one and then left because we left and then now we have to add the cost right of the previous thing which is actually just F of the current one so that's fine um otherwise we remove again so now that means that we do this thing uh last chart because we removed it we keep the Run we did it do and there's no cost because we haven't processed this thing yet let me turn best that's pretty much it I think let's kind of give it a spin uh what's one uh oh yes so zero and then left is K right let's give a spin hopefully this is right even though it made time out okay this is one we're just sad zero that's very optimistic of you uh the reason is because I didn't keep a barrel on left um okay so we can only remove if left is greater than zero then we remove otherwise you can remove it easy debugging okay so it looks good for the doing cases we have to worry about timeout of course but let's catch this first so the way that would cache this um you know I usually teach away just because that's the way I like to teach it and kind of go over it but again in this case the key thing to note is that a lot of these states are not possible right and because a lot of these states are not possible we don't want to allocate all the memory for the impossible States and this is actually one thing that is an uh Advantage for top down memorization is because a lot you don't have to go to every state to check whether you know you can reupdate it right so yeah so in this world I'm going to do a little bit of hack which is that you know let's just say I have a cache is you go to a set right and then here I just set the key is you go to index last jar run left and then if key is in cash then we return cache of key otherwise at the very end we go cash of p is to go to best and then we just do that let's give it a spin and see if it's faster at least make sure it's working and I don't have any weird typo so let's give it a quick submit we'll see if this is fast enough on this problem okay good 928 day streak not super fast I suppose but and uh I haven't solved this before so this is my first time seeing it and you're watching the first time uh the first south of this by me and of course a lot of silly mistakes but mostly on um I don't know I made us a simplification that was not true um so yeah sometimes you hit those sometimes you don't and actually just I mean I knew that this was possible it's just that I wanted to get a um a better running time um yeah I just wanted to get a better running time and I wasn't really uh actually I lied about this too or I didn't lie about this but I've made a whole deal about this thing and then I actually end up not using it so then what we actually should do is actually do a Min of one and then 10. so now this should run a little bit faster as well for certain cases because now the states are reduced so let's give it a submit again uh just because I forgot like we talked about it and I just forgot to put in code we'll see how if this is faster and how much faster it is it might have this is way test case dependent so it might not be that much faster uh in fact it is slow for some reason uh maybe that reason is that you know we use we're calling a lot of men's uh so maybe that's why Min is not super cheap um that's actually kind of set but the states we actually did a lot of States so I don't know in any case I mean I could add a couple more optimizations here but I'm not going to the idea is still the same though um yeah I made a lot of mistakes with the because I did the simplification but yeah uh this is I mean for complexity I know that I usually go over it but I think you know maybe this one I would skip a little bit because I'll let you try to do it at home because I have done a lot of these analysis lately anyway so definitely check that out this is a fun problem sometimes maybe just keep it still bit simple is what I say to myself because any less than 100 maybe I should have just I don't know but I think to be honest as well some of it is that I've been traumatized by the coast really dubious performance uh situations so um so I don't know maybe I'm just like one of those things uh yeah like everyone is greater than 10 and one is zero oops yeah so it's maybe one of those things were traumatized by lead codes I try to do some optimization even than not in theory necessary if uh like it's always hard to tell the optimizations unnecessary just because of that so yeah this actually may be a little bit huh I'll get it I don't get why this is slower than not doing this at all though I think despite a little bit messy Maybe the hmm I'm actually kind of surprised maybe it's just like coping lead code and it's just like it doesn't really matter uh I mean you could see that it uses 20 Max less but um yeah anyway that's all I have with this one I'll show you the top show you the bottom and that's pretty much it let me know what you think let me know how you did it uh stay good stay healthy to good mental health I'll see y'all later and take care bye
String Compression II
number-of-ways-to-wear-different-hats-to-each-other
[Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string `"aabccc "` we replace `"aa "` by `"a2 "` and replace `"ccc "` by `"c3 "`. Thus the compressed string becomes `"a2bc3 "`. Notice that in this problem, we are not adding `'1'` after single characters. Given a string `s` and an integer `k`. You need to delete **at most** `k` characters from `s` such that the run-length encoded version of `s` has minimum length. Find the _minimum length of the run-length encoded version of_ `s` _after deleting at most_ `k` _characters_. **Example 1:** **Input:** s = "aaabcccd ", k = 2 **Output:** 4 **Explanation:** Compressing s without deleting anything will give us "a3bc3d " of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd " which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3 " of length 4. **Example 2:** **Input:** s = "aabbaa ", k = 2 **Output:** 2 **Explanation:** If we delete both 'b' characters, the resulting compressed string would be "a4 " of length 2. **Example 3:** **Input:** s = "aaaaaaaaaaa ", k = 0 **Output:** 3 **Explanation:** Since k is zero, we cannot delete anything. The compressed string is "a11 " of length 3. **Constraints:** * `1 <= s.length <= 100` * `0 <= k <= s.length` * `s` contains only lowercase English letters.
Dynamic programming + bitmask. dp(peopleMask, idHat) number of ways to wear different hats given a bitmask (people visited) and used hats from 1 to idHat-1.
Array,Dynamic Programming,Bit Manipulation,Bitmask
Hard
2105
901
Hi gas welcome and welcome back to my channel so today our problem is online stock span so what have you given us in this problem statement here you have given us a class okay from stock spanner in this you have one constructor and the other one is your next The function is, in the next function you have an argument named price, which is what is today's price of the stock, okay, what do we have to find here, we have to find the spin off stocks price, now what is this is your actual that you have to see. That is, the price you have given for today, how much was the stop price lower than this before, okay, you have to continuously see for how many days the price is less than this, you have to return the count and give it, okay, so what do we do, give an example. Through this, let us understand that the problem is exactly ours, then we will see how we can solve it. Okay, so look here, what all are given to us here, this is your stock spanner, it is constructed, okay, so it is constructed and next is your function. If the next function is fine then here you must know that there is no return type of the constructor so here the answer will be null, after that we are seeing that we have given next what is the recommended price for you so if this is 100 then what is 100? This is the price of today's stock. Now we have to see for how many days the price of the stock has been less than 100 before this. So there was no one before this and this is the only one. We will give its count depending on it. Okay, after that it is 80. Now this is the price of today's stock, now we will see how much it has been less than this in the previous day, so here the pay is 100, it is not less than this, only we will join for 80 and give it. Okay, then we will come to 60, you will see. Before 66, this is the price of today's stock. Okay, now we have to see for how many days before this, the price of this stock is room, it is not less than ₹ 80000, it is not less, so here ₹ 80000, it is not less, so here ₹ 80000, it is not less, so here also we count the return. Ok, so here it is 70, now we will see that 70 is the price of today's stock. Now for how many days has it been low continuously before this, then count by including 70, this will be the one count, then if it is less than 60, you will be the count. Then it is 80 which is not less then what will be the count here 2 That is why you have given the answer here ok after that what is yours it is 60 now we have to see how much is less than this so here is less note is it not less If it is equal, then it is 70. We have to see it continuously. We will see it first. Okay, this is not less, so just because of this, the count will be our own. Okay, here, if this was 50 of yours, then what would have been the count of yours? Three, this is 60 even if it is equal. If it is there, it will be fine, but here it is 70, if the previous payment given to him is more than this, then we will not come here, okay, so count your van here, then what do you have, it is 75, now we will see how many days till 75. If there are less than till then this would include van come tu three four then what will be the answer here four would be ok then we will come to 85 if we come to 85 then what is less than this 1 2 3 4 5 6 more than 100 what will be its ears six This will be your answer, is n't it 1 2 1 4 6 So this is your problem, now how can we solve this problem. Look, you are seeing here, whatever is the current stock of today. If you are fine for this here, if you are finding this pen number, then it is depending on the previous stock somewhere, right, so we have to take care of that also, so what will we do for this, we will see this problem here. You must have found the next cricketer element, right, somewhere you are seeing this problem by type, we have done a little modification, so here we have solved the problem by doing the same with the stag of the stock, see, we have solved this problem also. Okay, we will do that, do we have to take care of the previous data also, then what will we do, will we keep the PAN number here, what will we do, if we keep it here, then what will we do, whatever will be in your interview, okay, what will we do with 100 We will give van here because right now this step is empty, so for the first element, we will have our van, so okay, we will insert it here, now we will come to 80, okay, we will come to this, whatever is this next function when you call. You will do this price, now we will see how much is there in stock, here we will actually see whether its price is less than this or is it equal or not, then simply what will you do, in this condition you will insert 80 van, okay Done, then you have 60, you will come to this, now here you will see how many will be less than this, do we have to see that, first start from the top, if the topic is not necessary for us to see, okay, like in this case 60 was equal here but here it was just what was its previous one? 7th was right so this is more so we will not look here, okay so we will keep comparing from the top first. Is this just less? Is it not less? So in this condition, after doing 61, you return it, okay, you have done it, don't enter, do everything, okay, then what is there is your 70. Look, whatever you are keeping here, you have kept these spend numbers in seconds. In the next function, you will return this, okay, so here you are again, if it is 70, then in 78 case, first you will compare with the top, what is yours in the top, what is it less, what is the loss. If it is less then now see how much is the number given here. See if it is less. If in this case someone must have got less here. First of all look at this, it is 60, here I have given you 70, okay if for this. We get some number, here we get some number, okay, suppose here we get 2 or we get van, whatever we get, it is sure that if the number is there, it will either be van or it will be greater than right. And whatever will happen, it will be sure that it will be less than this, that is why we have added the count in it. Right Honor Vice Van is there only, otherwise for 70 we will have to look further, will it not be there? Okay, so we will see for 70, how much will be in 60. How much is there in 60 rupees, if it is a van then we will add both, okay, we have added both here and here, see what we have done here, we will also remove it from here because we have to see further, okay let us see for this also. If it is then we will come here and remove it and you will give the count in 70. Now you will understand what I wanted to explain. Okay, look here from the top, will you first compare with 70 or 60? Suman's van and its You have added the van of 60, you are done, okay, now don't come, how did I not do it is not less, okay, let it be, now what will we do with it, we will insert you here with 70, okay, it is done, now what about us 60 Okay, now what is ours, 60 is 60, now we will see what is in the top, 70 is okay, is it less, what is not less, if not, then simply return the van with 60, okay now it is 75, okay 75, now see. What is the top element, what is less? Okay, if it is less, then remove this from here and add this 60 van along with the van, 75 van and this 60 van, okay then we will see if this top element is still less than 75. So what will we do, we will remove it, okay, we will remove it, so you will add it here, you will add it, due to which it has become four, will this 60 be needed, will it not be needed, because we have been removed from it may be in your main. Did you know that when you are doing this, will the next element be counted and what will be the loss because if it is less than this then its number has been added here, because of this, what happened when 75 So you see, you came to know that it is less, so whoever got less than this will not be counted in it, that is why we are adding 2, we are getting 4, we do not need to look at 60 here. Because when we have popped it is in it, otherwise how will this case be handled from here because near 70 it will be sure that this count must have been added to it, okay, because of this you got four, so here you get 4. Got it okay now look this is also done okay so here the count is how much of 75 is four okay now what is 85 how will you find for 85 then 85 has its own van count Then we will see what is the top element, is it less than the aap element, is it less, then how much is its account, if it is four, then what to do here, add two, added it, then removed it from here, okay, then we will see whether this Top element Now, how is it less than 85? Han is less than 85, so what to do, add it to this, add van, then we have to see further, is it less further, so it is not less, is it? 100 So the lowest till now is here 1 4 1 6 We wanted a six here, look, we even deleted it, still you got this six because we are what we are adding here, so it's okay. This case of yours has to be handled here, okay what will you do here, okay people, insert 1 here, top is it less, isn't the top less, okay, what should I do with five, insert it with van, then four. Come then when you come to four, you will see four, is it lower than the top one, is the top not less, here I will set it, see, whatever second you insert here, you will be returning, okay then you will get the van here. Here you will get van here, then three came, three will see if the top element is less or not less, set it and return the van, okay then you are there, what is there, answer you here, van. And here, damage the van is the second element, okay then this is the van, what is the topic here, it is not less, we will simply give 11 answers and what will we do with it here, we will turn the van here, now we have our turn, okay, let's come. Now we are seeing that what is its van will be ours. Now this is the top element which is less than this, so what element is it is not less then we will remove it and insert its second element in it and then we will see which is the top element. If it is still less, then we will remove this one, we will add its van to it, we will remove this, we will add its van also because it is less than 8, this is also less, its van which is second, we will insert it in this and then this one. We will delete this also and insert it here. What will be your total? 2 3 4 5 6 7 1 2 3 4 5 6 Its own 7 So what will be the answer here For 8 it will be 7 Ok I hope you have understood this, now what do we do, let's see, okay, what we did in the court, now what will we do, the answer which will be given after your return, how much will it be for this, okay, the answer is this, now we will see. Is it not our second? Shouldn't it be MP? And the top of the step and the top of the step is the first. What are we doing in the first? We are inserting the price in the first. Okay, we are inserting in the second. How much number is there, how much is the count? So we will compare it with the first one, which is today's price, is it equal or a lesson from it? If so, what do you do, take it out from there and pop it, okay and we will have the first element price, your second element will be your account. If it is then we will add the second element in the answer and add it. When it works for you, what will we do. As long as you keep getting less, it will keep working. Then what will we do, we will add the price ansor in the strike. Okay, which is the current price and How much less can be there, it will be yours in the answer, so you insert it, okay guys, and finally what will you do, you will donate the answer here, okay, whenever the next function is called, this operation will be performed, what will be its time, so here In the worst case of your time complexity, your ON would have happened. Okay, how are you seeing? When you were looking here for ads, now you had to see all these. Right here, after seeing all these completely, remove them all. done one by one so here what will happen in your watch case is time complexity on and you next express here what has been done tag that has been done so what will be the space on n will be ok I hope you have understood from the explanation if If you liked the video then please like, share and subscribe. Thank you.
Online Stock Span
advantage-shuffle
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day. The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. * For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days. * Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days. Implement the `StockSpanner` class: * `StockSpanner()` Initializes the object of the class. * `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`. **Example 1:** **Input** \[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\] \[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\] **Output** \[null, 1, 1, 1, 2, 1, 4, 6\] **Explanation** StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return 1 stockSpanner.next(80); // return 1 stockSpanner.next(60); // return 1 stockSpanner.next(70); // return 2 stockSpanner.next(60); // return 1 stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6 **Constraints:** * `1 <= price <= 105` * At most `104` calls will be made to `next`.
null
Array,Greedy,Sorting
Medium
null
95
hello everybody and welcome today we're going to discuss the solution to the problem unique binary search trees you're given an integer n which signifies the number of nodes available to you and you have to create from all these collection of modes binary search trees and you have to create all structurally unique binary search trees and that's it now we want to discuss what bsts are in the first place so a node like x will follow this property the node to the right z will be greater than that and node to the left of it y will be less than that so y x and then z this is sort of the structure we are going to follow this is important to keep at the back of our mind and let's go ahead and dive into observations as i've said in previous videos it's always a good idea to look at small little cases and then try to build your intuitions from that so we're going to look at a couple of easy cases what if n equals to 1 in that case you just one node available with you and so that's the tree itself to reveal n equals to 2. in this case you have one and two nodes available and so you can have two trees like this one as the root two on the right side of it and two is the root with one on the left side of it okay so right away we see either of these two possibilities going in the future either we are looking at the sort of the swapping of orientations or maybe we are looking at uh changing of root you know in this case we had one as the root and then rest maybe we will figure out later and in this case we had 2 as the root at this point we don't know so let's go ahead and enumerate harder okay n equals to 3 we see a lot more cases this becomes like this makes it easier for us to observe a couple of things first that swapping thing is no longer very easy to do we have to sort of restructure entire trees if we swap so maybe let's not focus on that right now we'll keep that as later if we can't figure out a solution but the root thing looks very interesting because it looks like in this case we have two ones one two and two threes as the roots maybe this is important and we'll keep this in mind we also observe a couple of more things it looks like this case with the 2 as the root or with us 3 as the root we have these structures which look very similar to what we have seen above this 2 1 or 1 2 kind of structure is exactly what we've seen in n equals to 2 and so this hence the possibility of a dp we have repeating sub problems so maybe we can use dp so we've figured out two things maybe use dp and iterate over all the possible nodes considering them as root each time and then maybe we can recursively figure out how to build the tree and that's it that's the core logic of the solution now quick implementation level detail let's look at an example to understand it better let's say that we are iterating and we are at the current node 4 will make 4 as the root and anything to the left of it becomes the left sub tree anything to the right of it become the right subtree that's fine but now let's say that we want to look at right subtree itself this is one very important thing that happens see even when you consider this say as a sixth note as the root of this right subtree you are no longer considering one two three four five six seven eight you're only considering five to eight you have sort of restricted the range because you are only looking at a sub tree this means that keeping in mind the left and right and dices are a good idea and in fact we'll do exactly just that we'll recurse keeping both of these in mind and will iterate over all the possible eyes in between lnr and then for each of those will recurse to the left and records to the right okay enough side i think the logic is pretty clear now we'll dive into the code of it which should make things a lot clearer first we'll have a recurse function taking an input lnr this recurs is uh what we're going to initialize the recursion with the nodes start from 1 to n so the starting node is going to be 1 and the ending is going to be n both inclusive by the way usually we keep zero comma n minus one because uh we're dealing with indices but in this case we have to print these out as the answers so we'll just keep one comma n okay what's the base case of the recursion when will we end this recursion it's pretty trivial if you have seen other recursion questions if l is greater than r return right away but what do we return since uh this is a question of trees and nodes we're going to return a tree node which is none so an unknown pretty simple okay work now as we said we want to iterate over all of the indices between l and r so we'll iterate over that l and r plus one why r plus one by the way because of how python takes range so we want to consider l to are both inclusive okay we'll have the index in hand now what well you have the current index in hand which means anything to the right and left of it need to be considered so we'll have left as the left subtree which is going to be recursion of what now going from l sure and take this case for example we have this is the current type and this is the ln dr from this point from l where are we going till i or i minus 1 it's both inclusive so we are going from l to i minus 1. similarly writes is going to be recurs from i plus 1 now skipping over i and will go all the way up to r okay once we have both of these in hand what do we want to do left and rights are by the way simply now two trees we want to care about these are the returns of these recursion so we want to keep that in mind as well we'll now iterate over for all left and for right and rights okay we are iterating over every single possibility now we're iterating over all of the possible left symmetries and all of the possible right subtrees and for each of these cases for each left and for each right and right let's create a particular tree which is the tree in consideration right now which is going to be a tree node of i is the current node three dot left simply becomes left and three dot right simply becomes right uh at the end we also want to return like a giant list of trees at this particular level so we'll have all or actually let's just call it dot append the current tree we'll initialize it above here as an empty list and this is the return of the recursion function trees okay let's do a quick sanity check sorry uh records is not defined so just uh and i think this should fix it okay spelling error so that's fine no difference in the outputs that sounds good now we want to discuss the space-time now we want to discuss the space-time now we want to discuss the space-time complexities so in this question what are we trying to do we're trying to enumerate and create all of the possible binary search trees now in whatever time we create those trees is the same time as we as the same space we take to store those trees you create one tree you take some time and you store that tree you take some space in this effect the space and time complexities are going to be the same but what number exactly this structure might confuse you a bit but the answer is actually in the order of catalan numbers that goes into an entirely different direction and the proof of how we actually got to catalan numbers is a bit complicated so i'll leave a couple of links in the descriptions for you to explore anyways this was the solution to the problem unique binary search trees thanks for watching
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**. **Example 1:** **Input:** n = 3 **Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 8`
null
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
96,241
1,046
easy level question of Welcome Tu De Stylish Co. Inside this question, we will have a waiting area filled with stones, inside which we will have a stone telling us the weight of the stone. Okay, so this is all about our input. What we will be doing in this question is that we will be playing a game in this question in which we have to tighten the two heaviest stones and let them collide with each other. Okay and the biggest stone we have will be called the bigger stone. The new weight will be the main one. We will have a small stone in both the weights and we will hit them both and the remaining weight will be our new weight. Okay, then we have to repeat this process until we have one last stone. It should not go back in the pass and we have to return it to the stone. Okay, if we do not have any stone left then we will be returning it to zero. Okay, so that's it, our question is done, now let's talk about its examples. Here he has given himself the first example of life. Okay, we have these stones. Okay, what do you have to do with this stone? First of all, you have to tighten two heavy stones. Okay, so like, we have the heaviest among these. What are the stones? One is 8 and the other is seven. Okay, so when 8 - 7 is 8 and the other is seven. Okay, so when 8 - 7 is 8 and the other is seven. Okay, so when 8 - 7 collided, what is the weight of their one. So we have added one more one inside it here. Now I don't have 7 children. Now I have a heavy stone, which one is the four, so if you subtract these two, how much does it become, you are okay, so the name is with me, the name is mine. The pass is now 4. Okay, now look inside it. What is the heaviest stone I have? 1 and 2. Okay, if I remove these two too, I took out these two, if these two collided, then what new weight have I got? It has become a forest. Now look in this 1 and 1 Now I took out these two stones, I collided these two stones, what was the weight of both of them, if it is zero, then should I add it or not, then the matter is equal, okay, so like, I have only one. The stone is inside me, which one belongs to which forest and what will happen to me in this forest itself? It will be the answer. Okay, it was quite simple. It was an example of it. If we talk about its solution approach, then what would be our solution approach? So like, we have this life era, what do we need from this life era, we need its maximum elements. Okay, so like what do we do with it, if we get it sorted, then what will we have after sorting, we have these maximum elements. How will the likes go? Our likes will come after 877. 4 will come to us again. You must have come again. One and one are ok. This is the one that came. We picked its top two elements. We picked 8 and 7. Ok. Got these two separated. So we have the answer Banta One, now what we have to do is this is our new weight, we have to put it inside this, okay what will happen at this time is that let us remove the elements of both our positions, we have to put this like our order maintain. Okay, but we cannot do this thing inside the area because if we do this inside it, we will have to do sorting, so what do we do for this, we make it by priority which is one in descending order. A will do it will be PK for us, that is ours, okay, now what we did inside this is, first of all, we get the elements added, first of all, by doing 87421 and one, okay, now whatever we took out 8 and 7 from it, okay now whatever. What difference did I have, how much did I get, now what do I do with this one, do I order it and insert it inside it on priority because then what did I have inside, 8, 4 and 2 children, I got that done on 4 and 2, so what do I have? A new weight has come, what is it, now I am inserting this tu inside it, which will run by maintaining the order, okay, like, how long do we have to do this, as long as I have this life, this is a priority. Size &gt; I have to keep Size &gt; I have to keep Size &gt; I have to keep doing this thing till it becomes one and one, okay and how can I have these two, if they get weighted by two, mains, I have one and one saved in the last, okay these two are one and one, so I will get them done. How much will be ours, how much will be the answer we get, how much will be zero, okay, then what will be our priority? 1 / 0 By doing this, it will be formed, meaning, if the children get these two separated, then how much back will we have? One, when and what will be our priority? 1 / 0 By doing this, it will be formed, meaning, if the children get these two separated, then how much back will we have? One, when and what will be our priority? 1 / 0 By doing this, it will be formed, meaning, if the children get these two separated, then how much back will we have? One, when and what will be our priority? You are equal, you are equal, its size has become 1. You can tell that I have this girl of one position, okay, so let's do this. It needs a very simple approach in the code, so why do we make our one a priority here first, okay? If it is of priority then it is ok, what will be its type, wait ok and let's name it PK = new PK = new PK = new priority stone, we have to insert them which will create its order, ok then put a folder here, anti stone is ok, where will it come from. Or we might have A from stone, okay, it has been added PK.ad and this PK of mine added PK.ad and this PK of mine added PK.ad and this PK of mine is okay, so this ad, sorry, will not come in PK, stone will come in its place, it will come here, okay, so this is our add, but now you see. The order of priority is ascending. By default, what we wanted is that we wanted it in descending order. Okay, so if we go here, then this will be the collection of min. What would I have, the largest element will come first and then that. A smaller one will come and what do I have to do now? I have to take two big stones and make them collide with each other. Okay, till when the length of the one which I have as a priority, as long as it remains bigger than the one, I will have to pay it. If you want to do it then it is okay then put a wire loop here and PK will do it okay if you have given this grater then you have to run it from one till then okay if you have to pick the first two stones then identity = PK then identity = PK then identity = PK is okay and aunty also has the stones with her. Now let's do our thing, it has to collide, whatever their difference is, why do we have to put it in ours? Okay, then what will be the biggest thing with P, A will be A - what will be the biggest thing with P, A will be A - what will be the biggest thing with P, A will be A - do it, B is okay, this will be our pulse, okay till when. This will continue as long as the size of our priority key is greater than one, okay, then we will have the last element child, that is, one element child, then it will do politics, okay, or we will have only one single element inside the stone, then this loop will not work. So what can we do directly from here, now we can return because we know that the one which is our priority will have only one stone child inside it. Okay, so give cat once and run it and see if there is any syntax error. Yours is fine, how did both of you go, do it in all, so here our today's course has been successfully submitted. Let's talk about its time and space complexity, then we have like here, why have we made it a priority. Okay, and in this lower loop, what we will be doing is inserting the element inside the priority key. Okay, so when we perform the insert inside the priority key, then our time complexity is as much as it takes us. Looks like that's what people are doing and it's okay so Mins we have n stones so we have to insert these other stunts inside this priority key so Mins our total time complexity will be at the time of inserting then it will be log n further. A would be n multiplied by log n Okay and then again we have put another loop down here inside it basically what would be happening is we would have nestons in the first one Okay in the next bar what would be happening we would be n - 1 It what would be happening we would be n - 1 It what would be happening we would be n - 1 It will be our priority's main, okay N - Then you must be back, will be our priority's main, okay N - Then you must be back, will be our priority's main, okay N - Then you must be back, okay so me our which is this old loop, it will be ours, how many times it will be running, it will be ours running N times, okay so minutes, this followup is ours in time, it will be running The time complexity of the loop was N people, okay, so basically like, if we talk, we have performed one edition here too, okay, so what will this edition be doing for us, people and times will be layer. It is okay for us to add that element inside it, so from here too our time complexity that comes out is how many N people, it is okay by doing N is our priority for this thing because there will be as many elements inside which we will check. We will get them added, the time complexity involved in adding them is in these people, so our total time complexity will be N people, N + N time complexity will be N people, N + N time complexity will be N people, N + N people, i.e. 2 A will go to us people, i.e. 2 A will go to us people, i.e. 2 A will go to us because we have got them all done. Okay, so this will be If you like, this is our constant, then how much would our total time complexity be? Oh, other people, okay, so this is our time complexity, now let's talk about our space complexity, so in this space complexity we have Here, how many N elements would have been added inside the priority key. Okay, so the maximum size of our priority key will be from this loop, which means it would have taken N special, after that when we add the elements inside this priority key. If we add N elements, then in mains we had N elements, so we removed N, that is, the top two elements, so the size of I is N - 2. size of I is N - 2. size of I is N - 2. We removed these two elements. Okay, then we removed the difference in them. If it came then N-1 size would be happening here, came then N-1 size would be happening here, came then N-1 size would be happening here, then whatever size we think, what would be its space complexity, that would be happening with us. Okay, so what would be our time and min. Space complexity will be happening. Time complexity of this court will be N people. And space complexity will be happening on. Okay, so gas, this was our solution for today. Hope you liked our solution. See you in another video till then. for bye
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
335
okay this is a this is an interesting problem okay so the thing is you start going arts then you take left run then you take left round then you take left and you continue taking left turns and you have to tell whether you have crossed the path or not so and this two means like you are going like you know two units towards north then one means one unit to its left which means going down basically and then two means again going two units to your right which means like each direction let's say so in this particular case like we are actually crossing ourselves in another example if we go like this we are not crossing it similarly in this example even if you touch actually it considers that you have crossed it because it went here with one unit and one unit so even if you touch your starting point you consider that you have crossed the limit so the problem seems pretty like you know easy to understand what we want to do anybody tried this problem I think that we go counterclockwise right and then we go the whole circle counterclockwise so my initial idea was like you know if we want to cut when we go up then heal the like the value you that we go nap had to be same our greater than no I mean let's say and about the value that we go now had to be same operator than the value that we go now similarly you know we go left and the value that we go right have to be greater than or equal to the value that we go left okay so like for example in example two we see in there okay the value that we go now and then yeah we go when we go down we go greater than the value that we're going up right so that mean that when we're not gonna meet we're not gonna cross but you can continue going that way forever so how would you it is just showing you for like you know values but you can have many such values so how would you deal with that so you understand this is the final value like you won't have one two three four this end can go up to let's see there is no limit but the problem has like it can have him I don't know too many how he said I found me for no [Laughter] yeah that was the same thing I thought upon looking I even thought it's you know it's not for hard problems because that was pretty easy kind of spiral so there are only two ways a spiral can continue without affected either it is going inwards or it is going outwards awesome and there's only an F it's going outputs at a single point in time it'll turn inwards what if it's going inwards it can never turn but I will in that I will explain that concept thanks for bringing that up because it was not my idea I did read about it I did draw some diagrams to prove myself and then explain the implementation the scenarios of this half lady half yes so anyone else tried other ideas because I did also thought about this like you know after going through the solution and we will discuss that anyway but anyone else thought about any other ideas or try to this problem okay probably not so let's try first of all the brute force way of doing this after because this is a good solution so let's talk about it later like what you would do these are all XY coordinates you have many XY coordinates so from XY coordinates you can say that I know a line right a line is basically x1 y1 x2 y2 and then you know it are details about that line and these are horizontal and vertical lines so we can figure out whether two lines are intersecting or not based on the value of x and y directly right because your line could be like this suppose this is a vertical line if this is a horizontal line I know it will not intersect if I just check these x and y-coordinates right because these x and y-coordinates right because these x and y-coordinates right because it will lies at this or if it is a like vertical line like this and there is a horizontal line I know that this will not intersect something like that so assume and this is a smaller problem to solve so assume you have this thing if a tool to figure out where the two lines are intersecting each other or not how to solve this problem is that fine like we will go to the next part of the solution can you explain so two lines if they are horizontal they will never cross each other that is fine because they are low but nice are like not parallel so one point perpendicular and another is horizontal then how can we determine whether a line crosses the other line or not yeah you can check these coordinates and these coordinates to derive that right so it's like you know after spending couple of minutes you will figure out how to do that it's not the main problem here so suppose you have this figured out now what you can do the brute force way is since you have been given all this point like you know here like something like this you can continue putting this line into some storage let's call it Q or something and every time you add one line will check whether it is crossing with the existing lines or not so if I have to draw it more like a nothing when I am drawing this line I will check hey I will not worry about this line because I know I originated from this line so it's not a problem for when I am adding this particular line this line I will check with I will not check with were like you know horizontal line because horizontal line is perpendicular I will check with this particular line I will check with this / - but this / - but this / - but and I will check with this board particular why right I because I'm keeping the coordinates and I will keep doing that till I see if nobody has crossed this we know that they didn't cross each other that's a basic brute-force approach like we are trying brute-force approach like we are trying brute-force approach like we are trying to simulate what was told without adding any intelligence to the problem oh why wouldn't we want to check the horizontal like it's like they could both on the same horizontal line right oh you are saying why okay you are saying if we were here and yeah like this so you are anyways checking with this guy right so it's all go we already yeah we are checking upward because you will catch it yeah so this way you have one solution if you draw multiple like you know examples you will figure out because while you are making it larger and larger like you know like this or a smaller you only care about last couple of the checks because see now this guy there is no need to check this guy if I am already checking this particular line because it will totally have this smallest smaller line inside it makes sense like when I am adding this line if I just add check with this line or even actually with this line this is not much like you know after a certain depth you can start to prune you're like hey don't even worry about after a depth of 5 or after a depth of 4 whatever so you will not have all the points inside your queue so your queue size is not growing like you know exponentially or linearly even like you don't have to care about every time going to all the n values inside your Q's don't go inside that just last couple of four five and you are good so your queue size then can be reduced anytime your queue size grows more than five just drop these values sounds good this is the like you know brute force approach we are talking about with some optimized and we just added this optimization and I will share the solution it's on discussed so I don't have to write code but after going through this maybe that will make you more sense so you can just go and read the solution verify if you want but conceptually is there a problem why do we need to check it with you know the previous four or five actually we could do it with the you know last parallel edge no sorry the last two last perpendicular edge I guess so you are seeing only the happy path your stuff would be like oh yeah okay but there could be multiple cases for that as well then we can't restrict to five even I got it like here now you have a different new rules yeah you are in a zone so you will have to spend some time to make sure that they actually those don't make sense like you know don't check that but that is an optimization you can always go and select all the points if time complexity allows it so that is the brute force way to simulate this algorithm right now if you are done we can go to the actual good approach or to like you know you learn from the pattern and then try to solve this problem we are great so let's clear this okay give me one minute break and then you guys can talk during that time if you have any questions and then I will be back in one minute guys so I just want to ask one question so we only have four directions to move or we can move like any directions like we have any number of yeah we can move in number of directions actually at the example show just forward you can make any sort of path you know if there are multiple even after four then we go on you know we keep on going in the counterclockwise direction with the units which ever make a balance yeah election will be four but the input can be extreme so any number of input integers will be keep coming and you need to move based on the previous direction you moved yeah so we will be moving in four directions always we are going left from north we start with north and keep going left so there are four directions and you can have any number of steps so it's not just four steps so any question on that was it Sonia yeah it's me it was me okay so do you have any further questions before we start the other approach at the beginning you mentioned this in world and a word can you yeah we are going with that approach now so let us do that why not we go with that approach so happy case like you know you start like this so what you are doing is going outwards that's what we are calling that hey if I keep going like you know increasing where value one two three four five then I will never be in a problem right because it's growing Yeah right so yeah this is one happy case if you go like that and if your input is like that then like it's assorted input suppose one two three four five six seven eight then you can say hey no problem I will have no problem I can just visit all the places I'm not self crossing so how would you determine it's like you will say that okay when do I know that I am NOT self crossing is keep going outward so if you check that wherever you are like here three and one let's look at it so three is bigger than one so it determines that you are going outward right because if three was less than one then if you because you know that you will take a right turn from wherever you stop so if I take a right turn here I will cross this line eventually or I may be trapped basically but if I go further than this value one then most likely I am going outward actually I am going so all you are looking at if I am at four I am looking at where was my horizontal last direction so from four I can look at two if I'm going behind two then I am going outward right so you keep going that I think this is the implementation detail but this is how you determine that you can go outward happy is one next happy case as someone was talking about is when you go inward so going inward means like opposite direction you start it like this you started going like this still we are not self crossing right because we are going in this particular dioxin everything is fine till suppose this was my last point I can say this is also happy path however there is a difference between being happy in this first way and the second way can someone tell me what is that we talked about it already so the guy who suggested he talked about it I think in the in word case whenever we go outward it really you know PSL crossing paths yeah that when we are going inward we are restricting ourselves that now we cannot go outward no matter what we do because we have made this circle towards ourselves what can you go from now the only way to continue is you can continue growing inward right yeah but this guy he can see what he can do like you know this guy he's growing outward and suppose he decided to go inward he can actually start a new cycle here someday does he can do right would that be the same for the outer case because you go inward then you go our but you're not crossing right from inward how would you go outward because here how would you go like what will you do here like in this point no I mean you can go you go outward but you not touching the outer edge and you go well if you are not touching other end then you are still going inward go opposite direction we can't go in opposite direction actually we have been given with that data is relational does that make sense yeah so the difference between these two happiness's is this observation that if I am coming from outward to inward it is still a good state but once I go inside an inward trail I cannot go outward I have to continue going inward so ok so that is one of observation now what can we do like you know one place where you can start doing this is you can also go inward like this right I mean just to make sure that it's not just this particular case you can also start going inward like in this particular case and whenever you go inward there are certain cases you have to look at so first of all how would you determine that you are in a now inward way that you compare your previous to previous like you know direction that am i trapped or not you can go to the code to determine that it's easy but here after you are in inward trail now your boundary is not the same see your boundary is now you are setting a new boundary for your trail basically this is the maximum now you can travel in because you are in that trap already when we were going out what we were just carrying about hey what was my previous same direction distance if I am going if I am NOT going with sir even one unit more than that I am in Auto outward trail so once you determine that you are not in that trail you have to check your boundaries okay what is my new boundary if I update my new boundary then we are again up after updating the boundaries so your update your boundary after detection it may not be required it may be required we can talk about that case also maybe you are going to this happy case so these two happy cases pretty trivial to implement as we can like you know we'll post the question solution and detecting this boundary is the crucial part of it like how you detect that once you detect that you that okay I am out of this loop and I am going to in word let's reset boundary and then just do these three step so your step is check whether you are going outward first of all outward then if not because as long as I am going outward everything is fine that's the best case and it has more leverage that I can go inward but not the other way do I need to check my boundaries check boundary because now I am NOT in my outward so check boundary after you check your boundary then you start inward trail so these three steps are there anyone has any questions or want to elaborate anything I thought like we can we check bibury when we go inward right we check the boundaries in both cases whether we go outward or inward because how would you know that you are going outward without checking the bottle you cannot determine that but when that transition happens then you now see now this area is a different rule this is not the same rule which this these guys were having when they were going outward now his boundary is like limited to this particular area right so that's why you do that check and that guy's solution I can show you and then let's if you have more questions we can just so that would be linear Wrentham yeah so exactly this is what that guy was doing it's a I have also put the reference of this code this is the code I was looking at oh nice so same thing we are keep going outward we keep going inward here and in between we check whether we need to change the new boundary or not and for that you will do these checks if you draw the like you know picture it will become evident what we mean but if anyone has any problem I can go and try to explain that to ya it is updating the input array because here he just changed his boundary this is the core point that he changed his next boundary and that's it yeah it was in a math category I guess related topics tells me math so yeah it was not any algorithm data structure problem but yeah interesting problem anyone has any questions or suggestions or anything or need more explanation oh I think we're good okay initial okay so we can discuss it now if you have time or I don't know we are over the limit of I can take a look yeah if you debug you can do that but I have already done some research so you can ask me maybe for particular example I can give you that so you can debug better we can stop recording and you know you can explain about it if we run out of time sure we can do that so we are done
Self Crossing
self-crossing
You are given an array of integers `distance`. You start at the point `(0, 0)` on an **X-Y plane,** and you move `distance[0]` meters to the north, then `distance[1]` meters to the west, `distance[2]` meters to the south, `distance[3]` meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return `true` _if your path crosses itself or_ `false` _if it does not_. **Example 1:** **Input:** distance = \[2,1,1,2\] **Output:** true **Explanation:** The path crosses itself at the point (0, 1). **Example 2:** **Input:** distance = \[1,2,3,4\] **Output:** false **Explanation:** The path does not cross itself at any point. **Example 3:** **Input:** distance = \[1,1,1,2,1\] **Output:** true **Explanation:** The path crosses itself at the point (0, 0). **Constraints:** * `1 <= distance.length <= 105` * `1 <= distance[i] <= 105`
null
Array,Math,Geometry
Hard
null
1,539
hey everyone welcome to Tech quiet in this video we are going to solve problem number 1539 Keith missing positive number first we will see the explanation of the problem statement then the logic and the code now let's dive into the solution so here I've taken the first example from the lead code website so we are given a sorted array and we need to find the ketamsing value so for example so in this input array the missing values are 1 so we don't have one here we have 2 3 4 and 5 we don't have then 6 is missing then we have 7 here but 8 is missing 9 is missing and 10 is missing right so in this list we need to find the kth value right so this is the first second third fourth and this is the fifth right so we need to return 9 here we need to return the answer as 9 right so we are going to solve this problem using binary search right now let's see how we are going to do this so initially I will be having the left and right pointers then I am going to find the middle value by adding the left and right pointer index that is zero here and 4. then I am going to divide that by 2 I'm going to get the middle value so I'm going to get 2 so my middle value will be index 2. right then I am going to find the number of missing values till my mid index so till my mid index I am going to find the number of missing values in this left part of my input array to find that I will take the mid value that is 4 and its corresponding index that is 2 I will subtract that with the mid value and I will Subtract with 1. so I'm going to get 1 here so which is nothing but there is one number is missing in the left part of my input array otherwise we can say like there is one number is missing till the mid index right so we found that the number of missing values till my mid index is 1. right from my left to pointer to my mid index middle value there is one element is missing so using this value I am going to decide whether I need to check my kth missing value in the left part of my input array or in the right part of my input array right I'm going to decide whether I need to search in the left part of my input array or in the right part of my input array using this particular missing value so to decide that I will write a condition where if my K is greater than the missing value I'm going to move my left pointer right I'm going to move my left to pointer which is nothing but I'm going to start searching the right part of my input array else I will search in the left part of my input array right so in this case k is 5 the missing value we found in the left part is 1. so we need to move my left pointer so I will move my left pointer to the index 3. right by adding 1 to my middle index value so now again we need to find the middle value so if I calculate that my middle value will be index 3. so to find the number of missing values we are going to take the middle index value that is 7 I am going to subtract with the corresponding index 3 this is the middle index then I will Subtract with 1. all right I'm going to get 3 in this case so this missing value is nothing but that is 3 we have right which is nothing but from the zeroth index till the middle value middle index the number of missing values in this cases 3. so basically if we count we have a value 1 that is missing and there is 5 is missing then 6 is missing till my middle index right that is what this 3 denotes now I will decide whether I need to search in the left part or right part of my sub array so here we have 5 as k and 5 is greater than my number of missing values that is 3 so I will move my left pointer again so this will be my left pointer and my right pointer so we have left and right pointer pointing to the same value now I need to find the middle index so I'm going to get middle index also pointing to the same as my left and right pointers so now I need to take the middle value that is 11 and its corresponding index that is 4 I will subtract that I am going to get 7 here then I will Subtract with 1. so I'm going to get 6 so there are 6 values missing from 0 to Middle index right that's what we are calculating right now again I need to check whether I need to search in the left part of my sub array or in the right part of my survey so here we have 5 and the missing value the number of missing values till my middle index is 6. so this condition fails so I will move my right pointer now my right pointer will be 3 in this case now I will come out of the loop so we know our right pointer is pointing to the index 3 I will take that index right that is 3 I will add k that is 5 and I will add 1 to it I will get 9. so 9 is the fifth missing positive number so this 3 is nothing but the right pointer is the value 3. basically left and right pointers are the indices of my input array right this 5 is nothing but the we are provided right then I am adding 1 to it I will be getting the kth positive missing number right now let's see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially I'm going to have the left and right pointer so left will be pointing to the zeroth index and right will be pointing to the last index in my array right then I'm going to write the while loop I'm going to check till my left is less than equal to my right pointer I'm going to find the middle value by adding the left and right pointers I will be dividing that by two I will be getting my middle value then I am going to find the missing value by taking the current middle value subtracting with the middle index itself then with 1. right now using this missing value I will decide whether I need to move to the left part of my input array or in the right part of my input array so if my missing value is less than my k then I will move my left pointer else I will move my right pointer right then finally I will add my right pointer and the value K and plus 1. if I do that I will get the kth positive missing positive number right I think it's fine let's run the code as you guys see it's pretty much efficient so the time complexity is a log of N and space is constant space since we are not using any extra space thank you guys for watching this video please like share and subscribe and keep supporting happy learning cheers guys
Kth Missing Positive Number
diagonal-traverse-ii
Given an array `arr` of positive integers sorted in a **strictly increasing order**, and an integer `k`. Return _the_ `kth` _**positive** integer that is **missing** from this array._ **Example 1:** **Input:** arr = \[2,3,4,7,11\], k = 5 **Output:** 9 **Explanation:** The missing positive integers are \[1,5,6,8,9,10,12,13,...\]. The 5th missing positive integer is 9. **Example 2:** **Input:** arr = \[1,2,3,4\], k = 2 **Output:** 6 **Explanation:** The missing positive integers are \[5,6,7,...\]. The 2nd missing positive integer is 6. **Constraints:** * `1 <= arr.length <= 1000` * `1 <= arr[i] <= 1000` * `1 <= k <= 1000` * `arr[i] < arr[j]` for `1 <= i < j <= arr.length` **Follow up:** Could you solve this problem in less than O(n) complexity?
Notice that numbers with equal sums of row and column indexes belong to the same diagonal. Store them in tuples (sum, row, val), sort them, and then regroup the answer.
Array,Sorting,Heap (Priority Queue)
Medium
null
438
Peace be upon you, my dear friend. How are you doing? Oh God, you will be fine and in the best condition. God willing, today we will be together. Instagram. Anna Grams is telling you that your hand is supposed to return to him all of his Instagram messages that are Anna Grams, and return them to him in any normal order. There is no problem. Yes, I am a gram of flowers. If you have the word ABC, then in this word you can change the order of its letters, so it will remain, for example, BC, BEC, CBA, or A. This means that the important thing is that these letters are the same as the letters here, but their order is different, so We call it I-gram, here, but their order is different, so We call it I-gram, here, but their order is different, so We call it I-gram, meaning this word is I-gram for this word, meaning this word is I-gram for this word, meaning this word is I-gram for this word, and I am-gram for this word, and so on, I and I am-gram for this word, and so on, I and I am-gram for this word, and so on, I mean, you do the other thing, and we call it, well, the first example is the word BPC-IBC. We the word BPC-IBC. We the word BPC-IBC. We need to take the ABCD to see how many I- need to take the ABCD to see how many I- need to take the ABCD to see how many I- grams are here for this word, and see their start index. And we put it in ours, which we will return at the end, so our word was CBEPEPEPICCD in the first letter C, the second letter B, three letters. What, this will be the part of our word, which is three letters, so I will look at the frequents of each letter and I will find that the C is present. The verse is present, so first I am a gram with us, okay. Then I will move the fingers like this, a letter forward. I mean, I will remove the si and add the letter “okay,” so this is a letter forward. I mean, I will remove the si and add the letter “okay,” so this is a letter forward. I mean, I will remove the si and add the letter “okay,” so this is a new super. So, see if it is the “ana” of the word of ours, or So, see if it is the “ana” of the word of ours, or So, see if it is the “ana” of the word of ours, or not. The verse is present, but the letter “is” not. The verse is present, but the letter “is” not. The verse is present, but the letter “is” is not supposed to be there. It is supposed to be replaced by a letter. Ours is not available with one letter like this. A.B. I will not this. A.B. I will not this. A.B. I will not move it either. Our reading is not available like this. A.B.A. is not reading is not available like this. A.B.A. is not reading is not available like this. A.B.A. is not available also. I will move it. B.A. is not available. A.B.A. is not available. A.B.A. is not available. P.E.C. I will see how many zeros, one, two, three, four, five, six, so I will move it again. We have index after P.E.C. I will see how many zeros, one, two, three, four, five, six, so I will move it again. We have index after P.E.C. I will see how many zeros, one, two, three, four, five, six, so I will move it again. We have index after zero and the last word is acd, so it is not a gram, so our answer will be zero and six, but that is the first example. Therefore, it is returned to you in zero and six. This is similar to the problem that we solved yesterday. In the second word, our letters were A, B, and B. Our solution method is the method. Our solution is that we take the reading of our second Syrian syringe and see if its size will be at first or when the wind is blown. We are doubting whether it will work or not, and we will see if it will work. We will find that it will work, so it is completely zero with us. I start moving my previous one like this and see that it will work, then we will find it will work. Another ransom will work for us and then Move the previous one like this, so the combination is useful, so the answer was zero, one, two, because there is no other letter after the b. To take a question like this, it is solved. How, like all the first things, I take my item on it. If my string S is less than my string B, this means that I will not know how to take it. B is equal to the B, ok, so I return along the irrigation line empty. Ours is supposed to have everything that was extracted from it with the same lens as the B, then I am a gram. This means that if the professor of the B is less than the one of the B, this means that it will not be useful to have it, nor exist, nor one, so the vector will return empty or The countryside is empty. After that, I make 26 letters with the Ace and the B with the S. This means that the card precedes the ri in the exponent which I hacked with the frequence of the total so that the p is all the strings of the p, but the ace is not equal to the lance of the p or the p begins with the letter until the sez of the p. The pipe is fine, after this instant is finished, it is expected that it will be present in it. Yes, it will be present in it. The first irrigation stop with the same lens of the pipe will be present in it. It will be present in it, because I am pumping up to the size of the pipe. Okay. After that, I did, or the vector whose name is this one. I will return it in the end, and I will calculate it and see that Luinsey's Ace, which expresses mine, is equal to the Frye of the B, which she expresses the String, with all of them equal. If they are equal, I will return or leave the one I am standing at, as an Index start for Al-Sabri, this is I am standing at, as an Index start for Al-Sabri, this is I am standing at, as an Index start for Al-Sabri, this is fine, and after that, I will move with the irrigation spoon, one step in front of Fahshil, who I am standing with him and I will provide a new index, which will be the i-plus size of the same size, which standing with him and I will provide a new index, which will be the i-plus size of the same size, which is me, and I will take a previous one like this, so I need this to be my start, which is the i- is the i- is the i- tab, and the second i- plus size is the same, so if I move a step, I will transfer from the i to the i-plus one, this is my start. The new thing is fine, to the i-plus one, this is my start. The new thing is fine, to the i-plus one, this is my start. The new thing is fine, so I remove the i as I did here, and after that I supply the next step along which is the i plus together, so I supply the letter that is standing here, which is the next step that I am still taking here, is it or not, if my father enters my bush and moves. One step and then the next until the last finger of suspicion comes. We have the last finger of irrigation. I will not be able to do a check on her. Why? Because I take the step, I mean, by checking the first, and then I take the step. I made a check, and then I took the step, and then I finished, so I made my calculations that the last step is counted here, which is what it is. The Ace, the Ace, is the last finger of the countryside. The Ace is equal to the Ace of the B, so at that time the Ace, which is the big one, is the Ace, and when it finishes, it's fine. But that's all that's simple. I mean, how will our Ace remain? So quickly, we'll review what we said. I'll still have the first one. This one is the S. I'll take the A and get his. Whoever takes the BB will get the first country finger, the name is equal to this size, and this will be the S- name is equal to this size, and this will be the S- name is equal to this size, and this will be the S- Frequin. After that, after that, you will doubt whether it is equal to the CB-Frequin After that, after that, you will doubt whether it is equal to the CB-Frequin After that, after that, you will doubt whether it is equal to the CB-Frequin or not. After you have checked, if they are equal, then what is left here will not be. Okay, if they are not equal, then they will not drop the start. After I finish my check, I move one step forward by removing the start index and adding its place, so that I move a step by adding it to the Frequeen CS and then I compare the Frequency and the Frequeen CP. After I finish the spot, what happens to the last step that I made a check on, so I work on it outside immediately, so I say Is the Frequency S equal to the Frequency B or not? If it is equal. There will be another. I will show it to us. What is my start and will it be the A-S? Mains of the A-S? Mains of the A-S? Mains of the B is there or not? If it is there, I will make it for it. If it is not there, if it is not cold, I will not do anything for it. And in the end, it will remain. This is how our issue has been solved. I hope the explanation will be easy, and I hope you understand. If there is anything you can write to me in the comments, and I will see you, God willing, next time. Peace be upon you.
Find All Anagrams in a String
find-all-anagrams-in-a-string
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** s = "cbaebabacd ", p = "abc " **Output:** \[0,6\] **Explanation:** The substring with start index = 0 is "cba ", which is an anagram of "abc ". The substring with start index = 6 is "bac ", which is an anagram of "abc ". **Example 2:** **Input:** s = "abab ", p = "ab " **Output:** \[0,1,2\] **Explanation:** The substring with start index = 0 is "ab ", which is an anagram of "ab ". The substring with start index = 1 is "ba ", which is an anagram of "ab ". The substring with start index = 2 is "ab ", which is an anagram of "ab ". **Constraints:** * `1 <= s.length, p.length <= 3 * 104` * `s` and `p` consist of lowercase English letters.
null
Hash Table,String,Sliding Window
Medium
242,567
1,663
Hello Everyone Chaturvedi Arvind Small Electronic Product Must Subscribe Till 2030 Vriddhi Misal Issi Ke Sikud Se Zameen Isse Idli 476 subscribe The Channel Please subscribe and subscribe Amit Ko WhatsApp Madding Dos Clear Loot Certificate Subscribe To Turn Off Side This big ass may stringers are going to be of science fair and first appeals are completely with this Vikram University introduce characters with district Jhajjar venues of such updating has happened twice of characters from myself just degree centigrade value ticket I told here And on this gray shades come that pics are given a picture feature behind an initiative minister can make and midstream check post - 3test post - 121 who - 3test post - 121 who - 3test post - 121 who is it a motu patlu aur sunao bhaiya appointed decrement the value of 125 every time e agree with you Aaj Tak And Narao 10 Cloves Cardamom Trade Center K B Complex Than Twenty 20 Minutes You Can Do Subscribe And Fixed For Rallies Simply Updater Character The Volume To The Giver Who Continues Subscribe To Unite Spot Joint And Narao Thursday Depart Finally Gravitation Rather E If Loot is a good person then finally Bigg Boss Mediclaim extremely beautiful replace characters no position and this electronic Loot number force
Smallest String With A Given Numeric Value
detect-cycles-in-2d-grid
The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on. The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string `"abe "` is equal to `1 + 2 + 5 = 8`. You are given two integers `n` and `k`. Return _the **lexicographically smallest string** with **length** equal to `n` and **numeric value** equal to `k`._ Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order. **Example 1:** **Input:** n = 3, k = 27 **Output:** "aay " **Explanation:** The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. **Example 2:** **Input:** n = 5, k = 73 **Output:** "aaszz " **Constraints:** * `1 <= n <= 105` * `n <= k <= 26 * n`
Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
1,071
hi guys and welcome back to the series um so we're going to be looking at um this question which is uh greatest common divisor of strings um let me just expand this first so for two strings s and t we say t divides s if and only if s = to t + t divides s if and only if s = to t + t divides s if and only if s = to t + t plus blah so we should be able to concatenate T indefinitely uh to get S right um and then given two more two strings uh string one and string two return the largest string X such that X divides both strings string one and two yeah and then we given a couple of answers uh sorry examples which is string one is ABC string 2 is ABC so the greatest common divisor is ABC uh and then we have another one which is ab and uh ab and then the final one is lead code okay um so the first thing that comes to my mind when I think or when I see greatest common divisor is in maths there is a way of calculating the greatest common divisor of uh two or more numbers so probably the first thing that I would probably do is try and find out what the common uh greatest common deviser is so the algorithm itself is uh relatively simple uh so if we use something like the ukian AL algorithm we should be able to find the uh GDC for uh two numbers so how this normally works is if we are given two numbers so in this case let's take the length of the strings as two numbers so for example one we have length of string uh six and length of string three right so we keep on um kind of uh getting the remainders so like we keep on doing a module until we get zero as the modulo um so in this case if we do a modulo of 6 and three we get zero right so the smaller number is uh the g c d is equal to 3 right uh if we get two more numbers so if we look at example number two which is 6 and 4 so 6 and 4 we do the modulo of this is going to give us two right so then we take the smaller number which is four and to the modulo with the remainder which is two which will give us two uh sorry which will give us zero right so our GDC gcd is equal to two right uh and then if we can look at a random example so if we take uh something like uh 24 and uh 21 right so if we take the modulo of this so 24 modul 21 is going to be 3 right 21 modul of 3 is equal to Zer right so our G CD is equal to 3 right so this is relatively simple to implement in code as well um so let's uh let's go to the code I guess um so the first thing that I want to do is uh calculate the GD gcd so I'm going to create a new function over here called calculate uh G CD and uh this will take in two numbers so num one and num two right and we can actually just do this uh recursively um which is going to be I think simpler um so I can just do um something like big num equals to whatever the max is between num one and num two right uh and then I can do small num and make it equal to the Min between num one and num two right so this will kind of give me the two uh numbers that I'm looking for but then like in big and small um and then what we can just do is let's think of the base case so the base case is whenever the remainder is zero right so if um if the remainder is zero that should mean that the small value is going to be zero so if uh small num modulo um sorry is equal to zero right then we just want to return the whatever the bigger number is um and I think it will make more sense after I uh complete the next line which is just return um calculate and GCT of um small num right and the big num modu small num okay so if we look at our example so if our big num was 24 right uh and our small number is 21 so we're going to come over here and we're going to pass in 21 as our small num right and our big num is going to be big num which is 24 modul 21 which is going to be three right so uh 21 and three get passed down so again we get it split up um this will be false and then we come over here so now the smaller number will be three uh and then and the bigger number which is 21 modul of three which is going to be zero right so uh we pass that down this time small number will be zero and we can return back three I hope that makes sense um okay so we have this helper function and what we can do is we can calculate the GC D of the two strings so calculate GC gcd of string 1. length and uh string 2 dot length right so the reason for kind of uh doing the math do Max and Min operation over here because we never guaranteed that uh string one will be bigger or string two will be bigger so this way at least we kind of um we're kind of going over that edge case if in the event that string two is bigger than string one we are still getting the correct values okay so once we have the greatest common divisor right that means that this the bigger string and the smaller string can come down to the Min the minimum length of um gcd right so what we can do is we can do kind of like a substring um so we can do a const gcd string and we can get a substring of either one so either we can do a substring of string one or string two doesn't really matter so I'll just do string 2 do substring um and we want to start from the zero position going all the way till the gcd position right so this should give us like a substring that should be equal that we should be able to um add to itself and kind of get the biggest string so let's try and test string one first so I'm just going to create a new variable called string one test right keep it equal to an empty string and I will do for let I equals to z i less than string 1. length umide by gcd right so if the if string one is length of uh six and our gcd is three right this should give us two iterations right um and then i++ and what I want to just do is uh i++ and what I want to just do is uh i++ and what I want to just do is uh string one test Plus equal to gcd string right that should give me a string that should be equal to the initial string one that we started off with so if uh string one test is not equal to string one then that means that um our gcd string didn't really match so in that case we can just return an empty string and we kind of want to do the same thing for string two so I'll just copy and paste this and this time around it will be string two um string two test we going to string two length and we are adding to string two test testing string two is equal to string to test right and if none of these things fail that means that we actually have the correct answer so we can just return gcd string right so let's try and run this calculate GC string gcd calculate gcd is not defined oh sorry typo um all right awesome that passes the test let's try and submit it to all the other cases awesome now um there's probably a few things that I was thinking of when I was um kind of quoting this up is that uh this these tests might actually be uh redundant to some extent if we can just check if string one plus string two is the same as string 2 plus string one right so we can actually just put in uh a test over here I'm saying that string one um plus string two is equal to is not equal to sorry string two + string sorry string two + string sorry string two + string one then we just want to return an MD string right so um how this will work is like if you look at string one and string two right if you con concatenate them we'll get ABC three times right and if you reverse the order so if you do string two first and then string one we would still get the same answer right that's not the case for like lead code right no matter how you concatenate it you will still never get the same answer so that will at least check if there if it's possible to calculate if it's possible to get um a gcd string for both the strings right so in which case then uh all these tests kind of become redundant right there's no point in having them and instead we just want to calculate the gcd uh and then create the substring and just return the substring so let's try and test this uh as expected that passes everything and the performance is also much better all right thanks guys um and uh thank you so much for supporting this Channel and this series I really appreciate everyone leaving their comments uh leaving their likes and also subscribing and hope to see you in the next one cheers
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
261
hey everyone in this video let's take a look at question 261 graph valid Tree on Lee code this is part of our blind 75 list of questions so let's begin so this question is actually a premium question and that's why we're doing it on the lint code website and why the number here is different but otherwise the question the test case is on the solution are the same so let's take a look so in this question we are given nodes labeled from 0 to n minus 1 and a list of undirected edges which means each Edge is a pair of nodes and I want to write a function to check whether these edges make up a valid tree we can assume that there are no duplicate edges will appear in edges since all the edges are undirected 0 1 is the same as 1 0 and thus will not appear together in the edges okay so what does this mean so let's take a look we'll go ahead and copy these examples here and again this website is where we will do our premium problems because they allow us to do them for free so we'll do them here okay so it looks like we're given an adjacency list to start off and the graph is undirected and what we are asked to do is determine if this based on the adjacency list if this graph is actually a valid tree or not now what is a valid tree right because they haven't really told us what is a valid tree so I'll just go ahead and tell you what is a valid tree so a valid tree satisfies two conditions first of all it satisfies I guess a couple actually um it satisfies first of all nodes are connected and I'll explain what that means in a second it also satisfies that there are no Cycles okay so what does this mean what it essentially means is that let's say we had three nodes right let's say we had three nodes oh take a look here okay so let's just say we have three notes right we have three notes what does it mean first of all that all the nodes are connected what does that mean well it means that from any node you could visit any other node so what it means is that from this node over here and maybe we can give these nodes names just to kind of make them easier to understand it means that you can reach any node from any other node so basically something like this right this is an entirely valid tree why because it is connected first of all and you might ask how can we reach like two from three right well notice that these edges are undirected so really if you want to kind of think of this in terms of a directed graph this would kind of be like an edge here and then an edge over here similarly an edge here and then an edge back here you can kind of think of it as that one okay so we now understand that the graph is connected now what about the second Point well it means that there are no Cycles so what does it mean when there's no Cycles it means that we don't have anything like this a cycle over here because what this would mean is like we could just infinitely go maybe somewhere here and then back here Etc there should not be any Cycles you still should be able to visit every node from every other node but there shouldn't be any Cycles to add on to kind of like the first point about the graph being connected an example of an unconnected graph would be something like this like let's suppose we don't have these two connections over here so then what do we have well we have three nodes before one we can only reach two and from two we can only reach one we cannot ever reach this three so in this sense the graph is unconnected okay so we have these two pieces of information that make a valid tree now you might ask that if the tree over here is actually undirected then it means that there are Cycles right because if you think about it we'll have an edge over here and we'll have an edge like kind of like also back here so their Cycles here right well technically there are Cycles but when we are approaching this problem we're not going to refer to this as a cycle so if we see an undirected edge we will not for example from one if we visit Three then we will not visit one again because technically although this is a cycle the graph is supposed to be undirected so it technically this is not a cycle in this case so we're not going to be thinking this in terms of a directed graph but in terms of an undirected one but when we're doing our coding it will still be in terms of a directed graph but we will make it clear that this is not a cycle so that's just one point I wanted to point out first of all okay so if you think about it the only thing we really need to calculate or you need to determine is that these two conditions are true if they are true then I know that my tree is a valid tree or my graph is a valid tree otherwise it's not so it's actually easier to determine the opposite so we will determine if all of the nodes are potentially not connected or potentially if there are any sort of cycle and if any of these conditions is false then I know that it's not a valid tree okay so how might we go about doing this well let's take a look at this first example that we have here I've actually drawn it right over here so we can see that 0 is connected to one and then technically one is also to zero but I'm showing it as an undirected edge here and then zero to two and then zero to three and then one to four we can see here that all of the nodes are connected from node from any node you can visit any other node we can also see clearly that there are no Cycles now what can we understand from this well we can understand that if we were to Traverse through our tree and maybe we did a DFS call from this node over here this zero node over here what can we understand or we can understand that we can reach every single node right and really it doesn't matter where we do our DFS call from we could maybe even like do it from over here but if the graph is truly connected then what it means that from any one of these nodes we should be able to visit any one of these other nodes so really if I do a DFS call then I should be able to visit one two three four five nodes and it doesn't matter like where I do it from I could do it from the three I could do it from the two we'll just maybe do it from like one of the indices because for example if it wasn't connected maybe if this Edge wasn't there then from any of these if we did it then we would just be able to visit four maybe if we did it from here we would just be able to visit one but we would definitely know that we would not be able to visit five so in that sense we can just do it based off of Just One of the nodes we don't have to go through every single node when we're doing our DFS call okay so that's one thing we know now what is another thing we know another thing is that we want to make sure there are no Cycles so how can we make sure there are no cycles and that's actually seems to be the problem in the second graph you can see that there's a cycle between one three and two and then so here's the cycle even though it's completely all connected there's still a cycle over here okay so maybe we can also while we're traversing through this we'll determine if there's a cycle and if there is a cycle then maybe we can just return true so our helper function returns true and so we know that it is not a valid tree so our main function will return false now how do we determine whether there is a cycle well let's take a look right if we have a DFS call what do we need a DFS well we need like a visited set right like we need to keep the set of nodes that we visited and we know that if we visited another node that we've already visited in the past then there is a cycle so what will happen here is we'll visit the zero then we'll go ahead and visit the nodes that zero is connected to which in this case is just one and not from one technically we can visit zero again right because as I mentioned it's an undirected graph but we'll be treating it as directed in terms of the adjacency list so technically this is possible so even though this is not a cycle would attempt to visit this so how can we get around this well maybe like when we are visiting when you're doing our DFS call we can just pass in like a parent parameter right so for example when one is here the parent will be zero so when I'm going through the neighbors of one if it is a zero then I'll just skip over it right but for any other neighbor for example the four over here I will go ahead and process it okay so let's say we do that so what happened at this part so once we do this in our visited set we have the zero we have the one and then maybe here I have my four so I'll go ahead and add my four right and notice I'm not popping from the visited set right I'm not popping from the visited set I just want to keep adding on to it because this visited set is going to essentially keep track of all the nodes that I can visit so then we'll go back and then from here maybe I can go to the three so add in the three maybe I can go to the two from the three so add in this and notice that when I'm on the two I'll try to visit Three again because but because it's my parent I won't visit it but then I'll try to visit the one here and I can actually see that one is my what one isn't my parent but I've already visited it in the past and so what this means is that there's a cycle so even though we visited all of the nodes here the second condition here will fail and so that's how we'll determine that it's not a valid graph okay so let's take a look at how we can do this in the code and we've done a question in the similar in the past to determine whether something is a cycle or not so I believe that question was core schedule so we'll just take a look at that question um or take a look at that question if you need a refresher but let's go ahead and begin and we'll see like how we can approach this problem here so I don't actually know about the constraints over here so I can maybe just return something like if not edges then we'll return true because an empty graph is also a valid tree now what else do we need well now I want to essentially do my recursive call so that I can determine two things well I want to determine the total number of nodes and whether there are any Cycles or not so I can do something like for example let's say we have my helper function and what am I going to pass in well let's see in my helper function what I want to know is I want to know the current node right like one of the nodes and actually I guess even before this we have to create our adjacency list right so let's go ahead and do that so we'll create a list where like zero goes to one and then one goes to do and the way we do this in um in lead code is or import a default dictionary and I'll have my adjacency list as the default dictionary of list and then I would do four let's see ft so this means like from two um in edges then I will create this connection here which means that the adjacency list of f appends to T and then something like this so all this is doing is like for example if this was 0 1 then here I'm creating the edge that goes from zero to one and then here I'm creating from one back to zero so that's all I'm doing here okay so what do I need well I need to know like which node I'm starting off at right so maybe I can just start off at like a node here I need to know my visit it says so I understand all the nodes that I've visited in the past I need to know like my parent to make sure I don't visit my parent again do we need anything else I don't think we need anything else so let's go ahead and start this and see if we run into any problems but okay so what's the first thing we can do well first thing is that like when we first of all arrive in the DFS call then we know that we have now visited this node so I can go ahead and add this and visitor will be a set so I will add this to my I will add the note to my set okay so now what well now I need to essentially go through all of my neighbors or all of the items that I'm connected to so I can do for neighbor in adjacency list at node right and first thing I would check is I would check if neighbor is equal to parent then I would just skip over this right because I don't want to visit my parent again so I will just continue here otherwise well otherwise I want to see if I can visit this right so I can check if a neighbor in scene so if a neighbor is in scene what does this mean well it means that we visited this neighbor before but it's not actually like from my parent right it's actually not my parent so what this means is we have a scenario something like this maybe we are at the two over here and I want to see if I can visit the one and one is not my parent is actually three but here I can see that if I try to visit the one then it'll form a cycle so in this sense here I'll actually return true and this indicates a cycle okay otherwise what well otherwise I can go ahead and I can visit this node right so I can do self.helper and I'll do node visit it self.helper and I'll do node visit it self.helper and I'll do node visit it and then what is a parent well the parent is actually just my current node at this point right so that's my parent and so this is all we need to do for this recursive Co here so what can I check well I need to Define some variables here so obviously visited is my set and I'll pass in a couple of things so I'll pass in node as 0 and then I'll pass in visit it and my parent maybe the zero parent because for zero like um we want to know what the parent is right even though it technically doesn't have a parent so we need to define something so maybe we can just because this goes from zero to minus one maybe we can just Define this as like negative one here so like this condition will always be false for zero because none of the neighbors are negative one so we don't have to worry about that but what can we check here so what would this return well this will return whether there is a cycle or not now one thing I forgot to do is like if we do all of this and we don't ever return true then we want to return false because this indicates there is not a cycle so we can do something like a cycle and then I can do if is psycho then I'll return false indicating that this is not a valid tree if there isn't a cycle then I want to determine whether the graph is fully connected or not that can return length of visited which means all of the nodes that I can visit whether this is equal to I guess n is at n here so n is 5 yeah 0 or 1 yeah so five it would be five right because we have five nodes so I guess this would just be n and so then let's go ahead and run this code okay and I'm getting adjacency list is not defined I guess I didn't pass it in um yeah maybe I'll pass it in at the very end first now let's take a look what am I getting seen is not defined um yeah I just call it a scene or I could have visited I always call it a scene call it scene then okay so it passes now let's take a look and okay so what am I getting so I'm getting two and then edges is empty okay so I guess we have to change this condition here if not edges um and I guess n is equal to zero then this is a valid scenario right then this is a valid tree uh we can also check uh if not edges maybe we can combine this let's just do if not edges and then if n is equal to zero then we can return true else I guess in this case we would return false right because it means that we are given some sort of edges but um like it means that we are not given any edges but they're actually nodes so in that sense like there is no connection so we can take a look at that and just more test cases so this means that n is zero and then okay um yeah I guess that's one more thing uh L if n is equal to one then we want to return true why because in this case if there's just a single node then that single node in itself is a valid tree so I guess this is the case for like uh no nodes entry this is the case for uh one node entry and this is the case for more nodes and perfect so we arrive at the solution okay so what is the time and space here so the space if you think about it at the worst case if we want our solution to be valid then we'll visit every single node so that would be o of n because our visited scene will be o of n like it will contain nodes and for our time complexity basically we're going through every single one of these nodes but we're just kind of visiting them once right so assuming it's like the best case so we're just visiting it like once here um even in the worst case we just visit it once but we'll understand that there's a cycle but essentially we're just visiting it once so in this case it's also like a o of n you can think of it as o of edges plus vertices or like just o of n in terms of like the number of nodes okay so that's what we have here we might actually be able to simplify this I think um because I don't know like how the edge cases like will be passed in here but I think we have this which is fine so thanks for watching
Graph Valid Tree
graph-valid-tree
You have a graph of `n` nodes labeled from `0` to `n - 1`. You are given an integer n and a list of `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between nodes `ai` and `bi` in the graph. Return `true` _if the edges of the given graph make up a valid tree, and_ `false` _otherwise_. **Example 1:** **Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[0,3\],\[1,4\]\] **Output:** true **Example 2:** **Input:** n = 5, edges = \[\[0,1\],\[1,2\],\[2,3\],\[1,3\],\[1,4\]\] **Output:** false **Constraints:** * `1 <= n <= 2000` * `0 <= edges.length <= 5000` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * There are no self-loops or repeated edges.
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
207,323,871
1,189
hey what's up guys think white here the second coding stuff on twitching YouTube check the description for all of my information I do I'm putting a lot of stuff on my patreon if you want to check that out pulling a new stuff every day and if you want to reach out to me patreon or discord those are good places I try and get back to everyone this is the looks like a newer problem maximum number of balloons not too many likes yet given a string text you want to use the characters of text to form as many instances of the word balloon as possible such a weird praça is a weird problem but you're given a string text so like any string we're given pretty much any string I think they're all yeah lowercase letters only this is it right here but the text could be really long right and what we want to find is as many instances of the word balloon so random but um you can use eat it makes me think of balloon tower-defense me think of balloon tower-defense me think of balloon tower-defense I don't know if you guys play that but you can use each character and text at most once okay so we can only use each character once and we want a form balloon return the maximum instances of balloon that can be formed okay so it breaks it down here for you a nice color coding so if we're given this we only have all the characters of the word balloon once so we return one when we look at this we have all the characters of balloon twice if we return to leak code has none so we just earn zero so um I mean it has an O but in and out but not even close so how do we do this I mean the it's pretty easy honestly like this is a really easy problem I think the answer is like instant for anyone who's done like string problems before it's probably one of the easier easiest ones honestly all I did is it's a linear constant space solution optimal solution just you may catch our counts array of size 26 because it's lowercase letters and if you don't know this strategy if you're new to algorithms you make an array this is an integer array that represents the count of each character in the string or given so in this case for example we have four else we have four OS we have two ends two ways two beats we want to count the number of each character there's no Z's so Z would have a count of 0 so this array has 26 for the 26 letters in the alphabet and what we do is we loop through the string our string I less than text out length I plus and we get access the current character text char and I and we subtract a 2 convert it into an index I'm sorry for hitting the Mike we the current character for example if it was a it would be a minus a which is 0 so what it does is it subtracts the ASCII value you subtract the current letter in this string we're given by a to get the corresponding index of that letter in the array or in other words the alphabet a minus a is 0 so we would access char accounts of 0 for position 0 because it's the first a is the first letter in the alphabet and then what we do is we see an a ok we increment the count so it would be 1 in that spot now so when we see a B it would be B minus a that would be 1 then we'd access to our counts of 1 the array of letters because it's the second letter in the alphabet you increment the count etc so at the end of it we will have this array filled with each letter index in the alphabet and the corresponding when we access the index and the alphabet through this array after we loop through this and fill it up and increment the counts we will have a count of each letter in our string which is good because all we want to do after that is what we want to do is we want to take we know how many B's we have we know how many a is we have we know how many O's we know how many letters we have to work with and we want to take the lowest it's almost like lowest common denominator if we have a string like this balloon you can see right here we're missing an N at the end so we can only make it once that's just from looking at it right so we would fill up this array and what we want to do is we want to look through and it's like oh look we have to be so we can make two balloons we have two ways we can make two balloons we have we do L divided by two because we need for Alice to make two balloons because there's two L's per thing so each part of balloon we want to check for the count of and then we'll take the minimum of everything because the minimum of everything is the answer for example everything we could have two of everything right we could have two sets of vowels two sets of those two ways to B's we could have everything to make two balloons but if we only have one n then we cannot make two balloons right this all goes to waste because you can't make two balloons so the maximum instances of the word balloon is the minimum of each part of the balloons occurrence so that's all you got to do we will just write that out really quick the minimum is going to be equal to char accounts of 1 which is the letter B that's the occurrences of the letter beat in our string and then we will keep updating it with the math I'm in of the current minimum and now char counts what's the next letter a so that's zero in the alphabet so the minimum of be the minimum of a and then we have BA L so L is the 11th letter in the alphabet and we divided by 2 because L occurs twice in each instance of balloon so we divide by 2 for repeating characters because we need four else actually so L o / - again need four else actually so L o / - again need four else actually so L o / - again because we need two O's and O is MN no so I think that's 14 and then n is the last letter so we need n which is lMNO so right before o which is 13 and you don't divide by two because it's only one and that's it you just take the minimum of each part and that will give you know kind of like a lowest common denominator type deal with the string on chart counts sorry guys can I ever do a problem without messing up the syntax you know at one point so there you go optimal solution very intuitive very easy tried to walk through it because I know I think there's a lot of people that I explain things and they're like oh that's easy go faster but then there's some people that like just don't get it even though I make it very clear so I try to slow down like for those people but I know I get annoyed when people don't go fast enough in these videos so I don't know who I want to really target I'm trying to stay a little bit in the middle here so bear with me if you're think I'm going to slow bear with me if you think I'm going too fast I think more people want me to go faster than slower but um thank you guys for watching I really appreciate you guys thanks for everyone that supports the videos channels growing really well so um that's it really fun problem very easy just perfect problem to understand a concept like this and yeah that's it so I will see you in the next video see ya
Maximum Number of Balloons
encode-number
Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible. You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed. **Example 1:** **Input:** text = "nlaebolko " **Output:** 1 **Example 2:** **Input:** text = "loonbalxballpoon " **Output:** 2 **Example 3:** **Input:** text = "leetcode " **Output:** 0 **Constraints:** * `1 <= text.length <= 104` * `text` consists of lower case English letters only.
Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits.
Math,String,Bit Manipulation
Medium
1070
2
hi everybody welcome back and thank you so much for all the support that you have shown on my previous videos i am very thankful for that but if you're new here my name is patricia vacrolla i make videos about lead code solution and system design concepts if you are interested in that sort of things make sure to subscribe and hit the bell button this question has been previously asked in a google and amazon interview while you are given two non-empty linked while you are given two non-empty linked while you are given two non-empty linked lists and it represents two non-negative and it represents two non-negative and it represents two non-negative integers the digits are stored in reverse order and each node contains one single digit we have to add the two numbers represented by these linked lists and return the sum as a new linked list now we can assume that the two numbers do not contain any leading zero so let's think of a brute force solution if we were to add two numbers we would start by adding these two numbers first and then add the rest of the numbers in this direction but since the linked list represents the number in reverse order our number 342 is represented as 2 4 3 and similarly the second number 465 is represented as 5 6 4. so in this case we still want to add these two numbers first and then add the numbers in this direction so when we add these two numbers we're going to need a place to store that so let's create our new node and let's call it result let's say list node result equal to new list node and let's point it to -1 list node and let's point it to -1 list node and let's point it to -1 we need to return a linked list we will also need a pointer to traverse through the linked list so let's go ahead and create that list node let's call it temp and let's make that pointer point to the same place as result we can continue to add these two numbers as long as list one or list two have value so let's go ahead and write the loop for that while list one is not equal to null or list 2 is not equal to null when we total these two numbers we're going to need a place to store that so let's declare a variable called sum equal to zero so sum is equal to l1 dot val plus l2 dot val when we wrote this piece of code we created a new list node with -1 here we created a new list node with -1 here we created a new list node with -1 here and we called it result and then we also created a temporary pointer to traverse through the list and pointed it to the same node now we need to add this total into the result list so let's create a new node and that will have the sum y plus two seven so let's do the coding for that new list node of sum so we've created a new node with that and we want to link it with the existing result node so we want to make this connection now so we will say temp dot next is equal to new result node so now we got this connection now we want to change the pointer temp to this node so let's go ahead and write temp is equal to temp dot next now you want to add these two numbers okay so you no longer want to point the l1 to here you want to make that point to this node and similarly the l2 should now point to these nodes so l1 equal to l1.next l1 equal to l1.next l1 equal to l1.next and l2 equal to l2 dot next so because l1 and l2 both have values none of them are null so it will go through the loop again and try to add those two numbers in this case sum is equal to the number 4 which is l1 dot value plus the number 6 which is l2 dot value which is equal to 10. so now in sum we have more than one digit that means we can we only need this portion to be added into the result node and we have to carry this portion into the next step where we do the addition so let's call it carry now this is not accommodated in our existing code so let's go ahead and modify our code to account for this scenario we will check if sum is less than or equal to 9 then our existing condition will work so as you can see sum is an integer type so we cannot just simply take one character out unless we convert that into a string so let's go ahead and do that string value of sum dot character at 1 that will give us this character so now we have extracted the number 0 from the integer and we need to add that into a new node but if you can see that node also contains the value integer so we now need to convert it back to integer so i'll say integer dot parseint and then i'll supply this value now integer.parsein takes string as a integer.parsein takes string as a integer.parsein takes string as a parameter so we now need to add an empty string to convert this character into a string now we have converted 0 into the integer but we also need to create a node and add that 0 here so let's say new list node and pass this value to the node so now we have created this portion but we now want to link it to our result so to do this portion we will say temp dot next equal to the new node we also want to change the temp to point to the latest node temp equal to temp dot next so now we took care of this portion we still have to now take care of the carry so let's declare a new variable int carry equal to zero and let's say carry is equal to so to set the value for carry we need to extract the value 1 from the integer sum exact same way how we did for zero but the only difference is that this will be the character at zeroth index so now we have set the carry rest of the code l1 equal to l1 dot next which means now this pointer is now pointing at number three and this pointer is pointing here okay so now l1 is pointing to the last node and l2 is also pointing at the last node that is because of this code now l1 and l2 none of those lists are empty so the code will still go back to our while loop and it will try to do the total of l1 and l2 but we also have to add the value of carry so we will say carry plus l1 plus l2 so now when we add sum is equal to carry which is equal to 1 plus the value of l1 which is 3 and the value at l2 pointer which is 4 and so the value of sum is now equal to 8. so our sum is still less than nine so we will create the new node of sum so let's create a new node and the value of sum is eight and then the temp dot next will create the link between this two nodes and then temp dot next will change the pointer from here to point to the latest node now let's look at this code now l1 will move on to the next pointer which is equal to null and then l2 doesn't have next element so l2 is now also pointing to null so l2 is now pointing to null and l1 is also pointing to null so the condition in the while loop is no longer satisfied so it will exit the loop but if you look here our addition is also complete so this is our result right now but if you remember we added a dummy node in the beginning so all we need to do right now is to return this list so we can do result is equal to result.next and return that equal to result.next and return that equal to result.next and return that value so now we have solved this particular example but we haven't covered all the edge cases if the list one and list two have two different sizes meaning if we had one more element here then our code will not work in that case let's go ahead and traverse the code and find our problem so list1 is now null so this condition is no longer satisfied but list2 is not null so this condition is satisfied so sum is equal to carry plus list one value plus list two values so sum is equal to carry which is equal to zero right now and value for list one which is equal to null plus the value for list two which is equal to one now your compiler will not be able to add the value null in a mathematical operation so your compiler will not like this let's create two variables int val 1 initialize it to 0 and int well 2 also initialize that to 0. now well one equal to now we're going to use a ternary operator and we're going to check if the value of list one is null then we're going to set that to zero that way our mathematical operation goes through so well one equal to l1 null then we will set it to zero otherwise we will set the l1. well okay so this is a ternary operator what we're doing here is evaluating this condition if the list one is null then value one equal to zero so this is the true condition and if this condition is false then the val one will receive the value of l one dot okay and we're going to do the same thing for well 2 equal to l2 equal to null question mark 0 colon l2 dot well we don't want to add this well use directly here so we're going to say well one and well two so now this will become zero plus one and your mathematical operation will go in fine now the value of sum is equal to 1. so this is our result when we did not have the value 1 in the list 2. now our value of sum is equal to 1 so some less than or equal to 9 condition will be satisfied and it will try to create a new node with the value sum so right now sum is one so it will create a new node with value one now temp dot next equal to the new node that will create a link from this node to this node and temp equal to tem dot next will change the temp pointer from here to point to here this else portion will not get executed and we will move on to the next statement l1 equal to l1 dot next so l1 is already null so when you try to go next of null your compiler will not like that and that's why this statement will result in error so we're going to do the same thing that we did for value 1 and value 2 with the list1 and list2 here as well before we assign the value we will check if l1 is already null if l1 is equal to null then we keep the value null itself and if it's not null then point it to the next node and we are going to do the same thing for the l2 equal to null if it's null then leave it pointed to null otherwise move on to the next node so there is one more edge case that we have not covered and let's look at it with this example let's say you have already done this result node it's pointing to minus one and then it's pointing to the node four and then it's pointing to the value eight and then now you have value nine and three okay so let's go ahead and traverse through the code to understand where the code will go wrong so while list one has value and list2 has value so the condition in the while loop will satisfy in this case val 1 will become 9. and then val two will be three and then sum is equal to carry which is zero plus val one which is nine plus val two which is three okay so now this will return the value 12. now sum is equal to 12. now 12 is not less than or equal to 9. so this condition will not satisfied so we will go here on this portion where we will take this character and add it at the end of the result just like how we did in all the other past cases with this statement temp will point to the last node so this will be our carry now we will get out of the else condition and then move the pointers l1 2.2 the and then move the pointers l1 2.2 the and then move the pointers l1 2.2 the next node which is null we will also point the l2 pointer to null now the code will go back to executing the while statement and it will evaluate that condition where l1 is also null and l2 is also null so none of this condition will satisfy so we will get out of the while loop now the next statement is the returning result we still have a carry that is outstanding okay so this is not a correct result we still need to add the value 1 into the result list so let's go ahead and account for that one let's see if carry is greater than 0 then temp dot next equal to new list node off carry also remember one thing when you add carry into the sum you have to reset the variable of carry now let's go ahead and submit our code as you can see our result has been accepted and if you want to further optimize this code you can change the if else condition using the two mathematical operations that i have listed in the comments below if you were able to follow what i was saying say yes in the comments below and give me a thumbs up and if you're not able to understand say no in the comments that way i know where to emphasize more in the next videos if you want to do more leeco problems here is the playlist and if you want to do system design concepts here is the playlist for that thank you so much for watching
Add Two Numbers
add-two-numbers
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. **Example 1:** **Input:** l1 = \[2,4,3\], l2 = \[5,6,4\] **Output:** \[7,0,8\] **Explanation:** 342 + 465 = 807. **Example 2:** **Input:** l1 = \[0\], l2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\] **Output:** \[8,9,9,9,0,0,0,1\] **Constraints:** * The number of nodes in each linked list is in the range `[1, 100]`. * `0 <= Node.val <= 9` * It is guaranteed that the list represents a number that does not have leading zeros.
null
Linked List,Math,Recursion
Medium
43,67,371,415,445,1031,1774
1,311
hello everyone so in this video we'll go over one more problem from lead code the problem name is get watched videos by your friends fine so let us move down to the problem statement it says that there are n people each person has a unique id between 0 to n minus 1 fine given the array watched videos and friends so now two arrays are given to you as you can see in the input a watched video array and a friends now what these edit define is that where watched videos i and friend of i contains the list of watched videos and the list of friends respectively for the person with idi now if you just understand this more clearly it states that there are different persons from 0 to n minus one that is fine so for the first person these are the movies that the first person has watched that is a movie named a and b okay the uh then the second person the id with one has watched only movie c then the third person with id 2 has watched movie b and c and respectively all of that and the first person that is with the id 0 has friends with the ids 1 and 2. now you can see here that the person with id 0 are the friends with one and two the person with id one is with friends zero and three so zero and three the person with friend two is with like our friends with zero and three id two as well as the person with id three is with friends one and two so this is how the friends map is computed using this friends area and now what you have to give in this problem is like started from here paragraph level one of the videos are all watched videos by your friends so all the videos watched by your friends is level one now level two of the videos are all was by your friends of your friends so like level two or like friends or friends then friends you got the point so these are different levels so you start at some particular id you are given that you are id and level of video so you are given that maybe you are the person five okay and you have to find out that at your level three friends what all movies they have seen got it and also you have to find out like let's say that you are like you are given that you are an id person three and from three you have to go two levels down like your friends and then your friend's friends and whatever movies they have seen you have to find out their frequency so let's say like one friend has watched movie a and b another friend has watched movie b and c so these are the two friends let's say so you are seeing that a and b and c so b is watched twice a is watched one times c is watch one time so you have to print out the whole movies according to their frequency like which movie is was the maximum i think so is printed first uh you can see that no so the movies that is was the least is first printed then the movies that is the more wasted like more voice is printed like this so it is printed by the frequencies from smallest to the largest so yeah and if the same frequencies are there then print it by the alphabetical order so i hope you get the point now you can pause this video try to think over the solution it's not too difficult to understand if you have some idea of maps as well as traversal idea yeah that is it like nothing much more uh the first idea you have to uh think is key okay you have to find out you like if the map is formed because they're already seen like explained in the example only that it should formed a map okay now if going through the examples always go through the examples because that will actually give you some idea okay now what you'll see here is that in the first example that is a map that is formed you can form using these uh like values that are given to you id means that you start at the zeroth index that uh you are a zero index person and you have to go to level one so level one is just your friend so one and two now one and two like id one and two has was c and bc okay c and bc and then you find out the frequencies and then spin them out similarly now if the same map is there but you have to find out for level two is this so level one is this level two is this friend there is only one friend down there and uh so that person has only was movie d so you have to pin that now the first thing is like the first thing which comes to my mind is okay i have to find out the levels so when i do a level traversal in a map what is that the like level traversal in the map can be done by bfs so if you haven't studied bfs i highly recommend to first like leave this video out or like make it post and then understand what is bfs try to understand go through one or two examples understanding how bfs is done how a queue is taken or all of that if you understand well versed with bfs then it will become very easy now so you have to do bfs and which means that in bfs you have to travel in levels so you have to go to the nth level or the kth level that is given to you in the problem statement and you reach the level you have all the movies down there when you raised in the graph now you have all the movies when you have all the movies you have to print like you have to store that into some frequency map okay like i have these movies like add them in some frequency map or you can use a map when all the movies are there then you have to like sort these movies out by the frequencies and then print it out nothing else that nothing much complicated the like the thing you have to understand in this problem is how the problem is given actually i got confused earlier like how this is like taken like watch videos on this like how the actual data is given to you but when you understand that you directly get the intuition that it is bfs and then after bfs you just have to find out the frequencies and just sort it out and print it out so nothing much i don't have to explain much you just have to traverse using bfs and in the first level second level and so on so if you have clear idea bfs you will understand the code part but if you haven't then bfs take a queue and from one level to another level it pushed all the like nodes from well like if you it's on the ith level then one move from i to i plus one level it will push all the nodes in the i plus one level in the queue and then when all the nodes are pushed then iterate over all the i plus one levels all the nodes are there and then it tried to push all the i plus two levels in the queues and so on that is why how it moves around so it actually moves down to the code part so that will become more clear but it is not much difficult to understand uh this is an unordered map you can also make a map nothing much different that will show string to integer that is used to find out a store what are the movies on the ice level when we'll reach down there okay this is a queue okay for q is for actually uh for doing the bfs part so we'll start from the id okay this is the id and this is the level on which here because we have to stop at certain level so this is the id from which we have to start this is also given in the input id and then we have to mark it as one because it is an un-directional map we have to also keep un-directional map we have to also keep un-directional map we have to also keep track of the direction like uh which nodes already travel so that we do not push them into the queue so that it will not become like overlooking okay we'll do and it hit over till the queue is not empty we'll pop up the first element pop it out then when we have popped out the second value is the level so we have to see that whatever element i'm popping out the level is there is this element has the level which i want the level i want is this level so if on the second iterator so p dot second is equal to the level then what i'll do so this person is the person i want i'll iterate over all the movies that person has watched so we have the index of that person because we are rotating with the indexes we'll go to that index like string index and take out all the movies that person had watched and iterate like increment that person watched movies in this videos map and incremented by one i hope you get the point so take that person which has the particular level i want it over all the movies that person has watched and like incremented their account in the map so that in the end we can iterate over that similarly if you are not on that the person we want then what we'll do we'll take that person and from that person will go to the other person like push that into the queue from one level to the next level so we'll take the particular like element we have popped out move over all its friends and what we'll do if the particular friend is not visited we'll first mark it as listed and push that particular new friend into the cube by incrementing the level because if you're on the first level let's say then for the next person we have to increment the level so index is there that is pushed but the level will also increase by one keep that in mind so that is how the whole bfs thing is working out after this whole bfs we have stored all the frequencies of the movies first at the kth level by all the friends in this movie's map so what we'll do we have to find out particular movies along with their frequencies so what we'll do we'll make a so that we can sort it out so make a vector and like store them so first because i want to like sort them by their frequencies so thus the first value is integer like it's a pair of string and integer the first value is the frequencies and the next value is the movie name so we'll first like move over all the movies that are stored in video and from that map take all the movies out and store them into the frequency vector so what i'm doing is and pushing back says that i dot second i dot first it means that placing the frequency first and then the movie name fine that is how you can directly do the sorting then directly sort them out because now because the sorting is done in such a manner that it will first sort by the first parameter and then the second parameter and we want in the same manner that we have to first sort by the first parameter that is the frequencies if the frequency is same sort by the second parameter that is name and because it is given that if the same frequency sort order like order by the alphabetical order so that is also done so that is how you can directly use sorting function you don't have to write a comparative function if you pushed the movies as well as frequencies in this particular manner now after sorting is done you have the movie sorted out by the frequencies just make a new answer string because you have to print out all the movies it did over this movie's vector like that has stored out all the frequencies and push these movies from like that particular vector to this answer vector that we have to like return and just return of the answer so that is the whole thing like the more overall crux for this problem is this that is the bfs and then after that it becomes very competitively very easy to like do this part and then that's how the whole problem goes okay so we have ex going through the whole explanation part as well as the code part for this video thank you for watching this video till the end i will see you next time keep coding and bye
Get Watched Videos by Your Friends
largest-magic-square
There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`. Level **1** of videos are all watched videos by your friends, level **2** of videos are all watched videos by the friends of your friends and so on. In general, the level `k` of videos are all watched videos by people with the shortest path **exactly** equal to `k` with you. Given your `id` and the `level` of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest. **Example 1:** **Input:** watchedVideos = \[\[ "A ", "B "\],\[ "C "\],\[ "B ", "C "\],\[ "D "\]\], friends = \[\[1,2\],\[0,3\],\[0,3\],\[1,2\]\], id = 0, level = 1 **Output:** \[ "B ", "C "\] **Explanation:** You have id = 0 (green color in the figure) and your friends are (yellow color in the figure): Person with id = 1 -> watchedVideos = \[ "C "\] Person with id = 2 -> watchedVideos = \[ "B ", "C "\] The frequencies of watchedVideos by your friends are: B -> 1 C -> 2 **Example 2:** **Input:** watchedVideos = \[\[ "A ", "B "\],\[ "C "\],\[ "B ", "C "\],\[ "D "\]\], friends = \[\[1,2\],\[0,3\],\[0,3\],\[1,2\]\], id = 0, level = 2 **Output:** \[ "D "\] **Explanation:** You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure). **Constraints:** * `n == watchedVideos.length == friends.length` * `2 <= n <= 100` * `1 <= watchedVideos[i].length <= 100` * `1 <= watchedVideos[i][j].length <= 8` * `0 <= friends[i].length < n` * `0 <= friends[i][j] < n` * `0 <= id < n` * `1 <= level < n` * if `friends[i]` contains `j`, then `friends[j]` contains `i`
Check all squares in the matrix and find the largest one.
Array,Matrix,Prefix Sum
Medium
870
1,987
hey everybody this is larry this is me going with q4 of the weekly contest 256 number of unique good subsequences so this one was very hard uh hit the like button in the subscribe button join me on discord let me know what you think about this problem i end up spending about an hour more than an hour on this one um and i kind of just to be honest guess at the end i think i just sim um just to kind of give you a little spoiler alert i kind of think i've done something similar to a unsimilar problem and i think i guess on the answer and i it happened to be right near the end which is kind of ridiculous way of saying it to be honest but i do have an explanation for you uh so show some support by hitting the like button hit the subscribe button join me on discord especially if you like contest farms come and hang out we'll discuss problems all day hey so i actually i'm cutting into my own explanation real quick to give a better explanation because uh after some code reviews i actually like the solution more um you can still kind of keep watching to see how i did um how i explained the way that i solved it during the contest and it still works it's still a thing that um comes in to play for counting distinct subsequences but i find that um for this one it actually this code is way better and i really should have gotten a disciplinary contest and it's odd that i think during the contest i did dismiss it because i didn't think it would take care of the uniqueness of it but after i kind of actually went through the code i was like oh of course this does so yeah so this is the code so the observation that i made in the other video or the other part of the video which i will make again here is that the key thing to notice is that you should go from right to left and when you go from right to left that lets you kind of get rid of the zeros in a way that i'll show you in a second and basically here zeros is the number of um unique good subsequences uh for this suffix for this current suffix and same thing for ones uh oh starting with zero and same thing here for once except for so same thing that i'm literally copying pasting and then here basically the idea is that for you know you see this easy formula and you see how does it work right but basically the idea is that okay you start with an empty string so this is basically this contribution right so md string is always going to be one cup empty string and then now you go okay there's a one well what happens right uh well one then you take um well there are only three possibilities right um so let's say this is zero for now the only three possibilities now that we're processing a one when we process a one we can add this one to an empty string so that's one plus oh well let's just say well next one um so this is one because we can add one to the empty string plus we can add one to the number of zeros um because basically the idea is that you're adding one on every suffix of zero uh of every string that starts with zero you add one to it right in this case there's none so we just add zero and here you add another one because another way to say it in english is that for we add one the prefix of one for every subsequence that begins with a one at this point that's zero again so that's zero so okay so after one elevations this is one right and then and this represents number one literally um and then now the next number is one again so then what does this mean this means that okay let's say we add one to the empty string so we get one the string one so that's one um and then now we also add one to order subsequence that begins of zero which there's none so that's you know another zero plus add a one to all the ones all the subsequences that begins with one in this case it's just one so now this is one so of course this is you go to two which is one and one right okay so then now you update it and then uh same thing for the next one so let's pretend this is let's skip ahead a little bit and then now we go to zero and in this case what do we have here right we have we can add a zero to the empty string again so that's just this string we can add a zero to all the zero strings there's none so let's just you know this is zero and then now we could add a zero to all these strings right so that's basically the idea and this is going backwards and we'll explain why going backwards is the key in a second um yeah and then next step we added one so then again this adds you know this one uh this one is for the empty string we added one to all these numbers so that's just this number um yeah and then we add a one to all these numbers right note that of course this is by definition that every subsequence here begins with one right so now we have seven of these yeah and then now we do the next zero and then i'm not gonna you know look at it too much this is oh did i miss one i missed the ones i'm just adding it to this one so i actually i messed up so this is eight okay right and this should be four okay yeah um yeah and that's basically the idea and you can kind of work it out oh you're at home to see that's basically the idea about this magical formula and then the answer is okay they ask you there's no basically these are all sequences that uh so zeros at the end of this loop contains the number of total subsequence that begins of zero but of course as far of the problem said you don't want any leading zero and if you have at least one in the beginning uh that's going to be a leading or that's going to be a good one so that's the answer is just once however you have to keep track of at least one zero because it's not a leading zero if it's just zero so therefore you do an if statement of okay if there's at least one zero uh meaning that there's at least one sequence that's you know with zero then you add one because this is a zero sequence and that's basically it um i don't i feel so bad not getting this because i feel like this is so this is essentially uh digit dynamic programming you may hear it that way um one digit at a time um but for some reason i really just didn't think of the like the uniqueness really threw me off um i guess this is something that i learned today so that's good um but yeah um and then going backwards allow you to ask answer this question of okay still if it starts at zero what would it be right because now we're adding them from left to right because if you're going the other way um you're gonna have to do a lot more so yeah um that's all i have for this explanation for this uh with this explanation uh this is linear time because you just do a for loop this is almost embarrassing the short and easy uh now that you know the answer right like for me i'm embarrassed that you don't yeah you could do your own embarrassment at home it's up to you but i feel embarrassed that i didn't get this but uh but yeah anyway uh you could go back to my other explanation the more complicated unproud explanation next uh well you know within reason anyway so yeah so this one um first look to see that n is 10 to the fifth you're probably guessing dynamic programming and if you guessed that you're right especially if yourself q3 because that was also diamond programming somehow um so i don't um so the one thing that i did do and you can watch me solve this live next is that i actually wrote a brute force algorithm to kind of test my solution um that's how i kind of uh you know that's how i kind of figured it out a little or like it made me figure it out without having like 10 wrong answers but the first idea that i would say is that um the way that the first so there are a couple of observations but the first observation that you should make or that i made anyway is that my computer is slow so that is the first observation that you should make but the second observation after that is that um only the zeros between the ones oh okay no i mean that's an observation you make but for me the observation was that um is that um going backwards is a little easier than going forwards meaning going from right to left instead of left to right because then i don't have to care about leading zeros as much and then it becomes more straightforward in that way so here i'm going to explain kind of my thought process because and to be honest i don't have a great explanation about it but the idea is that okay forever and this is how dynamic programming problems are done anyway i suppose but for every now that we're going from right to left right so we're going this way and as soon as my computer lets me i will continue to go that way right so we're going this way um let's say we start at one and i would and this is actually code that i submitted because i was testing it manually like i was trying to go through a test case that i know i have a wrong answer for from during the brute force you can see me do this live so try to figure that out so okay let's start with one well one only has one so yeah and i actually tried other cases first as well but yeah so now let's say you have one which is the suffix of two numbers what does that mean well now you have two possible numbers right um basically you have this one which we can either not care about and if we don't care about then that's fine um but if we don't care about it then your answer is just exactly the previous one so we so that doesn't like it doesn't change the result um but if we do care about this one then you basically take the previous one and then you add a one to it so that now your possible results of one and one because well one is just if you ignore it so and if you ignore it you just basically you know take the copy and paste this answer and if you add one to the prefix you have this and you may wonder how i came up with these rules and i did kind of have this consistency and you can watch me solve it live during the contest and that was my idea and i honestly if you saw me i went through a lot of small example cases to kind of get intuition to learn to figure it out right um okay so the next one is one and this actually now becomes a little bit um trickier because there are a lot of ways to go wrong about it and still get the right answer and that basically was how i got it a little bit so basically you have two choices right you could either not use this one so that's basically just copy and paste from here so let's just say this is one and you can use this one so that means that you take every number in here and then you add a prefix of one so you have um and that includes the empty string to be clear so in that case you have one because you add it to the empty string you have one because you add it to the one uh yep and then this right so basically you take every string that's here and then you add it to one okay that makes sense so far um oh except that they're dupes right so how do we get rid of dupes well we get rid of dupes by subtracting it turns out um the so this is this would um it turns out that you get rid of dupes by taking uh yeah by subtracting this number why because um because this number uh so the idea here okay i got it sorry i have to try to finger i'm doing this live so i'm trying to think about how to explain in a good way right so basically the duplicates are the same as if you add this number but not this number that's how you get the duplicate um because your previous duplicates is if you it's the same as if you did not take the previous one right because if you take here and you add a one um that will give you the same or you if you add okay let me phrase this another way sorry friends uh but if you add let's say you have this prefix man let's say we ignore this for now if we add this one to this one this is the same as adding this one to this one right so these two have the same sequence so that means that in order to figure out the duplicates it this the number of duplicates is if we didn't have if we add one to the previous one that already exists so that means that we have to subtract it from this one because this one is the same as this one right times your current one uh so that's basically the idea um yeah so just to reiterate a little bit sorry this is i know that what i said probably didn't make that much sense but this is basically uh if we did not add a one this is if we add a one to every um to every previous um basically this one right we added one to every previous sequence here um minus the dupes minus tubes right and why are these tubes or how are these tubes uh these are dupes um minus tubes and dupes are basically if we did not take the previous one right so that's basically the idea and this maybe is a little bit tricky to say but yeah but that's basically the idea and here then now you would get three right so you have one anyway um and then now this one has so if you have a zero it doesn't change anything because it's a leading zero so that's why you just skip it right um but now you have ten or you have two digits what does that mean well that means that now looking at everything here well this is just if we don't add a one right so here if we did not use this one um and then here you add so what do we add so now there are two scenarios right one is if we take every number here and we add a one to the beginning so one oops one um and then here but also now you have one zero right having one zero means you can also add one zero to the beginning of all these so yeah uh use a one zero right and of course just you know skipping ahead a little bit if this has five zeros then you have this times five right or times six or whatever you know um depending on how many zeros you have so yeah so this reduces a little bit but then now you have to get rid of dupes and of course dupes is if we add just one um to all these things so yeah so this is basically uh we ignore this one maybe i'll write it here so we can only get dupes if we um we have here uh if we add one to all the previous sequence of this thing because this is the only way to get dupes because this is equal to this which means it has all the previous unique sequences and it has all the unique sequences so that means that this is repeating so we want to subtract that right and you know i'm just going to die this so that's basically the idea um i know that this is a very tricky understanding try working out more problems and try to figure that out i think that's how i would talk about it um but hopefully this is an idea to at least kick you get uh allow you to get kick started or start kicked it um so yeah um this is my implementation again i even implemented this so and this is a strategy that i recommend just brute forcing it just to kind of get an idea um and here um it's just an implementation of what i said right so this is basically the last total and this is the la minus uh total m you know um yeah total uh two indexes ahead um and this is just the current plus one this current is the number of zeros and i added plus one so this is basically the answer i mean i have some extra stuff here but that doesn't do anything i just look at the last element so yeah so you can look at it here let me actually put this on one screen so you could see it on one screen uh and i had a lot of debugging things because i was just i don't know but yeah so this is going to be and i do this in reverse order as you can see this is going to be linear time linear space as you see but if you um uh if you have a ego eye you can actually reduce this to all of one space by noticing that at most we always look at just the last two total and yeah so this is always gonna you cannot do this in all one if you like um so yes i recommend you practice that even if you get it um let me know what you think and there's some mod math but yeah this is a very hard problem uh for me because you know i mean you can see that i didn't even explain it that well to be frank um so yeah so let me know what you think let me know if you have a better explanation let me know if you have a better visualization um yeah that's all i have you could watch me suffer live during the contest next i tried a lot of things during the contest so it's a long video skip ahead as you need but yeah i'll see you later bye-bye need but yeah i'll see you later bye-bye need but yeah i'll see you later bye-bye but okay um how many people have solved this yeah no more unique good subsequence and no leading zeros mode length is 10 to the fifth i think about this one did anyone solve this yet ten to the fifth so i'm gonna guess it's some sort of dynamic programming so what's the recurrence if it is a zero then it is the number of ones before is that true now because it's unique right the unique part is it makes it a little trickier as well it's okay let's say you have zero i mean we could special case out to zero if this is zero if there's a one then what happens after that if it's all once then it's just once so then it for every zero we do something funky maybe zero we could look at the zeros as the delimiters maybe did anyone salvage it no i guess they don't show up the first 10 minutes or something um if you look at the zeros as delimiters what does that mean so there's one in this so that's two this is the limit is does that make sense if that's the case then it's just now that still ends square though if you don't do it smaller wow people are really fast oh already got it so i don't know like two people got it so i'm just huh so hmm me so hmm so um it's going to be dynamite a little bit so hmm to see how many people kind of well you're loving joe got it already people are very good at dynamic programming we go backwards can that work because then now it's now we don't care okay maybe that's why i just have to go backwards because then now we don't care about the leading zeros it's just that now we can remove if the last element is zero okay sometime to the base cases one so we add uh so basically it is if the ones are delimiters then the number of different ones are just something about the number of zeros okay and we can solve that just looking backwards okay let's see i guess it could be n i don't even know this is right um okay so let's say we have something like this then in this case okay so let's look at backwards one the answer would just be one zero one the answer is zero and one so it's two 101 this is the one input so that's five or 101. this is at least five does that change i guess it doesn't change the answer if this is the yeah okay and then now still five okay now what which one is this one well this one we have all these strings um so these are at least these are the answers and then there's also just um 1 101 this one well just how do you do it because we can't add oh no there's no one so i can't do 101 again can i repeat can i just well i can add this one right because if i just add one two zero and one that doesn't work so basically we can because this one would already add it so we only ha can we only basically care about things that this one is directly responsible for which is i guess this one and this one so this is actually three for here so this is five in total but three and whatever um and this is zero but i mean i think we just ignored these and then here then it is it looks at this three um right so this so the last number that is three so it only cares about these three right and then these three we can add a one two prefix of all of them and that'll be unique by definition and then we can also add a one zero pretty much wait today now this these are unique right i think i just cannot okay i'm missing a one here okay so that means that for three zeros we have we can choose zero one two or three zeros on top of the previous one okay let's actually maybe that's not the thing i want to do that okay i think i have an idea now i should have thought about it like this a little bit earlier instead of wasting a lot of time and i think a lot of people got it already but that's okay um so the end is not necessarily binary but how do i want to do this let's see so basically now we have all these zeros between the ones so okay zeros is equal to i guess this there's a zero and then for x in binary let's just say we look at it backwards when we look at it backwards we have let's just say current zero if x is equal to zero then we increment i guess we already wrote this but otherwise current is equal to zero because we update but then now zero is that append uh current so then now we should have something like zero oh that's not good oh oops that's fair so now we should have something like zero one three dot right okay oh yeah i have an extra zero but that should be okay so zero one three zero one okay so i think i'm okay here and if there's any prefix of zero it doesn't really matter and we have to add in one at the end so make sure i remember okay so then now we do the math okay how do i want to do this so this is the number i can actually probably even do this here so i don't even need to append this then yeah let's just say let's just do anyway though because let's not try to be clever okay so now we know what the previous thing is so the current is going to be the last the number of zeros and then the previous result is the prefix so the prefix of one is number times current is that right times two maybe to add no you wanna add because if you don't add then you don't have a new prefix or you don't have a new amount anyway okay and now just returns some of prefix this is actually one i think so then this should handle all the cases maybe i need to do mod in more places okay well that's not a useful response but i just want to see if this works one that's definitely not right um okay hmm oh because this gets zero so what happened to them next to each other then this is just oh this is coin plus one okay two three four okay that's not right okay whoops let's print it out okay so this should be two why is it giving me 2 oh because i add 1 because it's 0 so then it's oh because i assume that 0 is part of it you know that's not true how do i handle the empty 0 case 4 is not right either why is 4 not right because so after this is one that's fine after this one this should be three because this appends one zero uh i don't i think i'm not handling the zero case correctly very well but i think i have the right idea or at least right path so okay how do i want to go about this then how do i this actually has a very good both of these things have a good case so okay we can maybe shortcut the first one just by f0 not in binary then just return the length of binary and that's fine so i don't know if that's gonna come back to bite me later but here we basically now that zero does exist what does that mean i think i have to pass out the first zero in a good better place think i'm handling the empty case and the zero case incorrectly or not the same anyway so this should be zero hmm this is the last amount no this is one i haven't seen one so if i just have one then this number will be zero and then the current will also be zero but that's what's okay hmm is it this plus one does that even make sense no i don't think so well just empty string i don't i'm not handling the empty string correctly that's why is this correct now i don't know because it could be that this is correct and i just have to add one for the zero case maybe i just don't handle the zero case i don't know what the answer is for this one though and i don't know if there's any way to tell maybe that's right i don't know but let's see okay um i don't know if i'm wasting too much time doing this but it was it's okay so hmm well that's not even close to being good but that's because i this is just really wrong oh no that's not right but um yes can't even write the proof force correctly oh yeah because now i don't have to zeroes again so okay and now let's try some let's see if these match on by you're just going to submit it okay they do not match though so i'm not going to submit that's sad save myself five minutes so i end up taking like two three minutes doing it so i don't know if that was a good five minutes thing but that's okay so let's look at this one there's only 14 okay so then 0s is 2 0 1 that makes sense 2 0 1 okay and then now you start with one because that's not true this should be three maybe i'm just doing it wrong i mean i'm definitely doing it wrong but i should definitely be three maybe i need to handle the first one in a weird way maybe this is just weird because this is the last number so the empty string is empty string a good string let's just say empty string is a good string again and then i just subtract it later so this is three which is true where is it yeah okay this is three that's true and then this is sex is that true hmm all right let's do a dumbo example first like this one why do i return two now i returned 3 because i just pressed 1 but the answer is 2. because this is this should give me a one which is true but the empty string we don't care about empty string right larry yep no we don't so then we removed the empty string this may be one of those problems that i'd end up spending too long on okay so this is good now this one we skipped because we cheated okay this one why is it four because okay so we have two levels of freedom here it should be this is one and then we have two levels of freedom how does that work this is where i need paper but i'm doing it for y'all instead okay so let's say one this is just one okay and then zero one we ignore and then one zero one this one we add we try to add one two to this and then we try to add one zero one to this so that's why we have two okay but we don't do what we don't do is we don't have um so but here we don't have we what we do want is this 10. okay i see so something about the max maybe well i guess it's the total number of ones or the total number of zeros because that's the number of zeros that we can have with this as the one and all okay so then that means that okay so this is good i think but it also means that here there's one total zero which means that we can have these two okay let's see if i can play around that idea um this is one nope am i doing all right in this plus because the number of zeros is just the answer maybe plus one more not good enough got this one right though but okay so why is it off by so much what is this one my answer is 10. the white answer is 17. how do you have 17 on this okay i guess there is 17 on this but well these are these should not be ones well this should be one but for now we add i think my adding is a little weird i think that's why because now we want to add one to all these is fine but one zero we also want to add two one three one four and four ones right because you have all these prefix so okay let's try a easier incorrect one now that i think i see it so you have this one which i put seven because i just this last one just times two of the previous but that's not true what it can do is have one two three four things that it wasn't does that only apply for that first and i'm really behind now i think a lot of people got it wow a lot of people were smart i was so fast on the other ones but i just can't get this one the recurrence is hard for me because here then okay let's you don't need all these things what does this look like then yeah i'm off by a lot because now i can have one zero and then the ones before that a lot of people got this pretty impressed i don't know if i can this is not my type of problem maybe so i have to figure out this out at 45 minutes though so that's a long time so this two it's not just applied on this element this all element hmm just i thought that would add uniqueness that's why because just playing around this would be too slow anyway but i just want to see if that works nope that's clearly overcompensated well maybe now it doesn't need to no it still need to press one because it also adds to empty string i guess maybe now i'm just like hacking it so i don't know well mistakes were made i suppose ah okay feel like i have the right idea but i did for a long time and now i'm just like way behind um well because of this particular one because that's the question okay so one this is just one just a new one new number but then now what how do we handle the one because now this is the funky stuff is that you can add one to only this one but then you can add one zero to all of these so one zero one right so just something about the total and i'm just adding a one and then now how do you do this for example well so you add one to every number here which is this thing plus 1 101 1 0 1 plus then you add 1 0 and you only add 1 0 now you add 1 0 zone one all of these right so one zero one hmm did i have a case i think i have this case what was the answer 23 i don't know i don't think i have close to 23 so i'm probably missing a lot but well yeah because i have one zero one for example how would i get that well it's just this but i don't think that's still not one two three four five six seven eight hundred and twenty fifteen eighteen nineteen zero so i'm still missing four numbers but well for example i'm missing uh 100. and just basic things like 10110 which is not even limited anymore i don't know how to do this um well and this duplicates otherwise okay hmm well maybe i just don't know this tragic hmm oh am i thinking so 1-0 so we have all these unique so 1-0 so we have all these unique so 1-0 so we have all these unique sequence so we can definitely add two of them well this one i guess because then you have two times all this stuff but this is way more than two times that stuff right hmm um i have to think about a different way of doing it because how do you get one zero one in this case i guess how do you get all this stuff in this case and why is it that you don't use it here so this one you're built on now this will always give you a unique one obviously but then how do you get this one well this one is this somehow keep track of the maximum number of zeros something like that because now you have zero so then now what does that mean and if now here you have two zeros what does that mean that means that everything before that i've not made any progress so so we can take the sum of ortiz what happens if we do but we know that these three are two can we subtract them is that how me and apparently this is a not that hard problem but i'm having a lot of trouble with this one because 200 people stop this i don't even have a clue oops um so well maybe i don't know how to do this one i'm not i'm just missing an insight that i can't figure out how do you do this math of uniqueness tell me how do you do this math this is seven right here this is look there's nine because it's this plus a zero wait what am i missing oh whoops ten and just see okay so let's just say that this is so okay so let's just say that this is the case right um we can't sum it because now we know that there's three tubes how do we get to three troops though right here how do we get to three tubes out of here get these tubes out of here oops what does this mean so is this plus but then like now this is too big would i get again 25 because i don't d-dupe 25 because i don't d-dupe 25 because i don't d-dupe because this is four and then now i have two degrees of freedom wait what now we'll get two so two times the sum of all this stuff is sixteen so there should be a three oh there should be a one even hmm still not quite right but just kind of you know not unexpected i don't know what i'm doing i'm just trying different things i don't know i don't even know how this formula works i was just doing i don't know it just feels like whatever but hmm this is just weird oops cause i already have total i don't use total right on anymore i get i don't even know how this works i mean if this works i don't okay well maybe not like this okay if okay let's try at least a few more things before i try to optimize this to be right how does this formula even work i don't even know sometimes you just get lucky i guess but i was just i think i was uh i guess i recognized this pattern of some sort but okay but now i have to think about how to do the prefix sum essentially so some of the prefix is just some of the first fingerprinting whatever hmm oh man i have 20 minutes to figure out this formula so i think i'm good okay so that this does match okay so that means that we can should be able to go to do okay just still matching okay and then that means that this is total minus two maybe it can be an outbound so yeah okay i don't know okay and this is actually just okay now we can do some math with respect to mods let's just make this this is just for timing anyway but it should be okay otherwise still don't believe this though to be honest i stepped 19 minutes so let's i mean i'm not i am not fast enough anyway so let's at least kind of look at okay huh okay if this is good i'm gonna submit i guess yeah i guess so okay i think that let's give it some and testing to um i don't even understand how this works to be honest yeah thanks for watching hit the like button hit the subscribe button join me in discord hope you all have a great week have a great uh you know contest and yeah stay good stay cool stay healthy and good mental health i'll see you later bye
Number of Unique Good Subsequences
substrings-of-size-three-with-distinct-characters
You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`). Find the number of **unique good subsequences** of `binary`. * For example, if `binary = "001 "`, then all the **good** subsequences are `[ "0 ", "0 ", "1 "]`, so the **unique** good subsequences are `"0 "` and `"1 "`. Note that subsequences `"00 "`, `"01 "`, and `"001 "` are not good because they have leading zeros. Return _the number of **unique good subsequences** of_ `binary`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** binary = "001 " **Output:** 2 **Explanation:** The good subsequences of binary are \[ "0 ", "0 ", "1 "\]. The unique good subsequences are "0 " and "1 ". **Example 2:** **Input:** binary = "11 " **Output:** 2 **Explanation:** The good subsequences of binary are \[ "1 ", "1 ", "11 "\]. The unique good subsequences are "1 " and "11 ". **Example 3:** **Input:** binary = "101 " **Output:** 5 **Explanation:** The good subsequences of binary are \[ "1 ", "0 ", "1 ", "10 ", "11 ", "101 "\]. The unique good subsequences are "0 ", "1 ", "10 ", "11 ", and "101 ". **Constraints:** * `1 <= binary.length <= 105` * `binary` consists of only `'0'`s and `'1'`s.
Try using a set to find out the number of distinct characters in a substring.
Hash Table,String,Sliding Window,Counting
Easy
null
152
hello so today we are doing with this problem called maximum product subarray and the problem says we get an array NIMS and we want to find the contiguous sub array within an array that contains at least one number which has the largest product so we can have something like 2 3 - 2 4 here and the largest like 2 3 - 2 4 here and the largest like 2 3 - 2 4 here and the largest product can be obtained by multiplying 2 &amp; 3 to get 6 so contiguous here it means &amp; 3 to get 6 so contiguous here it means &amp; 3 to get 6 so contiguous here it means it's not a subsequence we can't have gaps like we can't take multiply 2 &amp; 3 gaps like we can't take multiply 2 &amp; 3 gaps like we can't take multiply 2 &amp; 3 and then multiply by 4 we can't skip this number in between but this member makes smaller and so that's why the largest one is this one for this one - 2 largest one is this one for this one - 2 largest one is this one for this one - 2 0 minus 1 the largest one is 0 because if we include minus 2 it's going to be still 0 so and if include minus 1 is still 0 so the product of all of them is 0 but we can't just do if you do just minus 2 that will be smaller than 0 and we can't skip this 0 can take just minus 2 and minus 1 because that's not contiguous anymore so that's the problem now how can we solve it so for this problem the ye the thing is that makes the problem a little bit like different like if it was just positive numbers it would be really easy to do right just the product is just all of them right and so let's just go from the simplest case and then gradually increase so simplest cases this is a useful I think to try to do so simplest case is only positive numbers right now second so simplest case as far as 1 and then after that we can handle the slightly more complex which is positive numbers and zero and right that can contain both positive number and zero because whenever we encounter zero if we take it makes the product become zero and so we need to take basically the product is the max between what's left of zero and what's all right of zero because zero just makes the product smaller and equal to zero right what makes things even more complicated which is what the problem is asking is having negative numbers positive numbers and negative numbers right because when you have negative numbers like you could have let's say 18 a big number too and then we encountered minus 1 and 2 minus 1 just makes this entire big number here becomes like let's say 18 x 2 36 so it makes 36 become minus 36 which is really smaller than even two right and so the maximum product will be anything not including that we get your power all right but I'm gonna get you bodies make things even more complicated right because we might have a say after this - because we might have a say after this - because we might have a say after this - we might have - for right now the we might have - for right now the we might have - for right now the maximum product is the entire thing because if you multiply minus 1 with minus 4 you get 4 right and so this entire thing is 36 multiplied by the biggest product 36 multiplied by 2 multiplied so x - 1 x - x - 4 because multiplied so x - 1 x - x - 4 because multiplied so x - 1 x - x - 4 because now this - 4 made the number that was now this - 4 made the number that was now this - 4 made the number that was negative become positive and so it became really bigger than anything else we could achieve and so negative numbers if there is only 1 then what's whatever leftover 10th right of it is bigger if we have multiple negative numbers an even number of negative numbers which means then minus would make a positive number then in that point we would have to consider the entire sequence the entire contiguous range as a as the pod as the max product and so you get the idea how a negative numbers locating things and so let's just try to solve the simplest case first and then go from there so for the simplest case you can just go through the array and just have a product right in select one and then just go to the array and multiply all of them that's theirs because that's the biggest thing we can achieve and return that right it's a please straightforward now for the zero case what should we change in this solution so for the zero change the zero case is that if the number is so all is fine here but if none is zero that means the product became zero and so we need to reset it to 1 and basically just do something like this where if we have two one zero or then whenever you find so the product here becomes so the product is called P becomes 2 here at this point and then when we move to this it becomes well let's take this as 3 it becomes 3 here becomes 6 but the problem is here P becomes 0 and if we continue taking it as 0 we will only find smaller products right and so to do that we are just going to me make it 1 which is basically just resetting it so this is recently so that when we get to 4 we can consider only the sequence the continuous sub array of 4 right so that's what we'll be doing here but because of this we will need to keep track now of a best value because we don't know if the best value is left of 0 or it fits to the right of 0 right so we need to keep track of the basic value it was initialize it to may be the smallest number possible so that whatever we put in with the max it's going to be the max right and so what's going to happen is that here we will keep track of the best product that we found so far and we returned the fist instead and so you can see the only difference between this and this one is that one encounters zero we reset the product so that we can restart to the range from whatever is after zero because zero just makes the product smaller right okay now how can we handle this more complicated case that we have a problem asks for of us so here what does change the problem with negative numbers is that let's say you had four right and to encounter a positive number two at that point okay this is bigger certainly because this is eight but if you had four encountered minus 2 this number is smaller right and if you had the safe free and you encounter minus 2 this number is minus 6 but here if you had three and encounter to the number becomes six by the product so what's the difference here it's when it's not get a negative number the bigger number is smaller when it's a so we can see here this one was bigger but here this is smaller than minus six but here this is bigger than six so you get the idea be its reverse at white right when you encounter a negative number when encountering a negative number the bigger product becomes the smaller one becomes a smaller one but only this is only if when it counted a negative number the bigger positive product becomes a smaller one because if we had a product let's say of minus eight and then when encounter minus three and then we had a product of minus 6 and we encounter minus three again so this one is almost a stick to that would be easier to calculate then this here would be 16 and this here would be 12 right so you can see when we encounter a negative and the product was negative 16 is bigger than 12 and so where the number was smaller the negative number was smaller now the product became bigger so you can see the difference it's it gets reverse it every time I encounter a negative number what do i mean by it here what gets reverse it is Mac's product becomes the mint product or the bigger product becomes a smaller product and a smaller product becomes the bigger product right and since we are looking for the biggest product overall we need to just keep track of both so that every time we check will check both because we don't know if you will encounter a negative number this an even number of negative numbers or an odd number of negative numbers we don't know and so let's just keep track of you in a product and Max product and so what would change compared to this solution here so what will change instead of checking for number equal to 0 now we want to check for number less than 0 and we need to keep track of two things min product and Max product right so let's initialize was a both of them to 1 and now if number is less than 0 what we said is bigger product becomes the smaller and the smaller product becomes the bigger and so that means we just need to swap min products with Max product and then we need to keep track of the Max product at every point and keep track of the min product at each point and of course since this always keeps the track of the maximum product then the best is the best so far compared to the max product so what's the max product it's just the max of the previous Max product that we have multiplied by the new number that we just found or the max product previous max product so when does this it becomes bigger if number is negative then this is bigger right but if number is negative and the product was negative right and so we would have stopped swap with milk product and multiplied by the negative number and that becomes the overall big number and we put that at max product so for this one it's max product its main product the mean of main products multiplied by name and so that's what changes between the solution that we had before and the new one it's that we need to keep track of both because we don't know when it's flips when one of them becomes the bigger and the other one becomes the smaller and the flip become happens only when you encounter a negative number because in both cases if we had a product that is negative and we multiplied by a negative number then the order of which is bigger flips and the same thing when we had a positive number and we encountered a negative number the order also flips right so that's what we are doing here but what we are doing here is just the same bike especially for zero if a number is equal to 0 and this one became zero then we should just restart with the new with whatever new number we found so if the product was zero in Max product was zero because the previous number was zero then the new number was say in this case 4 is what's going to take over here and so that's what and the same thing for min product and so yeah so that's the solution for our last case so let's just replace it here and that's pretty much it service 1 let's try some other use cases like I know cellist one maybe two minus five minus eight and then let's try this one and let's try okay it seems good enough okay so here I'm returning minus infinity I should probably just initialize this one zero then okay so now what's like the same there is no difference what we have a problem for this case minus 2 to 0 but it should say okay so I guess what's missing here is that this basically should be so minus 2 case so I guess we should just take this if it contains or otherwise just do okay what about just one what happens yeah we have your 41 1 minus 2 okay so that doesn't so I think what we should do is just handle the case so if length of name is bigger than 0 just then we could just say give at that point the first number as the best else what should we do as the default value who did they say so they said the array contains at least one number so I guess we shouldn't care about the empty case so let's just do that to them yeah my test case here is not needed okay so that versus okay so another way to think about solving this problem is so it's very similar to what I did in the last solution except what I can do is not explicitly swap and check just do that regardless right and so that means basically that I just say okay so here I started with zero and I don't need to do the check just every time make max crud be the max of all of them so if the swap happen don't do the swap and just by default to just say okay mean product x and so this will if the number was negative it will act as doing the swap right but to not overwrite this before using it here because we will also need to do for the same for min products because this will do the same thing as the swap if the number turns out to be bigger because we multiply it by a negative then we do the same thing so all of them have the same we just take the max of all of them and then I just need to do it here so that I don't override it before using it and that's pretty much it and so yeah that's still working just we don't explicitly do this work it simplistically gets done with the max and min and did this pass yeah okay cool I forgot to mention the time complexity for this and the previous solution to it was open because we just traversed the numbers one time we can't do better because we have to check all the numbers to be able to tell them the point max product right the space complexity also is for this solution and the previous one in both cases we used only constant space so in both cases it's all one and so that's pretty much it for this method a slightly different way that we can approach this is to do something like this so basically we can have it we can do it we can claim something here which is that if there is no zero in the array then the max product is must either start with the leftmost or to the rightmost element basically the first or the last element which means that this basically means that the max product is either the prefix or the suffix of the red so it's either the product of some prefix or suffix of the array so how can we prove this claim here that we just um that we just stated so basically let's say the array a from I to J we don't know that but just the definition of the problem is that this is the max product right is the max product and to prove our claim by contradiction let's assume that is different than 0 and J is different than n because what we are saying here is if it's a max product it has to be either have I equal to 0 or J equal to n because that's what the leftmost in the rightmost element are and so if we are able to prove by contradiction that this is not possible then we can just prove our claim right using it just to prove by contradiction right ok so now what this would mean is that plus let's call this P right is the max product so if a pie is bigger than zero we said also that if there is no zero right so we know that if a and a chase B are bigger than zero so that means that so if this one is bigger than zero or this one so we are just going to handle multiple cases right so if I one of them is bigger than zero that means to get the max product we should include this right we should extend to it and if the if a I if both are negative so that's the only case as possible right either one of them is positive and the other one is negative whichever one areas or both are positive or both are negative that's the only cases that we have and so we should extend it to a to AI or to a J so we know now that in this case we should go all the way until the first until AI or until H a right now if both are negative that means we should include both we should extensible the two whichever one here whichever one is positive and here we should extend it to both because let's say I was minus 2 and then we had the set a number and we have minus fault it makes us to extend to both because if we do that we'll get minus 2 multiplied by minus 4 which is 8 which only makes the product bigger right and so now we know this claim and so also by induction we could just say ok that's valid if we had only two elements right let's say I is at some position here in Chains at the next position and we two elements here and so this claim up says that if one of them is if this one is negative we should even see this one is positive we should use this one is negative we should take only this one if both are negative we should take both of them right and so by induction we could just extend the same logic to this portion and keep extending the illogic to the entire array right this is also of course assuming there is no zero right and so that means that we could just that means we prove who proven our claim so we can use that in our solution and we need to also since the our claims handles only the case where there is no zero that means we should handle zero case right so that's pretty much what we are going to base our algorithm on and so in order to since we know that now by we prove this by contradiction we prove that it has to be it has to extend all the way until zero or all the way until end because of this induction so I has to go to either 0 and J so either I has to go to 0 or j2 n so that means contradiction here to this and so now we prove proven that if there is no 0 at the max product is the max product must include the first element or the last comment or both right and so to do this and plus we need to handle the 0 case so we did to do this just compute all prefixes compute all its products plus all suffix products and take the mats pretty much that's what this means because it's either a prefix or a suffix or the entire thing right and so the entire thing is also considered a prefix and considering the suffix so let's just compute this and take the match so how do we complete the prefix well prefix is just do product as we go and if encountering zero to handle the zero case just reset one right so that we can start anymore in your previous same thing for the suffix do product as we traverse the array from left to right the suffix is almost the same thing except the only thing that changes is that we do the product from right to left which is the same as saying this is equivalent to a new product as we Traverse from left to right but on the reverse array from left to right on the reverse array because if you reverse it and you traverse it from left to right that would be the same way as traversing from right to left new product from left to right so this is pretty much it right and the same thing reset to state 1 we count from 0 and then we take the max at the end and so now that we have our algorithm let's just computed so we need the reverse array so that we can compute the suffix for it and so let's say let's call it B let's just call this one a and now that is the reverse of the array which with Python we can just use this and now we are going to go through the length of the array and traverse left for the prefix which is a and right for the service so I is going to put our prefixes and B is going to hold our services and so we go through the length and for AI it's going to be just the prefix product so did the same at the sum-product we keep adding same at the sum-product we keep adding same at the sum-product we keep adding every element we encounter here we keep multiplying right and for the zero case so this is if AI is different than zero if it is equal to zero then we need to reset so it's 1 but that's what we do here for the suffix part same thing it's I because it's reverse it will go from right to left and we need to multiply by B I minus 1 but if the eye is different than zero if it's equal to zero when it is at one so basically this means that we take the number and we multiply it with the product of all the previous elements which is in a I minus 1 by now and the same thing for B I will take the product that will start from the last element because we reverse it and we multiply it with whatever was before it right so that would mean pretty much that if we had an array like this state maybe this one so our B would be this is just at the installation step would be 4 minus 2 3 2 right now if we do the product if you start doing the suffix we would have 2 and then now at i3 we'll multiply it by whatever the product of what's before which at this point it stood so that would be 6 then we get 2 minus 2 we'll multiply it by what was before which is at this point minus 2 multiplied by 6 which is minus 12 and then 4 multiplied by the product of what's before which is minus 12 so power x minus 12 minus 48 and that's the prefix 1 for the suffix it would be similar thing so 4 multiplied minus 8 we multiply it by 3 18 minus 24 and then 24 minus or e8 so minus 48 right and so now that we have both the prefix product and the suffix product to get the largest sum we just take the max of all of them right this one and this one which pretty much would be the max of because this represented all the prefixes or the suffixes right and so the max of all of this is just six right and that's the solution right and so here we just return the max of a and B if we had zero universe will just have skipped it and reset the product right and that's pretty much it so let's run this so we have a slight problem it seems like we have numbers that are sounds like the negative stuff yep so the problem here is that I go from zero which means that this here would go to and take the last element which is mean it's not what it should do because a minus one in Python is the last element so I want to limit this to one because the first element anyway the product is just the element itself and that's already in the array so we don't need to compute it and so okay let's see it seems to work okay it's not us admit it we have a slight problem with this miss case just so the problem is my solution cells zero and the max is one for this use case yeah it should say one that's the Matt so why isn't it same yeah so here if a I minus one man because if the previous element was zero the previous product was zero wanna reset the new product right but what I was where I was doing is that if only if this is zero so I make this one becomes zero which is not the right thing to do okay so now it passes there is a slight thing that will make this easier to read in Python we can this here we can just say if it's zero then say one instead so or one so this means if this is zero just make it use one instead that makes it a lot shorter but well this is running let's just talk about the time complexity here so the time complexity for this solution is the same as the other one I'll just drop us in the array once and so it's open and space complexity it's just a one because no sorry it's over one because we are using an extra right here so it's slightly worse in terms of space complexity than the solution or not before okay so you guys look alright okay it's all to submit okay so that passes yeah so these are the different methods that we can think about solving this problem with and yeah that's it for now thanks for watching see you next time
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
146
lead code problem 146 lru cash so this problem gives a wants us to implement a class called lru cache and here they have some different things they want us to do so in the Constructor you will call the contractor like this where it will use a the capacity which in this case will be the total size the capacity of the cash and then they want us to implement the get method as well to return the value of the key if the key exists otherwise return negative one and they also want a put method where they will put the key and value so we have to update the value of the key if the key exists otherwise we add the pair into the cache and if the cache I've already exceeded the capacity upon putting we have to remove the lease recently used key right and then our function has to run in o1 average time capacity that means we cannot iterate through every time we get or put okay so when you look at Key and value I thought I mean I will need to use a map in this case would be an order map but in regular map will work fine as well and then I have using a c plus first pre-built link list right pre-built link list right pre-built link list right and then I also have my integer here which stores the capacity of the cash right so upon construction I will store the capacity in every variable core cap okay Okay so once we're done with that let's talk about the put method first right okay so I'll use the example given here and explain how my code handles it so when the lru cache is initialized the capacity is set at two so right now our capacity is 2. okay and then it calls put for one right the key is one and one okay so what actually happens is uh when you call the method he's using key and value right okay I'm gonna use a list and then we have a map okay so when it costs the key and value okay if statement it does not do anything because there is nothing inside the map second if statement is to check whether or not the list has Rich capacity and in this case it does not because it's nothing right so we don't have to do anything there as well so what we do is we just push front the key and value pair so right now all this looks like this one like this and then on map e which in this case will be one we'll store the value of the iterator right remember we are storing the iterator of the list begin right the reason why we're storing the iterator will be explained later but for visualization stick I will put in the node right so this is the iterator of this node in the list okay after that calls put again two this will not trigger so we put only right so push front so two here two and then we add the key value into our map to Tool okay and then he wants us to get right okay so when we get in this function I'll try to find I first find whether or not the key exists in a map in this case we are getting one so the key does exist but in the event that it does not you return negative one so since it exists or my function will then do is use splice right so splice is a built-in function in list where it a built-in function in list where it a built-in function in list where it will move the node it will move a node to another position inside the same link list so what I mean by that is the splice the first argument is where I want to put it the second argument is which link list I want to use and the third argument is the iterator right which is why we store the iterator inside the map so what happens here is I want to put the note of one right since we use get ready that means this one is not the least recently used rate is the one has to be moved forward so I supplies I move the one forward right at this list using this list at the key of this one which is over here so this happens is this will move to the front right so let me add this okay so in the event that if let's say yeah right I this one have another node like this right so what spice will actually do is that you will move everything behind to the front like this as you know it will not move everything to the front you only move this node to the front one then we'll move like this right so supplies are basically a method to move the notes around okay since you don't have the three other three this okay and then I return the key of the second which is the value so map key is using one right so one so this is the value we're going to return and then the second so second will be this we want okay that's why uh how are you cache when you call get1 will return one okay after that it tries to put three right okay so when we put three remember now that our capacity is two so our cache is actually full but uh let's keep going first so the first statement doesn't trigger because there's no tree and this second if statement will trigger because the list size now is equals to cap right our list size is two so what you do is we erase the back of the list first right so the back of the list which is this node and the First with the key of two so the map will erase this after that the list will also pop back so this will be removed okay then only then it will push front the new key and value which is three and then add it into our map as well okay so a couple or map looks like this our list look like this so one becomes the least for example at least recently used um value again so when you want to call get again since the map cannot find the tool you just return negative one and then you try to put four so the same thing happens when you try to put four we're trying to put four this is not trigger this will trigger because our cache is full we erase the first release the back here back first we do this one so we erase this and then we pop back and then we push front and then we insert as a key again so far or four all right okay let's begin right because we push front all right and then after that you will just try and get one get trigger ball okay so let's see I want to put let's say I want to put a new uh not a new key the theme key called tree I want to change the value to 5 right to three to five okay when I call this now this is the move then trigger because there is an existing key already it is three so what happens is I move the node 3 to the front of the list again so I move this to the front and then I change the value into the new value right so this will be five right okay this will be five okay so that's what happens when we put then we just return nothing else we need to do and then this is our list after we put three five is our map of the aperture5 so when you call get again you can get again you return the correct value which is five okay pretty straightforward that's all I have to show thanks
LRU Cache
lru-cache
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`. * `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, null, -1, 3, 4\] **Explanation** LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 **Constraints:** * `1 <= capacity <= 3000` * `0 <= key <= 104` * `0 <= value <= 105` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Medium
460,588,604,1903
165
welcome back guys today we're going to solve this lead code question compare version numbers in this question we'll be given two strings version one and version two as an input and we need to check if version one is greater than version two or not and the output will be like if version one is less than version two then the output will be minus one if version one is greater than version two the output will be one and if version one is equal to version two then the output will be zero and there's one constant in this question the constant is that we have to remove the leading zeros so if we remove the leading zero from version two then this input will result as three point one point zero point six right and comparing version one two version two now we can clearly see that version two is greater than version one so by this condition the output will be minus one right so how will we compare what we can do is we can split the string using dot as a delimiter so if we split the string then we'll get string of strings let's say we split the version one first so we'll get something like this so for version one we have this and for version two we'll have three 0 1 0 and 6 right now what we can do is we can traverse both of these array of strings at the same time and we can convert every intermediate element to an integer and we can compare them if both of them are similar we'll just move forward and if both of them are not similar then we'll check between these two conditions which one is satisfied and will return the respective answer so now between 3 and three both are similar so we'll just move forward one will be converted to one zero one will be converted to one again both are similar we'll move forward zero are similar again so we'll move forward between five and six five is less than six so we met the condition that version one is less than version two that satisfied this condition right so the output will be -1 right so let's see one more example here the version 1 will be converted to 0 5 version 2 will be converted to 0 and 5. between 0 and 0 both of them are equal again between 0 and 0 both on both of them are equal this 0 5 will be converted to 5 this 5 will be converted 5 both of them are equal again so we reached the end of the loop and at the end we found that there is no difference in the version 1 and version 2 so we'll return 0 as the output now let's see one last example so for this we'll have this array of strings as v1 as this and v 2 will have 1 0 1 right now we'll compare 1 with one both of them are equal then one with zero one uh so this will be converted to one again so between one and one both are equal so we'll move forward again now we have one in the v1 but in v2 we don't have any element right so we'll just check it with zero so here we found out that v1 is greater than v2 so will return one right so now we have seen the explanation part let's have a look at the coding part initially i'll split both of the strings so v1 or version one dot split using dot as a delimiter here will split v2 i mean version 2. now we'll traverse both of the array of strings at the same time so v one dot length or i is less than v to the length so there can be a condition where v one's length is greater than v two or v2's length is greater than v1 right so this for loop shouldn't stop right so this condition will take care of that so inside this will have n1 will first check if i is less than v1.length if it is will pass that string to an integer if not we'll just assign 0 to n1 and we'll do the same for n2 right so yeah now we'll check if n1 is less than n2 we'll just return -1 else if n1 is greater than n2 then we'll return 1 and if n1 is equal to 2 we'll just continue the loop and if we come out of the loop then we know that both of the version are similar wasn't 1 and version 2 are similar so we'll just return zero yeah i think this should work so let's run and test this so what did i miss here hmm for entire is less okay i should be equal to zero right so this works for this input let's submit and test this so yeah it is accepted so don't forget the drills do like and subscribe see you next elon musk time o'clock and it's pm being patient with my buzz yeah you can't rock with us i can't rock fittest i don't cat put em i see fake on em the ice look fake on em
Compare Version Numbers
compare-version-numbers
Given two version numbers, `version1` and `version2`, compare them. Version numbers consist of **one or more revisions** joined by a dot `'.'`. Each revision consists of **digits** and may contain leading **zeros**. Every revision contains **at least one character**. Revisions are **0-indexed from left to right**, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example `2.5.33` and `0.1` are valid version numbers. To compare version numbers, compare their revisions in **left-to-right order**. Revisions are compared using their **integer value ignoring any leading zeros**. This means that revisions `1` and `001` are considered **equal**. If a version number does not specify a revision at an index, then **treat the revision as `0`**. For example, version `1.0` is less than version `1.1` because their revision 0s are the same, but their revision 1s are `0` and `1` respectively, and `0 < 1`. _Return the following:_ * If `version1 < version2`, return `-1`. * If `version1 > version2`, return `1`. * Otherwise, return `0`. **Example 1:** **Input:** version1 = "1.01 ", version2 = "1.001 " **Output:** 0 **Explanation:** Ignoring leading zeroes, both "01 " and "001 " represent the same integer "1 ". **Example 2:** **Input:** version1 = "1.0 ", version2 = "1.0.0 " **Output:** 0 **Explanation:** version1 does not specify revision 2, which means it is treated as "0 ". **Example 3:** **Input:** version1 = "0.1 ", version2 = "1.1 " **Output:** -1 **Explanation:** version1's revision 0 is "0 ", while version2's revision 0 is "1 ". 0 < 1, so version1 < version2. **Constraints:** * `1 <= version1.length, version2.length <= 500` * `version1` and `version2` only contain digits and `'.'`. * `version1` and `version2` **are valid version numbers**. * All the given revisions in `version1` and `version2` can be stored in a **32-bit integer**.
null
Two Pointers,String
Medium
null
1,689
hello everyone welcome to learn overflow in this video we will discuss another liftboard problem partitioning into minimum number of dc binary numbers okay so that's the question we have over here this is an uh medium level question let's see what's the question it's all about so before starting this make sure to subscribe to this channel for regular record videos okay so this question says like we a decimal number is called a deci binary uh if each of his digits are either zero or one okay so we are just mean to say that uh the deci binary is called only when ways either all of its zero are zero and one like each of us is this are either zero or one okay without any leading zero okay there cannot be any kind of leading zeros as well for example one zero one or one zero are like the deci binary numbers okay so if it's uh if you just look carefully these are the numbers that what we used to write in decimals actually but they mean to say these are in binary as well so that's why they just named it a deci binary okay all right so but it says like while uh one two uh three zero one these are not like obviously they say either zero or one can also only be the digits so uh that's why you can see like this is this values cannot be there okay so 2 3 cannot be there okay fine so now they say like given us a string of n okay there's a string of n given to us that represents a positive decimal number okay so that is a positive decimal number but remember this is a string of n okay so this is not an integer this is a string okay so what you need to do return the minimum number of positive deci binary numbers needed so that this sum up to n so like we need to find out whereas the minimum number of uh positive basic binary numbers can be there so that this uh this sums up to uh this n okay so let's uh let's take an example like 32 over here okay so we have a number like 32 for us okay now see to make this dc binary you can have either zero or one okay so first try to take uh say we take one and one okay so that's the maximum we can take in the first case because we need to find the minimum number of positive disc binary possible so if we are supposed to find the minimum then we should take the maximum values possible at each step okay so there's a one we got and then we need to add another 11 uh 11 in the sense one and one in the descent binary format and then to make it a three we need to make another one and zero right so that's the thing we need to go ahead and that's why they uh explained that in that format actually okay so we can find that here we got one number second one and the third one so we find that the answer we need to return is a 3. so that's what that's return is a 3. so that's what they say like the we need to find the minimum number of positive received binary numbers needed so that they sum up to n now uh look carefully what are we actually looking for in this question okay uh whatever question we have okay we cannot have like oh like we need to take i zero and one right uh like the maximum number of like the digits can be only zero and one right so if that is so that at each instance we can have a maximum of one at each value right if we need to sum up to that value then uh like the needed so that they sum up to n okay so they sum up to n so if we do a sum of two n at each step we can have a maximum of one right so look here whatever in the number it is see you have 50 uh six all right you have a number 56 how can like how can you reach there maximum you can go like one uh and one here let's eleven and then one and one right one and one so whatever it goes and then zero and one right so maximum is how much six because you cannot go beyond like you cannot take any digits beyond one right so you have to take digits that is one so the main idea is to think closely the main idea is to find what is the largest number or the largest digit in our string in being why i'm saying so like if that is like you find the largest digit then that will be the answer in any ways because you are doing a summation of uh like one like summation of the numbers that are one okay so it's more like 1 you are just summing up the numbers all right so if you are just summing up the numbers then uh just summing up the numbers with each number being one okay so then there's a maximum number being whatever be the maximum number you have in the maximum digit you have in this string n will ultimately come up with the result right you cannot like you have to give those many ones for that particular digit say you have a nine at any place so that means you need to put a nine uh ones below it right you need to you have to make it a summation of uh like nine times one right anyways you have to do that because otherwise you cannot reach up to a sum of nine because we need to uh reach up to a sum of up uh sum up to nine or sum up to n okay so that means the basic idea is if we just reach out anywhere that's uh that say we find out that the maximum value is something like this and then no issues just return of the value right and say if we find this then simply return the value over here but i think you can i can make you understand that the idea is to just find the maximum uh like the maximum digit value we have over here because that will be the sum up to that number if you just look carefully another example so there are eight two seven three four okay so eight two seven three four how can you reach a you have to have eight ones so that means you have to have eight uh deci binary positive numbers right that the minimum you need because the largest uh number largest digit in this uh indeed like in this string n is eight okay and if that is a eight then you must have eight digits like eight ones right if you have eight ones that means the eight times the numbers get started like this whenever is you have to get that exactly right so that's the idea behind this question that's the basic idea behind this whole question that to find the max of any number like the max um or digit value in that whole number so that's the idea you have okay so uh let's write some code this won't be a bigger big code or something complicated this is a simple code and let's write that and then i will explain you how the code works over here okay awesome so here you can see we just uh um like we submitted our code over here it works fine so fine let's try to understand what exactly we did we took a variable answer bring storing the maximum integer value that we can over here so uh since our return type is integer that's why we took it as an integer value over here all right now uh for and next we ran a for loop and it's like for each loop in like we converted this string into an character array and we just traverse to each of the characters in the character area okay and like each of the characters what we did we found the math.max and converted did we found the math.max and converted did we found the math.max and converted our character to integer and found a maximum value with respect to the answer so we took our answer value to be zero initially so that's the uh minimum you can say because a negative cannot be answer right so we took it at zero initially and just found out what the maximum uh digit value we have in our string in okay and thus after finding the maximum value we just returned the value and that works super fine that's like completely accepted and so acceptable answer right so that's all uh in this question guys so i hope i can make you understand how this question works so make sure you just like this video and subscribe to this channel as well also if you have any doubts or any queries like put it put them down in the comments below i'll be happy to help you out in the comments as well thank you all for watching this video hope to see you soon in my next video as well
Partitioning Into Minimum Number Of Deci-Binary Numbers
detect-pattern-of-length-m-repeated-k-or-more-times
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._ **Example 1:** **Input:** n = "32 " **Output:** 3 **Explanation:** 10 + 11 + 11 = 32 **Example 2:** **Input:** n = "82734 " **Output:** 8 **Example 3:** **Input:** n = "27346209830709182346 " **Output:** 9 **Constraints:** * `1 <= n.length <= 105` * `n` consists of only digits. * `n` does not contain any leading zeros and represents a positive integer.
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Array,Enumeration
Easy
1764
4
hello friends welcome to geeks for geeks today we are going to learn how we can find the median of two sorted areas of same size problem statement there are two sorted arrays a and B of size n each write an algorithm to find the median of the area obtained after merging the above two areas that is array of length 2 n since there are 2 n elements medium will be average of the elements at index n minus 1 and n in the area obtained after merging erryone and airway 2 for example there are two input areas everyone equal 1 1215 2638 l2 equal to 13 17 30 45 after merging these two sorted arrays we will have 1 2 12 13 15 17 26 30 38 45 medium would be 15 plus 17 by 2 which is 16 method 1 we simply count while mooching use merge procedure of merge sort keep track of count by comparing elements of two areas if count becomes n we have reached the medium take the average of the elements at indexes n minus 1 and n in the merged array for example we apply the procedure of merging two arrays until count becomes n which is 5 here and then we simply take the average of middle two elements but the complexity of this method would be big off in second method is by using divide and conquer technique with log n time complex they note both the areas should be of same size in we take the base case when n equal 2 anyone be a 1 a 2 and array to be B 1 B 2 we know after merging these areas the first element will be minimum of a 1 comma B 1 and the last element will be maximum of a 2 and B 2 between the first and the last element remaining two will be there which will be maximum of even comma B 1 and minimum of a 2 comma B 2 they both can be in any order but the middle will be the sum of these two elements divided by 2 therefore order does not matter so I have mentioned them in brackets which means they can be in any order when n is greater than 2 let us take n equal 5 case 1 when millions of to Ares are same that is M 1 equal M 2 after merging all the elements less than M 1 and M 2 will come before M 1 and M 2 they can be in any order but total n minus 1 elements will be there and similarly after M 1 and M 2 n minus 1 elements will be there in any order therefore Medan will be M 1 plus M 2 divided by 2 which is M 1 equal m to case 2 when M 1 is less than M 2 so in the merged array before M 1 definitely a 1 and a 2 will be there B 1 and B 2 can also be there so maximum of four elements be there before m1 that is maximum of n minus 1 elements and after M 1 B 1 and B 2 a 4 a 5 can also be there but not before and b5 as they are greater than m2 after em 2 B 4 B 5 a 4 a 5 can be there again this set can have maximum of 4 elements we want m array of n minus 1 and M array of n so we can cancel out the elements before M 1 and after M 2 so we can change the start index of array 1 to index of M 1 and we can change the last index of array two to index M 2 when M 2 is less than M 1 so in the merged array before M - 1 so in the merged array before M - 1 so in the merged array before M - definitely B 1 and B 2 will be there a 1 and a 2 can also be there so maximum of 4 elements will be there before M - 4 elements will be there before M - 4 elements will be there before M - after em - a 1 a 2 B 4 B 5 can be there after em - a 1 a 2 B 4 B 5 can be there after em - a 1 a 2 B 4 B 5 can be there but not a 4 and a 5 as they are greater than M 1 after M bonds a 4 a 5 B 4 B 5 can be there again this set can have maximum of four elements it won't an array of n minus 1 and M array of n so we can cancel out the elements after M 1 and before M 2 so we can change the start index of array 2 to index of M 2 and we can change the last index of array 1 to index of M then we recursively call they get median method and that n becomes 2 for which we have discussed the medium already example given n equal 5 everyone and area to since M 1 is less than M 2 we take everyone from fifteen to thirty eight and from Eric to we take from start to empty that is to 317 again in the new areas M 1 is greater than empty so we take fifteen twenty six and thirteen seventeen Medan equal maximum of 15 comma 13 plus minimum of 3 6 comma 17 which is 15 + 17 / - 16 now let's 17 which is 15 + 17 / - 16 now let's 17 which is 15 + 17 / - 16 now let's look at the code yet median method takes three arguments array one era - and size three arguments array one era - and size three arguments array one era - and size of n that is n if n is negative we return -1 as it is invalid if N equals 1 return -1 as it is invalid if N equals 1 return -1 as it is invalid if N equals 1 we return the average of the first elements as discussed before if N equals 2 we return maximum of 3 1 0 comma area to 0 plus minimum of every one added to 1/2 if n is greater than 2 we first to 1/2 if n is greater than 2 we first to 1/2 if n is greater than 2 we first get median M 1 and M 2 if m1 equals m2 we return either m1 or m2 if M 1 is less than M 2 then if n is even we return get median every one plus n by 2 minus 1 comma 2 comma n minus n by 2 plus one else peak return depth median array 1 plus n by 2 added to n minus n by 2 similarly when M 1 is greater than M 2 we return the other house thanks for watching this video I hope you like this please leave us your likes and comments
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
934
hi guys good morning good evening welcome back to the next lecture of our series it is the last video of our BFS and DFS traversal which we have been doing so far it is the mix of both BFS and BFS for your uh like in this video we're gonna see the power shortest bridge but if you want to try on you can also try minimum cost to make at least one minute before further Ado let's start with the problem itself what the problem is saying it's very normal as standard the mattress question which we have been seeing so far but you will actually see what is the pick behind it the person saying that you are having a n cross n binary Matrix which means you are having a matrix which is binary having numbers in a matrix as 0 or 1. where one represents land cool zero represents water as we have been seeing okay one represents land water you can have any number represent anything cool and I land is a four directionally corrected group of ones not connected to any other ones they are exactly two islands in the grid so basically we have the Grid in which one connected group of ones is one Island and one get a group of ones is another Island and in total it is saying that you have exactly two islands performance exactly two group of ones cool uh you may change your zeros which means water to one to connect two islands basically between two islands you have water right so to actually connect piece to eye lens you can replace your water with a line so that these two islands will actually connect that it is same return the smallest arguments smallest number of zeros you must flip which means change your 0 to 1 which means change your water to land smallest number to flip that you need you can connect two islands let's look at the problems examples very easily I have shown your example a form of a grid Matrix so one represents land which is in green color and zero percent water which is a blue color uh so what options you can have is you can just replace this as one now see initially it is not connected it is one Island they are not counted although you could see that okay they are when they are at this touch but when we say connected we say four directionally connected which means Left Right top bottom it is four directionally connected it is not if I just add one element here of an element here then these will be connected to each other which is also continued so now clutch will make them connected I can add a one here or I can add a one here it just connected so number of smallest number of zeros I've flipped to actually connected was one I can flip just one zero and I can just connect them both the islands are now connected answer is one in the next example I have one Island here and one Island here to actually connect them I can just replace water one still it is not connected because still you can see it's not connected or now I can just replace a one here or what I can do is I can replace a one here now they are connected so how many ones I have to add I have to replace two zeros to ones to actually make these two islands as connected in the next example what will happen you will see you have a Green Island you have the next of this island to correct them you can see you can change any of these water locations you changed it right here now it is become one it is now done it's now an island so now you can see it is now connected now you have got just by replacing one zero you have got the island now the first thing okay Aryan uh as I read the questions I have been given the smallest number of the zeros I need to flip which means from one Island in smallest number of steps I need to reach to the next Island so uh smallest number of steps which means shortest path from one Island to the next Island shortest path oh shortest path from one place to next place I can do a BFS but Aryan it's an island which means every of the land parts are very different and Scattered which means okay it is one Island in which every of those part are very scattered right uh from which of the set because I knew one thing that we start BFS from one node right so from which nodes shall I start how to choose that node uh not sure right so why not let's try with every possible node which means from one Island I need to reach to the next Island so how about from this land piece right here I just tried to do a BFS and reach in a shortest step to the next Island which means I just had to do a BFS and reach this island in one two three four steps all I can do is I can just try and reach from here to here as simple as that again reach from here to here and as soon as it reach it just is adjacent and it can just connect two islands what I can do is I can reach from here to here I have multiple ways which means I can do a BFS travel self from Island one of every which means I have to do the BFS traversal from every node of the island one I'm then I can reach my Island too what's the complexity like then if you just say okay you have to do the BFS drivers from every note of the island one every node how many nodes can be there n Square nodes because worst case it can be half full cool to do the BFS traversal from one node in a matrix as we have seen it takes n Square time that seems pretty large gnome although it can happen that your solution might get submitted but it's way too large can we optimize it just a question for you what you would see what you were trying to do was you just go on from every cell and you were trying to do a BFS right individually I just ask you one question why it is necessary to start individually which means if you have this island right here why not you can start BFS from every cell simultaneously which is actually a multi-source BFS which is actually a multi-source BFS which is actually a multi-source BFS which we saw in lecture 8. how a multisource BFS is done it is nothing but rather than starting from one node itself you start from multiple nodes simultaneously as the first nodes so basically in one step what will happen is these all it will go here uh sorry um yeah here you see in one step I just try to expand my Island one it is nothing but a bit first search earlier I was fine okay let's go on to every land piece of Island one and try to do a BFS but because of that I am going on to every land again and again rather start BFS from the whole island itself and try to expand that now in The Next Step what will happen is my Island will what will again expand because I said which is cry always try to expand birth first search breath wise it expands okay cool it's expanding expending now full step one expand it step two expand it is nothing but we are doing a multi Source BFS which means from multiple nodes I'm just expanding out right that is it now what will happen is in the next step it will just again go again and now you will see that your one has reached here which means it is now connected so in a step three we have just reached how simple it had become firstly what you did was you just grabbed all the elements of your Island one all the elements of the island one in the next step okay how to grab all the elements of the island one but just a simple EFS just grabbing all the elements in one whole position what we do a third pill how is a third pill finding one component a flat fill exactly same thing that okay you just grab all the elements and you are good to go so you will just do a EFS traversal to find the elements in the island one and as soon as you got all the elements you will just start your multi-source BFS to actually reach to multi-source BFS to actually reach to multi-source BFS to actually reach to Island 2. as soon as you reach Island 2 it will be the shortest distance which means the minimum number of smallest number of zeros which you need to flip and that will be my answer now let's see the code pretty quickly it is exactly very easy finding the component anything you can say we have seen in the last videos very clearly by Aryan why you just wanted the drivers the right then you can also do that by BFS while you're opting to do the person yeah for sure you can get all the notes of your Island one by just a breakfast search traversal also because finding one component is just traversing that component and Traverse so it can be completed by both PFS and DFS but I've always said a TFS food is much shorter in comparison to a BFS food so it would be faster that is the reason faster results to write to code in an interview to code in an honest display it will be faster that's the reason we just think of the depth first search way to actually find the connected component which means the island one notes cool now let's look at the problem it's very simple but firstly I have initialized everything which means visited array my directions which is food racing connected which you have seen in the last videos also but it's the connector node 10 hours and rules of production connected all that stuff uh we move to x i plus 1 comma j i minus 1 comma j i comma G plus 1 I comma J minus one and so on so that is we have this direction uh I have this tube as a pair of in command you can also have a Q of vector um but it is much slower in C plus so pair of incoming is much faster but I have shown you both the base in the last videos also uh now everything is initialized I will just go on and try to find the island one so as soon as I reach the first moon which is the line I will do a f versus traversal from that first node first land node I will just try to do a tip for search traversal with that I will visit the entire Island one but I need to make sure that all the nodes of Island one I need to push it in my queue so what I'm doing is it is a standard simple step for search traversal that I'm just moving on to the base condition which we have which you have seen so many times that the first condition is it should be inside the grid it should not be visited it should be aligned if any of thing violates which means if it is not a lan if it is already visited or if it is out of bound I need to return that is it now as it is valid cell I can go on firstly I will make Terrace user because I don't want to use that again and again I will push that in my queue because I need to start a multi-source because I need to start a multi-source because I need to start a multi-source BRS from my Island one position I am pushing that in my queue and now just going from that cell going on to the every of those neighbor cell from that cell going on to every of those neighbor cell to actually do a standard for search traversing now what you have found is you have just got all your iron one nodes in your queue now you can actually you have you can just have any variable that's a flag and you can just break out this whole part because you have to just do a Traverse on your eyeliner one so that you have got your all the elements in your queue now you can set your multi Source BFS cool I will just start my multi Source BFS by my queue is not empty I'll just grab the size which means I want to do a level wise traversal that's the reason I will just grab the size until my size which means until my third level is not empty I'll just keep on grabbing the nose of that I will find the neighbors of that self whatever neighbors are there which is nothing but left right bottom and top I will check if that cell if that enable is actually a ballot cell or not and if it is not visited so far if it is the case then I will actually go on and push that Neighbors in my queue and also mark them as visited but before pushing and before marking that as visited if by any how I can see that oh I have reached another cell that was one and as you can see it is not visited which means it was not visited by Island one it is not visited so it is the island too and it is the land cell it is not visited it is an answer for sure it is our Island too because I learned two cells were the only cell that were not visited that's the reason I will just return the number of steps which I have been increasing on every of those my as soon as I just grab the level wise traversal which I'm doing I'm just increasing my steps ultimately if I am not able to reach then I have to turn up minus one the time complexity is nothing but o of n Square because in one step you just went on to Island one and did a TFS traversal which is nothing but o of n Square as soon as you grabbed the elements of those Island one which is nothing but multi Source BFS at Max you can go up to O of n Square again to actually just expand your Island one to actually reach I want to that is again a o of x square inputer you have publicity of O of n Square so from o of n r four it reduces Work N square that is how beautiful you solved it space is nothing but over n Square same for Q for recursive stack of uh EFS Q of BFS and visited array as we choose to take it and the code for C plus and Java is down below exactly same code you can just have this PDF with you open it parallely as I'm spinning exactly you can see exactly the same code the same function of TFS initializing and calling that function of TFS to grab that Cube and just foreign
Shortest Bridge
bitwise-ors-of-subarrays
You are given an `n x n` binary matrix `grid` where `1` represents land and `0` represents water. An **island** is a 4-directionally connected group of `1`'s not connected to any other `1`'s. There are **exactly two islands** in `grid`. You may change `0`'s to `1`'s to connect the two islands to form **one island**. Return _the smallest number of_ `0`_'s you must flip to connect the two islands_. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 1 **Example 2:** **Input:** grid = \[\[0,1,0\],\[0,0,0\],\[0,0,1\]\] **Output:** 2 **Example 3:** **Input:** grid = \[\[1,1,1,1,1\],\[1,0,0,0,1\],\[1,0,1,0,1\],\[1,0,0,0,1\],\[1,1,1,1,1\]\] **Output:** 1 **Constraints:** * `n == grid.length == grid[i].length` * `2 <= n <= 100` * `grid[i][j]` is either `0` or `1`. * There are exactly two islands in `grid`.
null
Array,Dynamic Programming,Bit Manipulation
Medium
null
929
hello friends so today we're going to discuss a interesting problem asked in google interview and this will help you to understand how to pass a string given some constraints i will tell you two examples but the question statement first like read down this question statement the question name is unique email addresses and it's an easy problem if you understand the logic it's very easy so the problem statement states that uh like in any email you are given the email is of this type okay alice at the rate okay but there can be two things the first thing is a dot and a like the plus sign if you add period between some character to the local name so the any like email address has two part the first part and the address part so alice is the local name and lead code is the domain name you all know that okay but now if you put a dot in the local name then also actually it doesn't actually really cares so like if you put a dot lice then this is equivalent to a lic alice is equivalent to like a dot lice is like they both are equivalent so like there is no difference between them as you can see this and this are both straightforward so like both of these email addresses if you send email to this or this they will go to the same address but okay but this does not apply to domain name domain names are different if you put like lead dot code and lead code they are different but alice and a dot list are same okay now if you put a plus sign in the local name then all the characters after the loop plus sign are ignored that's also thing they are given as you can see in this if it is m dot y plus name so before this at the rate of sign and like plus sign every character is disappeared so this is actually equivalent to this my at the rate of i hope you my at the rate of i hope you my at the rate of i hope you understand so you are actually given a number of emails and then you have to upload how many different emails are present over there okay so that's the first thing now because domain name the second part after the at the rate of part that should be different like if there is a lead dot code it is different from lead code but for the first part we have to see so what you can see here is first try to like separate this in two different problems the domain name problem and the local name problem so first like parse out the local name as well as a domain name if the different domain names will be different then we will like try to smaller like smallify the local name according to the constraints if they are dot ignore it if there's a plus sign like ignore all the plus characters after the plus sign and then we will again add the domain and the local name together and then that's the final string and then we can put all these different strings in a set because set will construct only one type of string and then we will find out in the end the size of the set and that's the whole question but now how we can find out the domain name as well as the local link differently that's the first thing how to pass out the string now there's one thing that you can see here is the add the rate of sign it actually is the like the middle point before the like domain name and the local so that's the main thing you can use so what you can do here is take the input of that string and start popping out the last character as you go from like right to left start popping out the last character till you reach the at the rate of sign until you don't read that the rate of sign keep popping out the last character and then in the end you will like separate out the domain the rest of the is the local name part so i'll tell you how let's see this example uh let's copy it out okay then first like take an empty string s let's assume then keep on popping out the last character and put this and push it in this string okay let's assume that c oh just put it in this for formation till that you will not reach at the rate and then in the end you will be having this string stored in this now again pop out the last character at the rate because you don't need that then the rest of the string is the local input so you can take out the local lane and what you'll do you will it go from left to right in the local name only if you encountered a dot leave it if you encountered a space just break out of that uh for loop and that's the because you don't have to look forward to the other part and then in the end join the local name as well as the domain name that's the whole trick a few days back one of my friends asked me to pass out a string in which you are given some day month and then a year now that's the like let's assume that year is always four digit okay like it is always like 217 or 1997. okay now month can be like 12 or like 0 9 or 7 and so on and they can also be like there's no zero that's the whole thing like it can be 7 it can be 13 it can be 21 now how will you pass out the strings and then the main thing is this forward slash will help you to pass out just move from left to right sorry right to left and keep on extracting out the last character till you reach the first forward slash and that's the year then again keep on starting out the from like from right to left and then you will get the month and then the last of the remaining string is the monday so that's how you can pass out the strings you have to find out some like similarity or how to find out some pattern so that you can easily extract out the material which you want okay so that's the whole thing in this question let's move to the code part now for this question i'll zoom it out a little bit okay so the question statement in this question statement you are actually given okay it's loading yeah so you're given the an email size of the n emails make a set to store all the different strings now for all the strings iterate over them then this is string back to find out actually your domain name so what you'll do you will do a while loop and then you will keep on extracting out the last character like with how you can get the last character of any string email i because you're on the ith string dot pack will tell you the last character and then what you'll do you will add this character to the back string so i have it over the string and added that string to the forward of the back string and then pop out the last character till you reach the other rate of sign then after reaching the other rate of sign you will block like break out of this while loop but still the other rate of sign is there in the string so again pop out the last character then you have the back string ready in this string the domain name and then you have to find out the start string which is actually the local name so now for that you'll hit it over from light like left to right and then whenever you find a plus sign you just break out if you find a dot sign you will continue but if you find like any other sign it's a character so you will keep on adding it to the start string and in the end the final string is actually start plus this additive vector and the back so this will actually get you the final string and then you will insert this final string in the set and if there are two same type of strings they will not insert the only one type of string will insert in the string or in the set sorry and then in the end you just return on the size of the set i hope you understand the logic as well as the code of this problem if you still have enough speed mentioned down thank you for watching this video i'll see you next time keep coding bye
Unique Email Addresses
groups-of-special-equivalent-strings
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Array,Hash Table,String
Medium
null
167
in this video we're going to take a look at a legal problem called two cell number two input array sorted so given a integer array and a target sum we're given we're asked to find two elements in the array that has a sum that is equal to target so in this case we cannot use the same element twice um and there must be a solution in the array so here you can see we have an example of array and target in this case we have one and two right so the first element as well the second element has the sum of nine so we're just going to return that in the array integer array form and here you can see we have another example two three four which has a target is equal to six and then we're going to return their position in case one and three so two plus four which is six right so and here you can see we have another example where we have negative one and zero and the target is negative one because we cannot use the same element twice so we're gonna have negative one plus zero right so we must have two elements add up to equal to the target so therefore in this case we uh we're gonna have negative uh sorry we're gonna have one and two right first element the second element so to solve this problem what we're going to do is we're going to use pointers right one way we can do this we can use a hash table but this is this will give us a linear space complexity so it's not the most optimal solution so we can do instead is we can use eight pointers right two pointers to solve this problem by having a pointer on the left and pointed on the right um and then what we're gonna do is we're gonna get the sum for those uh elements that the pointers are pointing to in this case one plus six which gave us seven and the target sum is six so therefore we have to move the left pointer or the sorry the right pointer one to the left now we basically decrease the sum right and now the sum is less than the target sum in this case one plus four is five so five is less than the target sum now what we have to do is we have to think about how we can increase the sum of those pointers by moving the left pointer one to the left sorry one to the right now we have two plus four which give us the target sum so now we find a pair and we can just return those elements position in this case it's going to be the second element and the fourth element right so now we just return that in a array form so let's take a look at how we can do this in code so first we're going to define um our base case right because there could be a situation where the array is empty uh let's see sorry there the constraint says that the array might not be empty so let's just okay so what we're going to do is we're going to define our pointers right so we're going to define our pointers and then we're going to do is while the pointer doesn't uh does not meet right does not meet each other or does not go past each other uh we can just continue to check to see if the sum of those pointers is equal uh the elements that the pointer is pointing to the sum is equal to target so just like binary search if it's not equal to target uh we want to see if it's bigger than target if is it if it is bigger than target we're going to move the right point one to the left right and then if it's less than target we're going to make sure we increase the right left pointer by one right so we're gonna make sure we do two pointers um find the cell right and then first we're gonna have our integer so our left pointer which is point zero and is equal to uh numbers.length and is equal to uh numbers.length and is equal to uh numbers.length okay and then we also have our right corner which is going to be n minus 1. now we're going to once we define the pointers then we're going to say while left is less than the right uh because we cannot use the same element twice so we're going to have left is while left is less than right so what we're going to do is first we're going to define the sum right so the sum is equal to numbers at left plus numbers at right so once we have the sum just like i mentioned we're going to see if sum is equal to targets so if it is then we're going to return their position right so in this case we're going to return new integer array right with these elements right so we want to make sure l plus 1 right plus 1 in this case because the array is 0 base so we want to make sure we inc plus 1 to return the element's position else if we have a situation where sum is less than target so remember if it's less than the target then we're going to move the left manner by one so increase the left pointer by one otherwise we're going to move the right one to the left right so we're going to continue to do that if we found that there's no solution then we're going to return just negative one right so now let's try to run our code let's try with a few more examples okay let's try to submit so basically this is how we solve this problem in a linear time complexity as well as a space constant space complexity
Two Sum II - Input Array Is Sorted
two-sum-ii-input-array-is-sorted
Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`. Return _the indices of the two numbers,_ `index1` _and_ `index2`_, **added by one** as an integer array_ `[index1, index2]` _of length 2._ The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice. Your solution must use only constant extra space. **Example 1:** **Input:** numbers = \[2,7,11,15\], target = 9 **Output:** \[1,2\] **Explanation:** The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return \[1, 2\]. **Example 2:** **Input:** numbers = \[2,3,4\], target = 6 **Output:** \[1,3\] **Explanation:** The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return \[1, 3\]. **Example 3:** **Input:** numbers = \[\-1,0\], target = -1 **Output:** \[1,2\] **Explanation:** The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return \[1, 2\]. **Constraints:** * `2 <= numbers.length <= 3 * 104` * `-1000 <= numbers[i] <= 1000` * `numbers` is sorted in **non-decreasing order**. * `-1000 <= target <= 1000` * The tests are generated such that there is **exactly one solution**.
null
Array,Two Pointers,Binary Search
Medium
1,653,1083
59
hey what's up guys it's Nick white I do tech encoding stuff on Twitch in YouTube and I do all the leaker and a current solution so if you want those explained up playlists I do like all of them so just check those out on my channel I guess everything else in the description I just did one called spiral matrix on leak code and then I saw spiral matrix two and three exists so I'm just gonna do those two spiral matrix two is literally the same question basically it says given a positive integer n generate a square matrix so that makes it easier actually because the last one was kind of arbitrary on the width and height spill filled with elements from 1 to N squared so if they give us 3 then 1 9 I don't know why they don't just give us and giving us N squared makes that even easier too because then we could just declare the matrix with they give us the width and I basically 3 by 3 so 1 2 n we just basically do the exact same thing and the other one except we fill the array with values from 1 2 you know whatever n is squared so I mean it's the same thing I'm if you watch the first one you don't need to watch this if you didn't I guess honestly check that out because this is that probably I think the first one was better here we go so you're just gonna declare a matrix so we I'm just gonna call it red you know return array or whatever return matrix you can call it red right that's a lot of what we call a lot of these so with the sizes the dimensions there we go and then we're gonna have our boundaries once again let me explain this we didn't see the other video I guess we keep a boundary of the row beginning boundary the row end boundary so the row beginning would be 0 and the row end would be n minus 1 column beginning column end and as we do a spiral traversal which if you don't know is you know 1 2 3 4 5 6 7 8 9 and we have to do you know we do we're doing a spiral traversal up to 1 to N squared and putting them in the square matrices as we do this traversal when we traverse the first row we move the row beginning boundary up by one as we traverse the last column we move the count we decrement the column and value boundaries so we move the boundaries inwards till we traverse every element and that's pretty much it so same exact thing is the other one so row begin is going to be 0 intro and the boundary is going to be n minus 1 into column begin zero column end equals n minus 1 same as last time conditions the same two row well row begin is less than or equal to row and I've chopped it all into my throat so maybe scratch what I said at the end of the last one and column begin is less than or equal to column end that's the main condition just make sure we're within the boundaries we do four different loops so I is going to be set to column begin while I is less than or equal to column and so while we start at the first column indices and we get to the last column indices we will set matrix of you know what we did in the last one so we're doing columns right now so we're gonna do row begin because we're going down the first row for every value that we go and we're just incrementing the column value so column bellies I is going to be equal to okay and now here's the only other different part is you're gonna have a counter or some kind of number so we could just have counter is equal to one because we're going from 1 to N squared so it's gonna be equal to counter and then you can do counter plus right here or you can just do counter plus right here so I'm just gonna do that I think it looks cleaner it's just incremented the counter by one because obviously we have to increment by 1 as we do the these traversals and then like I said we just have to we traverse the whole first row when we do it all these column indices so we just do row again we upgrade that boundary we increment that boundary by one so now this whereas been traversing this is the beginning row now and then we just do that for four different Lu so what do we do now we go down so we're going from Row begin to row end and setting matrix of I column and because we're at the last column incrementing the row only is going to be equal to counter plus same deal here we traverse the last column completely so we can now decrement the column end boundary and then like just like the last one we've changed these values within this loop now so we have to do conditionals from for our last two loops because we change these so we could have broken Row begin can now easily be equal to row and so we have to just do a check now and then we do our last loop so we're at the we're going to from right to left so we're going from column end to I greater than or equal to column begin to the beginning boundary and we're D commenting this time because we're at the end which is a greater value than the beginning and then we're setting the matrix of what is it we're at the ending row now so the row end we're traversing the entire row end with I is equal to counter plus same thing still incrementing the counter though because it's increasing in value as you do the whole traversal and then we traverse the whole last row so we can change the row end boundary we can actually determine that now and then column and while column begin is less than or equal to column n because we did update this up here we want to make sure we're still within the constraints of that column and then we do our final loop here I is equal to we're going up so we're going from row end to I greater than or equal to row begin boundary decrementing our count thing here our thing I'm getting pretty lazy here if I'm just saying our thing what is it we're doing I for the row indices and then we're going from the beginning this is the beginning column boundary it's the first column so we're going for column beginning boundary is going to be equal to the increments of counter and we traverse the whole first row now so row I mean the first column sorry the first column right because we want all the way up so column begin boundary that's the whole thing you fill it and then incrementing the counter each time so as we go from left to right we got one two three you know beginning column to end column with the counter incrementing one two three four five because we go down here we go left right to left here 5 6 7 etc right and the boundaries keep moving and it's a spiral and if it was a bigger example you'd be able to see better I think that's the only thing they have to prove otherwise I kind of like this question a lot pretty cool I want to do some more 2d array stuff I really like 2d arrays and then you return res hopefully this works I maybe I messed up I never did this ran this one before I just saw it's like the same thing matrix yeah oh crap I'm saying matrix it's actually called the res so just make sure you don't have syntax errors yeah I've been done this one usually I practice one time before I make a video but didn't this time okay there we go ran it perfectly let's submit it there we go that was C my first submission there we go that's it's the same as the last one I knew I would work it would work right away when I saw it's literally the same thing as the last video you're just actually incrementing a counter and going from 1 to N squared so if you check out the other video it's exactly the same so I just made this because I wanted to make a video on all of them so hopefully spiral matrix 3 is a little bit different I'm kind of excited for that one so check out all my other videos I do all of them once again and thank you guys for watching so see you guys next time
Spiral Matrix II
spiral-matrix-ii
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order. **Example 1:** **Input:** n = 3 **Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 20`
null
Array,Matrix,Simulation
Medium
54,921
378
Hello everyone welcome to my channel, today we will give challenge question of number two. Let's see the question. A question is that smallest element is sufficient water meters given in process meter is illicit liquor collection shifted in ascending order return's smallest element inter. metric notification smallest elements of this order no due element you must find solution with memory complexity better than out of square soham if it is that you have kept one meter from this which is completely sorted in ascending order is gifted with more short and column what do we Smallest elements meter to remove air, it is okay so let's see the matrix okay matrix if this is the example given to us from late 150 phone no 80 eleventh thirteenth and value MP3 that and 15t is what is given to us from China that if given to me Okay, if we consider this a method, this question is coming to our mind every day that what can we do, we can make a trick, we can make a person, we have filled all the tricks in the elements, okay, we have applied short function, what can we do? Can do the position element directly, okay this method or complexity means it will be very useless if it is put into it but we should subscribe and subscribe only then what can we do that if we want to make it better than this then what can we do? We can do this, we are doing travels, okay, but if we use the method of making a person, if I have made a maxi, okay, then this is a maxi and what we do is that we put the element starting in it, this is how we inserted the pipe. 155 inserted, not inserted, okay, let's keep its size, okay, keep it, sit, Kunwar is okay, we covered it late, and our third means our elements have gone till thirteen, okay, like fun, this is the total element, because here, there are nine elements, size three grocery. No Limits and March a Gorgeous in Matriculate Tell us then if the destinylessness goes as our fifteenth will go then we will check the team that it is not full of mine and the stool will bump our jeep and set the size of this to know how it is mine It is not getting bigger, if it is equal then we will pour the top element, okay pinpoint of key and Buddha, meaning, what can we do in the last, we will complete the traversal, what will be left of us, meaning we will then return directly. This means that if you are okay, then you will return the limit from me, which will basically be our maximum element because it is the maximum. Okay, so in this way we got the maximum element and in this way we will return. Let's see the code of this particular approach. In this political form, it is better than that, in this way, if we were to do this as normal then we would also be adding dry ginger to it. What are we doing in this, it is being made on traveling but here the meaning is to score. Then log in people, this means that to Shravan, I confirmed the PQ dot, cleaned the matrix and directly pushed the matrix every element in my pc and then I checked every time, check that this size of mine is 38. It is getting bigger, it has become bigger since late, Jain, I am pausing it, one element at its top end, then what should I do, then I am placing WhatsApp on the table, then I am getting the element of maximum element, then this process is my code and submit. It will be done, let's see, I am running in your show Mera Voice, it is better than late, we have to do it, okay here because a little more meeting is required in this, complexity memory complexity is better, see in this you must find a solution to If memory complexity is a battery saver then what should we do? If I comment on it then what should we do? We can do research in it because look at one side but here we see one thing. If you have any question then you have to see this question pepper. This is a complete shot, meaning it is from top to right, this is also a shot and from top to good, join this for decoration in the recorder, it is complete, so how can we put it in this, okay, meanwhile, we have done this, we have to find the limit, okay, so what will we do, right? Basically, what are we going to do? Normal - What are we going to do? A we going to do? Normal - What are we going to do? A we going to do? Normal - What are we going to do? A little bit - Some of us will modify it a little bit - Some of us will modify it a little bit - Some of us will modify it a little like our first element we will take one is okay, the last element we will take leave means this is our 0's this is our end minus one is okay so then What have we done, we will find out the but this particular if - we are extracting the juice, starting left, if - we are extracting the juice, starting left, if - we are extracting the juice, starting left, we have taken this, right, we have taken this, and but let us find out the meaning of this, which is this of the eleven, I will check this eleven, okay because it is sorted. Okay, it is short, we know this much, I will check this eleven directly with you, this message came, I took out this lemon, how did I make it, Bandhan Left, what does it mean to take out, madam is equal to male plus right - l madam is equal to male plus right - l madam is equal to male plus right - l divide 222 yo It is true, no, it is true, so this will come out of ours, it will come out, madam has taken it out, so what will we do, then we will check this particular element, what are all the elements smaller than it, what is its size or then mother will become a case in it. We will basically calculate the account, this means, we will calculate the account of this political America, how much will we calculate the work of that thing due to which how small are the elements, okay, then how many elements will make it small, if those elements are total, then it will have two cases, then this account will have as many accounts as my song. Two cases will be created that if my account is big then how come this account is small or it is equal and these two cases have been created Sanam this thing has become now this is what I will check means this is what I will check that If I am or and according to that I will update my left right late, this is my account which is big, okay this is my great application then what should I do if my account is which is full of which means What is mine that if I have a stomach okay if I compare in this that 11:00 is if I compare in this that 11:00 is if I compare in this that 11:00 is greater than it is okay 1111 dresses is mine yes okay so this is my good fortune I will update the right in this means left mine The answer may come, okay, so this is because my account is big, okay, how then I will update it here on the right side to e-mail plus one minus one, I am e-mail plus one minus one, I am e-mail plus one minus one, I am okay, it is my minor and in this, I will update this on the left side. I will make it equal to left plus one and I will stop the alarm clock. Okay, this thing is done. Okay, now in this way we will do our travels in the entire solution. The second thing that happened is that if we get late people, then there is an account in it like The functionality of the account that was done is to withdraw this account, how to withdraw it, this is the direct way to withdraw it, meaning what can we do if one of my particulars is above late, I am fine, this is a particular, we know what we have on it, withdrawing it from late I am melanin element, like suppose you are definitely excited after seeing a particular hard disk throw one, neither can I apply binary search in every rupee, but then if I take K as my target value and measure on it that this value If you are deciding the necklace in this, then accordingly I will get its type, okay, but taking it out, basically, it is the add which is directly bigger than eight, I will get the line, okay, so this valley is done, now this will be the value of the note, meaning. All the elements before that will be small, so the problem with its index will be that if I make its starting index 20, then it will be combined with this, then how many elements will be smaller in this row, then that is fine, this and each one. Particular that I have to withdraw the account, it is okay to withdraw its eleven separately, so for 11:00, I first separately, so for 11:00, I first separately, so for 11:00, I first checked the above, so two and okay, this one, I checked this one, I am okay in this, how many of these are in the middle part of mine, how many are in the small ones. It will be eighth, if my target day is what will be, then here I have taken seven zeros because one of mine will come here, neither 8 means small, nor is there any, nor are the stars big, so I will calculate it accordingly. And then I will add everyone and a picture of mine will be there and my answer will be there and if it is understood by the court then it will be clear. Sonu Nigam, if mine is like this, I did a binary search in this mask. I elbowed you and here I have passed my matriculation, whatever was mine, passed, I will kill the director, look at this, what should I do, I opened the left, took the first element, okay, I took the last element on the right, okay, last elements of Rambo size minus. One and half inch is ok so I have made one of its size, I have made an answer, ok to find out my answer, then I have used normal - then I have used normal - then I have used normal - now in this I have taken out ok, I have taken one account, the account is threaded in the beginning, but what will the account basically check for me? With the help of this, whatever matter is the minute, like this is 11:00, 11:00, 11:00, this is 11:00, I am this is 11:00, I am this is 11:00, I am fine, I have calculated this, 11:00 to 11:00 fine, I have calculated this, 11:00 to 11:00 fine, I have calculated this, 11:00 to 11:00 is my target and my matrix is of M.Com excise. I will take out his of M.Com excise. I will take out his of M.Com excise. I will take out his account. Sir, let's see how I took out the account. Like I am taking out Eleven's account, we are fine, I was 11th, I took out his account, so what will I check to take out Eleven's account. I will start every romance with this code. So, according to this, what am I doing first, time is, I am starting from this point, it is okay that I am starting from this point, and what should I do here, who is mine, this is my and minus. One row, okay, so I have created two roles, one is controller and the current column is in the current day, this is okay, this is the last, okay, it is last and I have a current problem, which is the column on this side, so this is mine, how much is this mine. Zero thought in starting, I will request my starting volume from here. Ok Mitti, I took this to create an account, this is the answer for the account, which will be my account and then I put a while loop that why won't my row become bigger, meaning. This one will not go out of mine late from here and it has gone out or I have taken out the column. Okay, so in that case, I have put a limit on it, but the hero will always be filled, it will be equal to zero and the current. Columbus became present from these, if you relax and look at me, if I cycle the value of target from here, meaning, what is the target of mine, here it was 11:00, not targets 11th, okay, then 11:00, not targets 11th, okay, then 11:00, not targets 11th, okay, then look at this, target eleventh twelfth, my photo is equal, meaning. Did I get my small one which is 12:00? If this small and equal to which is 12:00? If this small and equal to which is 12:00? If this small and equal to target is not there then I will add control - - current - - done so where is mine control - - current - - done so where is mine control - - current - - done so where is mine reached this one point of mine has come up okay so this is my now Here it is appointing the button, okay that the tender is gone, now this is on my tab, so I will check it on time, see on the tension, I have come to the tone and run it again, okay then turn off my alarm and turn it on electronic true and correct. Off column in small and equal to target, checked again that my tanks are a smaller and equal to 11th exactly definitely here as it came then what should I do, I am adding in the form of current as I said upper limit is also out of this. Look, what are we doing here also we have the same thing, now we have to cover this also, so 10:00 My basically, if 10:00 My basically, if 10:00 My basically, if I take out this has to be stopped, this disease, if whatever it is, this is one, this is two, then its How much is one plus one, how to do it, so I added it to the account, okay, I added it to the account, and I added the current column plus, which means then I have reached the point that I have reached 11th. Now here this is my smaller and equal to okay yes so here also my 11:00 is yes so here also my 11:00 is yes so here also my 11:00 is smaller and equal to here I will add here again so again I will add this what time should I have coffee This prayer will not go, so this happened, then I saw what is happening then, but then we went ahead again, then it came on me, this meaning, then here it came to thirteen, when my affair with thirteen, then I should be bigger. So then I reached here but 9 inches, then I don't know, mine is small, okay look, the ninth is small, so it will be added to the line, it became tight in Noida and got the fiber dipped, so from this it will be three, from here it will become 2. From here I have my dad and from here I have how many adds, from here I have three and this is definitely from this bottom one, when hey man, I have continued this, okay so I have done it in this way. Okay, so this is how it will be for me 2012 Okay, so in this way my entire row has been added and then look what I did it in this way, I can remove it but late I can add one more I can do this method, if I don't do this, it's straight forward, if I do this for this function, which I am taking out to account, right, if this is how I do it for you, then I do it in this way, late, if I have an account, right? I will comment and I will go directly to the account if I have some idea about the appointment from the function, then I can apply the director powder here, to remove it, I have appointed and print M dot, kill both of them, m20, that comma is ok, so this When it comes, the target person is Meena and in this I am the mind, this is my contact, this is my address - what have I done - - what have I done - - what have I done - I now need to mean that mine - what will happen to the accident, this is my that mine - what will happen to the accident, this is my that mine - what will happen to the accident, this is my account of Plus, this is my address, I will have to follow right here. But half of i20 are small size, tax becomes two, so the index is that means from zero, but each one is particular and taken out, this is a particular Owaisi Travels tax, like I did in this, I am stopping adding like this, in current, in C, so like this. In this, I am taking out each particular element and taking out the last element. I am taking out the effect of this particular element. It is fine, so I have done this with Apabhramsha here, but here I will do it with only two lines, so semi things are fine. Here I have done this and this will be organized Moff had come that we had come that and minus I will do it in this Moshay dot Big Adda okay we can do this also in this way also and I will run it once Should I say that it is accepted, okay, you can do it in this way too, I will put both of these in the comment, that means there will be some code in the description, you can take it, now I have created an account, okay, so look further, the account as I got it, then here. In two cases, as I told you, if my account becomes equal to that increase, then I will set the answer to be erased, that is, my answer to that particular matter, this value of mine, has become my answer. Okay, and I will reduce my arm hole again, that is, it is necessary that it should hurt, if you look at me, if my account has become big since late, my account here has increased from date to left, it has become full, okay I Here, this file of mine has become 209 from late, okay, so that means that I should make it smaller than the next mine, so I will go to this side, that is, I will go towards the left, if you are filled with the possession of if, then towards the right and I will say inches, okay, so I will make the flashlight mid-meet-one, make the flashlight mid-meet-one, make the flashlight mid-meet-one, so I mean it should be on this side, it should be on the start, it should be left, from here to here, okay, if this I, if I mean this, which is It is big that if we have accounts greater than that, then I will set the leftmost influential to maximum. Reddy will return my answer. I am ok, so this is the default home. If you have any doubt, then comment section once. Ask me, that is, if anyone can put it in, then what will be its complete time complexity? Let's see, this is all the details. Okay, so if we are doing it this way, then look, we are doing a lot of things in it, meaning one thing happened in 1 second. If it is day then we are taking out the typing index, meaning we are taking out the starting index which is relative, my starting is one and the last index is taking that, so if I take out a service - I take out a service - Me off this isko come alu hoon aaj aa then me one se that off jo log a me and my one or in this I this 1 - me and my one or in this I this 1 - me and my one or in this I this 1 - done from the starting to the end in 1 - done from the starting to the end in 1 - done from the starting to the end in 1 - is put my ok means in the starting and the end Add in the middle, inside this also mine is appearing, so here my one - is appearing and appearing, so here my one - is appearing and appearing, so here my one - is appearing and for loop is appearing, okay this is following, so how much will this total be mine, my wife and mother and son will be there *n my wife and mother and son will be there *n my wife and mother and son will be there *n and * My call will be done as per login A, mine will be done here basically, that means yes, size jobs trick, so in this way, my time complexity will be removed, we are not taking space here, okay, so that would be mummy, that So here was the code, now you must have understood, if you have any doubt then ask and if you liked the video, please like and subscribe the channel. I have shared this video by
Kth Smallest Element in a Sorted Matrix
kth-smallest-element-in-a-sorted-matrix
Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_. Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element. You must find a solution with a memory complexity better than `O(n2)`. **Example 1:** **Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8 **Output:** 13 **Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13 **Example 2:** **Input:** matrix = \[\[-5\]\], k = 1 **Output:** -5 **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 300` * `-109 <= matrix[i][j] <= 109` * All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**. * `1 <= k <= n2` **Follow up:** * Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)? * Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun.
null
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
Medium
373,668,719,802
80
hello everyone let's welcome back let's solve today's problem today we'll solve the problem remove duplicates from sorted array 2. so here we are given our non-decreasing array in which we'll non-decreasing array in which we'll non-decreasing array in which we'll have to remove uh some duplicates in place such that at most Two element appears twice as okay the relative order of the image should be kept the same so here we have examples in this example you can see when this is the duplicates are removed the output should be 1 and this third one will be removed and two and three this could should be the answer let's go through using one example and let's keep this example only one two so let's have one more two and three okay so uh what we'll do we'll have two pointers left one left pointer and one right pointer forever what in one Loop what we'll do we'll keep on Counting the occurrences of the same element we're using a right pointer so right pointer will go from here to here now the now count becomes 3 that right pointer will stay here and then it will replace this right value with the left value so this will be this will come here and layer our left front will be increased by one left comes here again this will come here now left pointer will increase by one now let will come here now left and right both are here now right will again increase by one or I will come here again same element here and here now the right comes in this place because the count is three now the left value will press by the right value so 2 will get so this one will become 2. okay now right Ponder is here again this two will come here this two also become 2 and left one double increase by here then left hand will come here okay again we'll Advance the right pointer here right is here left is here so this there is no more elements so now three well this 2 will be replaced by three here and left will come here so now we have the arrays one two and B and we'll return this as so L is 0 1 2 3 4 5 million so let's code it out okay so in first Loop what we'll do let's lift and our 200 left hand right pointers Define them as zero okay zero now we'll Loop while this right pointer is in inbound of the array nouns okay what we'll do we'll have a variable counter initially we'll set it on because we are starting from one and if we check if this nums this the value is equal to Norms of next value are the same okay then what we'll do we'll increase the count by one it will keep making the value of iPhone here too because I this I doesn't go out of bound will fertile two will be 4 going forward we'll check if this I plus 1 is inbound okay now the right pointer become the right pointer is at the end of the current repeating value in that means now for in this example right pointer is pointing here now I want to point in here the third one and left one there is a zeroth one so what we'll do will now will increase the left pointer how we'll do so left wonder will be increased by the number of discount or maximum so it will do the maximum of this 2 or left Page left will be increased by equal to four i n range magnets okay so what we'll do we'll first we'll release the left that you with the right value okay in terms of right value it will increase the left value icon now this is now left has come here the probability left is here at here right is also going to be on the right by one okay divide by one again the frame under the loop will start from here now this once this Loop is completed value okay Okay so okay uh this R plus one awesome sorry this will be R not I sorry for that let's run it again 11 400 inch okay what did I miss here okay here this should be we'll have to keep on increasing right pointer now let's run it okay again sorry for this one while R plus 1 is less than equal to less than nums then we'll again it's keep on doing this okay here we'll have to take minimum of 2 and maximum not Max sorry guys for the mistakes after not done a lot of mistake so five is the output if you remove this two then we get the example from yeah four so here this was the four as the output here this is four okay to do three uh it is four so that's all guys this was the example for this one and again uh this takes only big of two and time complexity is 0 up to n uh that again converts to and only and space complexity is big of one okay thanks for watching if you found this helpful please like And subscribe see you soon
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. **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,1,2,2,3\] **Output:** 5, nums = \[1,1,2,2,3,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 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,1,2,3,3\] **Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\] **Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order.
null
Array,Two Pointers
Medium
26
969
That one shot of your pan was started, in this we will get one Hey, this ray will be found 3241 So we have to cost it, using pan cake clips of one of the tips is that like this, you can give a point here to your fans here. From here to here, you can just click on this, you can click on my from here to here, you can write from here to here and you can take any number of such clips. Okay, how many clips can you take, so you have to tell that when you If you soften it, then what size flip did you take and to return the tips of that size to you, like one way to soften it is not given here, it is 243, meaning I have clicked it from here till here and you can get it here. Click from to means from here you reverse this, from here you do this and so from here move 200 so first four size we have subscribed Suvvi will come here and will come here fully will come to will come here ok then what It says this, we have clicked to subscribe and you will see it yourself, click here, you slept, this is the meaning of youth or inside, this is the way I have understood, but let me clear you a little, I will click on your show of workers and Now if you do four cups then this will come for three here 214 then after that flip 1234 so you subscribe then and so this photo 3243 and subscribe and you can subscribe this is its possible hatred from here if you have 1 inch from here Here and anywhere else in the last post, you have not subscribed that let me tell you how Panic Shot actually works, how Prank Shot works, do not visualize the thing in the way they have done it. We should see our own way, no sorry, so how can we set this up from our stomach, we must not be doing it in this way, that is, before our own wish, that is, this is a way, okay, this is also a way, but look at this, Sir, Oye Prank. In short, our first task is that Ajay, one, two, three and see first before starting, this is the life in it that the length of ours is from one to hundred, then Malhari Dance Qawwali which is Alwar Dam, the expenditure on fans. Inspector will work great and whatever is the value, whatever is the viewers, all are unique and all are between the seven of the length, this means all are between their lineage, if there are four sizes, then what would be read inside one is 12345, that is different. -Stay what would be read inside one is 12345, that is different. -Stay what would be read inside one is 12345, that is different. -Stay in separate quarters and possibly in sweaters at any time. Increase their competition. Okay, so we have done this thing slowly. It is okay if we get permission. If they want, then maximize it so that their interest is in yours. Got two Abir welcome two so what is the first thing we have to do is the maximum line next9 and then we are clicking from zero till there so because ours is of floor length then we have to first find four and then from zero till send 4g. One big one has to be clicked there. Okay, listen again, we have to find the maximum because in this question, it is between the length of all the [ __ ] and submit one, so definitely the tomato will have the between the length of all the [ __ ] and submit one, so definitely the tomato will have the between the length of all the [ __ ] and submit one, so definitely the tomato will have the maximum, that will be so we for induction maximum welcome back. Will take two and will hit the pan cake flip from zero to that index which from zero to this index I hit the pan previous so my in Hey whatever is there it will look like this and from here to here you will hit the flip you started a work 200 here I If I keep making my body, then how many sizes will I have? Film Raj - 3 then how many sizes will I have? Film Raj - 3 then how many sizes will I have? Film Raj - 3 sizes, so three A's, now you guys, here the answer is four, Patti Gayi, this is also the correct answer, this is a reference, how is this, I will tell you, but you will see that it is like this in one. Someone who is in the business of doing this is definitely a professional, so all this work is done, what is this first second clip that you take it till the last, then in this second tip, you are gross, till where you are hitting so many feet. Yes, if you are hitting four sizes, then the face should go here, it should come here, now how is yours, something is like this, 200 power will not be asked, one hands free, two are fine, 0123 clip is killed, now we have reached here, what can I say? Be it that I was the last one or he reached the last place, then it means that so many hours have to be picked up, even from here to here it will be free, so if I am in touch with you then do this first, from here till this point. So here and the sum of subscribe nuvve a you from here till here so kill two clip art that 213 loot 0123 two now you will read till my place so like I have its this good now so many in so many who is where is here 000 So I have to click from here to here, so what is mine now, I have to move it here to here, I will click it so deep, let's show one after doing the flip. After clicking on 1234 0123, I have reached here, I can say that my so-and-so average has started, so when the so-and-so average has started, so when the so-and-so average has started, so when the elements on the table and minus one are the last get started, then the mind of the last is left, any first limit. If there is anything left then it already needs to be folded. No, you say 68, otherwise you have completed this and subscribe for this is the way to subscribe. Now let me tell you how they did this as per their wish. They find the maximum length and then they made it the maximum as per their wish, meaning if you understand then what was 3241, the police station was 3241, then they first made the original four sizes, you can make it one to two as per your wish, no problem, it became 1423. Now this one, now what we are doing in our first elements, we made it clear that maximize it, so this was our clipping, a slight reversal, this is the way that I did this a little bit, so I did it to you like this, so now inside this we are clicking. And subscribed and in this you are going everywhere and clicking on the element, you will get it and everywhere you will do it, its time complexity will become more and oven will be done, you can select this dress competition. Okay, so what is this path code? Tha Three 2100 Okay, so what is the use of this point, so see here till how far we will work, whatever is there, it does not happen at all, meaning from here it will go back to our Ghaghra, do it till here and like here, we have done So we are doing a little bit of work if there is any problem here, now we have to call this file question in this and end 113 So now first of all if this ribbon is its length which they want what to find first. In the first four, we have four where we have the indic tool, so this one is lying on the top, so we should get the mitthu, from this function, we are getting the tattoo, which our mouths are doing, hey, you saw while doing the mouths, hey you came. Look here, you dialed this phone, you see, you got index number two, which we hit return from here, index number two, now we hit return, we got interest here, so what work should we do to flip the first flip, from here till here, this should be And ours is 4231, but then the second clip will be written from here to end minus one, from here to here, so after clicking both, what do you have to store in the answer? Your index was indexed, you got its value. If it was lying on you, then it is free, you have to put it inside you, now this is the value of one, the devotee who started is of this size, you have to see the size, index plus one, as if it started from here and till here, if you click, then two index. Till you did it then what size is the real husband then as much as the index was one part of it ok after that first you play this that you will wipe the other one second after doing this you have taken 0123 from here till here last Indian Army and these were Whatever is nda, you will click till there and here, whatever is here, if you click till here, then take n Now if you do N Do please click on till inspector, you keep getting and from here to here, if you want to click from here and from here, then I will do both of these and then tell my start point and encounter and then I will search both of them, so this is just Their Yasmin, subscribe to both of them, there will be death. 1 free Indore, then make your tonic one smaller and one bigger, either this will go to the photo and this is that cosmetic, then do something like this, now we are clicking by doing the flip chut like this, let us choose three options. What is a lip, how do you set the point and this one is our mean flower, as soon as you have done all the rest, then you finally list it and you will get this pan cake, listen carefully, you will get what you need. Hai Tu So Ture Hey Using Pan Ke 108 Let's be so lucky in this video
Pancake Sorting
number-of-recent-calls
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**. In one pancake flip we do the following steps: * Choose an integer `k` where `1 <= k <= arr.length`. * Reverse the sub-array `arr[0...k-1]` (**0-indexed**). For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`. Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct. **Example 1:** **Input:** arr = \[3,2,4,1\] **Output:** \[4,2,4,3\] **Explanation:** We perform 4 pancake flips, with k values 4, 2, 4, and 3. Starting state: arr = \[3, 2, 4, 1\] After 1st flip (k = 4): arr = \[1, 4, 2, 3\] After 2nd flip (k = 2): arr = \[4, 1, 2, 3\] After 3rd flip (k = 4): arr = \[3, 2, 1, 4\] After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted. **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[\] **Explanation:** The input is already sorted, so there is no need to flip anything. Note that other answers, such as \[3, 3\], would also be accepted. **Constraints:** * `1 <= arr.length <= 100` * `1 <= arr[i] <= arr.length` * All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`).
null
Design,Queue,Data Stream
Easy
null
3
alright hey what's up guys they're quite here to tech encoding stuff on twitch and YouTube and yeah that's cool right yep very cool right this is the longest substring without repeating characters so this is given a string find the length of the longest substring meaning part of the string that doesn't have repeating characters so in this case you know this is a substring any this is a substring and as long as it doesn't have repeating characters we want the longest version that doesn't have repeating characters right so you know this doesn't have repeating characters in its length too but this does have repeating characters so that doesn't count you know anything with repeating characters you know doesn't count so right here this is the longest one in this case B is only one cuz it's just one character is the longest one because all of them are B's and then we have you know PW is the longest I'm seeing here and then we see ok wke right there so yeah pretty easy it's literally just a sliding window problem like we just did I just did want a couple minutes ago so it's very familiar to me um basically what you're gonna have is you're gonna have two pointers and you're going to set them both to the beginning and you're gonna have one pointer keep going one pointer is gonna stay at the beginning and one pointer is gonna move the wind you know expand the window and go and make sure that none of the characters are the same right so one of them's gonna be sitting that a and then one of them is gonna go okay a is new B is new C is new and we're gonna add these to a hash that's good for this cuz hash cuts keep track of unique things and then once we see another a we're gonna say up we already saw a and then you have that other pointer at the beginning and you're like okay get rid of that a and we'll just keep a maximum throughout the whole thing so whenever the window we're expanding the window with our two pointers and we're gonna keep a maximum to keep track of when the window is the biggest meaning the longest subs with unique characters okay that's it so pretty easy so you could call your pointers whatever you want we can do I and J we can do a point or B pointer I'm gonna do I and J just because I wrote it with a point or B point or a second ago I got a little bit messy so we have these are pointers this is gonna sit at the beginning this is going to go out and make sure that everything's distinct and then we're gonna have our max okay and then we need a hash set of characters this will only hold up to a certain number of characters I mean how many distinct characters are there if we're counting if it's alphanumeric that's a little bit more but if we're just counting letters of the alphabet in lowercase or uppercase it's really not that big 26 or you know that's or depending on what the character set is that we're using but um it's not gonna be scaling with the data you know it's unique characters so it's the biggest it's ever gonna get is whatever our restrictions are so it's not anything we have to worry about it so you can technically count in this constant it's not going to go up to a million or anything like that so then we're gonna be looping here we'll use a while loop so the J the second pointer that's going out and making sure that we're finding to have all distinct characters this is gonna get to the end the one that's expanding the window is gonna get to the end before the one that sits at the beginning so we're gonna do a check to say okay while J is less than s dot length okay so what we're gonna do is we're gonna say okay if the hash set if hash set dot contains STR at I to our beat I mean J because J is our second pointer that's going out and moving along here if the hash so I star J first is a right they're both at a I and J are pointers I think it's a little bit easier to do this actually now I'm thinking you know the were you gonna use pointers a pointer B pointer a pointer is gonna sit at the beginning B pointers gonna go out and expand the window so if our character at our B pointer that's going to expand the window there both of the first character right now if the character of the string if the first character of the string is not in the hash set okay well let's add it to the hash set we said we found a new character so we'll say okay hashset add and we'll add our new character here see the only point I didn't want to do it's because of all the parentheses okay there we go so we added to our character and then we increment it we only increment the second pointer to keep going out in it expanding the window and yeah that's it and then each time we see a new character and this is the case where we see a new character because the hash that doesn't contain it yet we're also gonna update the max so we're gonna say okay max is equal to math max of you know whatever the hash set sizes because this is how many unique characters we have against the current max so we update the maximum each iteration when we find a new unique character with the hash set size because that's the size of all the unique characters we have okay we're on a roll here now and the only other cases okay this character is already in the hash set so if the character is already in the hash set meaning we find a duplicate so B's already in the hash set and we find a new B we're gonna have to remove from the beginning we're gonna remove an old character and all you have to do that is you do hash set remove s touch are a pointer and that's because a pointer is the preview though you know the last character that we saw so and at that point we're just gonna increment a character the index of the first pointer so it's a sliding window you know they both start here B the B pointer goes out the second pointer goes out and expands the window and we see three and we're updating this max so it goes one two okay one two three we found three unique characters they're all in the hash set we keep we update the Mac two three because that's the hash set sighs then we see a oh it's already in the half set okay well we have that other pointer at the beginning we pop it out of the hash set so now it's BCA we keep checking against the max nothing's going on though you know because it's still three and then we see B up that's already in we pop it out you know and you just move along it's like a little sliding window that's the whole problem hopefully I made that clear let me know if you guys have any questions I'm trying to do these pretty well but you know obviously you know it's been a while since I did it all the weight codes so let me know if you guys have any advice for me to make this better I've been playing with the microphone levels non-stop and I'm having a levels non-stop and I'm having a levels non-stop and I'm having a difficult time so I'm sorry if you're unhappy with the microphone levels while Jay is less than at Wii Fit we remove Jay sorry for switching up on you guys in the middle of that as well s top length it's lowercase s sorry for the errors as well you know not the best oh my gosh guys I'm an idiot okay bear with me there we go success finally yeah you know I'm not that good I guess apparently but that's this is a good solution because the hash that is only gonna hold a certain amount of unique characters there's not we're not dealing with what are the restrictions every alphabet in the world including Chinese characters then it might scale up a little bit more but like it's pretty much constant we're not gonna get up to billions of you know different characters it's a hash sad so in this case it's pretty good and it's linear runtime and linear if it what worst case it would be like you know linear space 2 or not even it would be em you know oven runtime o of M 4 M will call the character set so if there's a million alphabets or whatever then you know that would be all right let me know you guys think comment blue check out the patreon and subscribe and like and all that stuff and see
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
1,861
hey everybody this is larry this is me going with q3 of the buy weekly contest 52 uh rotating the box so this one is also simulation it's just very tricky um there are probably a couple of ways to do it but the thing that i noticed is that n is 500 so as long as you do it reasonably it'll be okay and basically i just simulate gravity for what i did um first i rotate the box to be on its side and then i just have a two pointer algorithm of okay uh you know you're at the top and you have to i mean you kind of have to flip whatever but you have to top and you have a bottom of 2.0 and then you just keep on bottom of 2.0 and then you just keep on bottom of 2.0 and then you just keep on going up and uh and then you know keep on going up simulating pushing down um and then the only tricky thing is that when you see a stopper or whatever you want to call it um you kind of reset it so that the next one is the bottom um so that you keep going um that's basically the idea here uh it's kind of tricky to kind of get all the edge cases as well um so just really think about it deeply but it's two pointer for each one and as such um two point as you know is going to be linear uh for each row so and we do it once for each column so this is going to be linear um in total which is r times c which is row times column so it's linear in the size of the input and in terms of space because we have to flip it what is i did uh it's going to be r times c as well also linear and the size of the input so yeah so let's put it here just um but yeah uh that's all i have i think the only thing that's tricky is that you have to you know uh just be really careful about it so that you know it's just simulation and you just move it one by one and with the two pointers you get in linear time instead of if you do it naively of you know just keep for each box see where you get four because that's gonna be n squared and that's gonna be too slow uh well that's gonna be rho squared so it'll be r squared c which would for 500 would be too slow so that's why you need the two pointers um yeah uh that's all i have um yeah this looks this code looks really funky but basically you know for you it is just two pointers as well the bottom box uh you know you move the bottom up one at a time or yeah you move the bottom of one at a time the indexing is really weird because um yeah the bottom has the higher index so that's why it's a little bit awkward uh well but yeah um that's all i have you can watch me sub it live during the contest next i wish i remember really struggling with this one uh i know this isn't right yet i'm just looking to see if this is what makes sense this is hmm oops this is so hard to compare come on okay uh hey yeah uh thanks for watching hit the like button to subscribe and join me in discord let me know what you think about this contest um yeah i hope y'all just have a great week good contests and yeah stay good stay healthy to good mental health and i will see you later bye
Rotating the Box
building-boxes
You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: * A stone `'#'` * A stationary obstacle `'*'` * Empty `'.'` The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity **does not** affect the obstacles' positions, and the inertia from the box's rotation **does not** affect the stones' horizontal positions. It is **guaranteed** that each stone in `box` rests on an obstacle, another stone, or the bottom of the box. Return _an_ `n x m` _matrix representing the box after the rotation described above_. **Example 1:** **Input:** box = \[\[ "# ", ". ", "# "\]\] **Output:** \[\[ ". "\], \[ "# "\], \[ "# "\]\] **Example 2:** **Input:** box = \[\[ "# ", ". ", "\* ", ". "\], \[ "# ", "# ", "\* ", ". "\]\] **Output:** \[\[ "# ", ". "\], \[ "# ", "# "\], \[ "\* ", "\* "\], \[ ". ", ". "\]\] **Example 3:** **Input:** box = \[\[ "# ", "# ", "\* ", ". ", "\* ", ". "\], \[ "# ", "# ", "# ", "\* ", ". ", ". "\], \[ "# ", "# ", "# ", ". ", "# ", ". "\]\] **Output:** \[\[ ". ", "# ", "# "\], \[ ". ", "# ", "# "\], \[ "# ", "# ", "\* "\], \[ "# ", "\* ", ". "\], \[ "# ", ". ", "\* "\], \[ "# ", ". ", ". "\]\] **Constraints:** * `m == box.length` * `n == box[i].length` * `1 <= m, n <= 500` * `box[i][j]` is either `'#'`, `'*'`, or `'.'`.
Suppose We can put m boxes on the floor, within all the ways to put the boxes, what’s the maximum number of boxes we can put in? The first box should always start in the corner
Math,Binary Search,Greedy
Hard
null
63
Hello friends welcome to the new video question number 63 unique part 2 name is follow medium rice question is DP question you will find this question on the internet and this was asked on Facebook let's start give this gram and said The robot went to the top left corner, the finish line is the last one and if your robot can do 2 movies, then it can go up to the right, it can do it in two directions, which was the same in Part 1, now go to find out how many. How many unique paths will there be to reach the finish line? How many different ways can there be to reach the mark? Okay, but that was all in Part One. What's different about this minute? There are obstacles in between that haven't been there for a few years. The robot cannot travel where there is blockage so it cannot travel from there. Well then we have to tell how many unique paths are there so that the robot can reach the mark again then let's start what will be the approach what will we do in actual anything new the court has said Who will do anything new? We will edit our part one code. If you have not seen the video, read the gender description and you will not be able to catch up, then let's start a little. You revise twice daily that we have done part- I went to 1, I that we have done part- I went to 1, I that we have done part- I went to 1, I take bread worth 723 in one. Okay, so I told you that there is one thing to reach the first position, there is one part to reach here, this is how we create the table of our DP. As we have shared in Part-1 also, eat half, As we have shared in Part-1 also, eat half, As we have shared in Part-1 also, eat half, well, there is a part to reach here, why is it because if you come here then there is only one way, you can go to Syria and no one else can take your hand to reach here. There is only one way to come here, there is only one way to come down, there is only one way, this is the frill of sawn into three, in this we are finding out how many unique passes can be done, okay I told that at this point How many ways are there to reach here? You can go by taking the right from the top or if the robot can remove 2 directions then there is one way or from here first down then you guys there are two ways to reach here so we have What we did was that we used all these two problems and found out the answer to this problem. We added 141 and here we got the total of five. What we did in the same way was to find the answer to this position. We will not calculate, we will see that there is one part till the top, then there is 25 till here, so we will add it and this becomes our three, OnePlus 3, then it must have been revised, how did we make it dubitable to come here, it is done for coming here. Fiber is done, ok, if I tell you, now there is a blockage here a few weeks ago, what will you do now, we did not do this thing last time, so if I tell you, here we will put zero, there is no point in coming here, it is optional. And I should find out the sin next to this, okay, how close is it to coming here, till the last question, I should say that there was a character to come till the top, I saw that there is zero here because there was a block till here, so I should add zero plus to both of them. Well, this is a part of coming here, whereas if there was no option, then this question of song 65 becomes part of coming here, but due to obstacles, you can reach here only in one way. You just have to change this, first in the court where it is optional, you will put zero and after that you will calculate, once you select your code, copy it and change it, this is the code of part one, okay now crotch typing. You must have understood not to do much and one more thing and we will understand what to do in the village. If you did this frill in the beginning Vansh because you knew that for all these problems it was necessary for you to fill this default to find out the answer. But if in the beginning if you meet some people then you will put zero there and you will see that now you cannot go ahead if this path is closed then all these will be 0, so what we were failing in the beginning. There is also a little change, if zero comes anywhere in it, then we will not do it again, we will break it in the same way. If this zero comes, is there any way to put it below, then we will not do it here again, we will leave it as it is and break it. If we give, then these are the changes: are the changes: are the changes: I have copied and added the earlier chord and understand this code a little, this time we have been given into Ani, this time we have taken out the size, the obstacle has migrated to the side, so in the same evening, we will take out the side, so in the same I will take it to the side of M. I take out what will be its length and at the same time I take out the anchor side, I am just making changes in the same chord, we don't have to do much, it is okay that Saurav of one country, if you guys have thought about it then he would have told. If there is already a blockage in the path, then you cannot go anywhere from here. If you are not able to move in the beginning, then our entire matrix will be zero because actually you are already blocked from here. This is the first path box, so you You will not go anywhere, how will you travel in the entire matriculation, you will return zero here, so you should also check once that first of all, he is not there, then if I am chatting in such a way that etc., this is how the app does it. Let that etc., this is how the app does it. Let that etc., this is how the app does it. Let me see in this, which is the worst position, there we did not have block share, here it is in Giridih of Obstacle in the office collection yesterday, in it was said that wherever there will be a rise, they have put a forest, so Vansh, we have to read it. I lookup channel one is in the worst position, if you check then I will say no problem ca n't happen, I will return zero five, rest of ours we had spread in the beginning in the first column but I told you that if any Let's copy this and what you are doing is you are folding the first column. Okay, so we are folding the column. So what we are doing is we will check that wherever we feel. There are obstacles there, if what we have means there is no difficulty, then you keep adding forests and look below, then we were adding forests, if there is no worry, then put them here, put forests here too, put them here too, but if If this affair goes away, the path ahead will be black, then all these will remain heroes, that means if Hina is not updated then what to do now, I come again, I was feeling my jam, I have my own matrix, so how did we feel the details, if the option is ours, if Once forest arrives, what will we do there, we will basically blacken it, if we don't update further then we will have to do the same thing above here that this is ours, we are doing the first prevention bill, this will also be our zero so do this first look. So we will fold like this, first stop, this is basically one feel, wherever it comes, we will back it. You must have understood that in the beginning, we have made a change and here we have to make a small change. How were you calculating that? Let us understand below how this two back to back problem was solved, that the above one was attempted, the left one was attempted, we found the answer to this problem by using two sub problems, so it was easily calculated but If at any place you find that obstacle, if there was an option here, we would not have added it here, we would have put this zero, then we do not want to find the solution here, so you will have to do it one more time in the same way. You will have to write that if you ever get an obstacle, let's make it a little smaller. If ever we are getting an option, where are I and J positions, wherever we are two, there will be an option, wherever there is Africa, then this position will be We will reduce it to zero as we saw in the oil below. There is no time to do anything. Same to the same code will work for us. Before making some changes in the court and I think it should work, let's compile it once and see. Change it to Shimla and ours is Shimla, they complete it and check that it is accepted and submit, at that time also the code is happening, you will see it in a very easy way, now I have solved it, Gautam has not done anything new, we We made some changes in our old chord. This is the change we were feeling in the beginning and in the end we have made changes in the case of obstacles and we have created our DP table in a very easy way. Both the questions are 90% Shimla. If so, we will way. Both the questions are 90% Shimla. If so, we will way. Both the questions are 90% Shimla. If so, we will meet again in the next video. Thank you very much for watching this video.
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
1,660
okay so here's the code and solution let's run through it so as you can see we create a set which will keep track of the nodes that have already been visited and we start with our first Noe okay let's start at node one if root equals none that's not the case if root. WR exists and the root. right value is in the self. scene so the set we return none but it's not so set so far equals self. scene. add root value that's one next we recursively point the root to the right and then the left okay so we have two branches now so three is uh not none and there are no values to the right of it and uh it's not in the set anyway so we just add it to the set and on the left hand side similarly we have a root value and we point it then to the right and check if this right value is in the set it is so we return none two becomes none uh so root. left returns none and root. right equals three therefore we're left with 13 as our final uh new tree okay next example okay let's look at the first example so we start at root 8 if root is equal to none not the case if root. right and root. right value is in the set already return none no one is not in the set we then just add root. value which we just did eight okay so 8 root. right equals self. correct binary tree root. right okay root. right is then we're going to recursively do the same thing but for the right node and the left node so now we're at three here on the left and one on the right okay same thing is one equal to none it's not so is root. WR and root. WR value in the set already so four it's not okay then we just add one to the value or to the set one same thing for three we add it to the set meets the same conditions next we point one to the left and one to the right and then for three there is no right we just point it to a left and the same thing so is four uh equal to none no it's not is root. WR and root. WR value already in the set no it's not okay we just then add four same thing nine add it now this part is where it gets interesting seven has pointing to the right to four uh this value is already in the set so we cannot uh add it to the set already so we remove uh this seven value return none so this if root. right and root. right value in self. scene we return none okay so seven is not returned and added to the set it's just none now and this also applies for the children so two now that we've got that part over with uh the four continues on to the right and the left so these are just added then to the set as well notice that then we were just trying to figure out with the set which nodes would be poing it to again which would reveal to us the wrong ill placed incorrectly placed node so we're left with 81 34956 this is our answer for the set and then when we return root it will be all of these nodes besides 7 and two okay hope that makes sense let's look at the solution okay to start we first Define our Constructor this will keep track of the scene values so self. seen equals set so only those values that have already been visited will be added to the set and this will check then if we have our incorrect node pointing to the value that's in the set so then we do our base case so if root is equal To None return none okay next if root. WR exists and root. wr. Val is in self. scene so the set we return none this just means that we've ran into a node which has already been added to the set this indicates to us that the node that we're currently uh at is invalid because it points incorrectly so we return none and if these two conditions are not the case then we simply add the node since it's a good value so we do self. scene. add root. value okay and then we do the same thing recursively for the rightmost and left mode so now it's so root and then once we've uh recursively gone through every single node we can simply return root this will be our modified binary tree without the uh incorrect node pointers and node values okay let's see if this works it does work very nice so what is the time and space complexity for this solution well the time complexity is O of one sorry o of n where n is the number of noes in the binary tree this is because we are traversing each node once and the space complexity is of N and this is because we are using a set to keep track of the values we have seen and in the worst case all the values in the tree are unique and we need to store all of them in the set so that's o and space o and time complexity that's it for this problem thank you for watching
Correct a Binary Tree
thousand-separator
You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**. Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this invalid node **and every node underneath it** (minus the node it incorrectly points to)._ **Custom testing:** The test input is read as 3 lines: * `TreeNode root` * `int fromNode` (**not available to** `correctBinaryTree`) * `int toNode` (**not available to** `correctBinaryTree`) After the binary tree rooted at `root` is parsed, the `TreeNode` with value of `fromNode` will have its right child pointer pointing to the `TreeNode` with a value of `toNode`. Then, `root` is passed to `correctBinaryTree`. **Example 1:** **Input:** root = \[1,2,3\], fromNode = 2, toNode = 3 **Output:** \[1,null,3\] **Explanation:** The node with value 2 is invalid, so remove it. **Example 2:** **Input:** root = \[8,3,1,7,null,9,4,2,null,null,null,5,6\], fromNode = 7, toNode = 4 **Output:** \[8,3,1,null,null,9,4,null,null,5,6\] **Explanation:** The node with value 7 is invalid, so remove it and the node underneath it, node 2. **Constraints:** * The number of nodes in the tree is in the range `[3, 104]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `fromNode != toNode` * `fromNode` and `toNode` will exist in the tree and will be on the same depth. * `toNode` is to the **right** of `fromNode`. * `fromNode.right` is `null` in the initial tree from the test data.
Scan from the back of the integer and use dots to connect blocks with length 3 except the last block.
String
Easy
null
1,921
hey everyone welcome back and let's write some more neat code today so today let's solve the problem eliminate maximum number of monsters this is from today's elite code contest so we're given two arrays an array of distance an array of speed as well both of these are going to be the same size and each position of these two arrays represents a monster so where the distance array represents the initial distance that a monster is away from the city and the speed represents the speed that monster is traveling towards the city every monster will be at least a distance of greater than zero away from the city and we're starting at minute zero and at every minute including minute zero we can choose any monster from the array so let's take a look at this example so we have three monsters a monster that's one distance away three distance and four distance away and each of these monsters is traveling at a speed of one mile per minute or whatever or meters per minute and we at every minute including minute zero we can eliminate any of these monsters and we want to return the maximum number of monsters that we can eliminate before any of the monsters reaches the city and if it's possible we might be able to delete or we might be able to eliminate all of the monsters in which case we can return and the size of the array now the first solution that comes to my mind with this problem is a sorting approach so the overall time complexity can be n log n and i think since we can do a sorting approach we could probably also do a heap approach which i think worst case would also be n log n but in some cases in which case we don't eliminate every single monster would actually run a little bit better than n login but i'm just going to stick to the sorting approach because it's a little bit simpler and this solution does pass on leak code but there might be a linear time solution i'm not sure if there is feel free to suggest it in the comments but this is the first solution that i came up with so why not just run a simulation right we're starting at minute zero so let's start at minute zero and then go to minute one and then go to minute two and then go to minute three and at every single minute let's eliminate one of the monsters right which monster are we gonna eliminate first well are we gonna use it based on the distance that it's away or well we don't we can't do that because some of the monsters might be traveling faster than others so why don't we for every single monster actually calculate in a different array let's call it minute reached in this array for every single monster we're gonna calculate at what minute is this monster gonna reach the city so let's look at monster one it's one distance away and traveling at a speed of one so after one minute or in other words the distance divided by the speed after one minute that monster is going to reach the city next monster three divided by four that's that means in three minutes at minute three it's going to reach the city the last one four divided by one that means at minute four that monster is going to reach the city so let's run through every single position in this array and we'll be keeping track of what current minute we're at the first position we'll be at minute zero at the next position we'll be at minute one next at minute two etc right so it kind of matches up nicely the index is basically the minute that we're at notice how this array is already sorted but if it wasn't we would have to sort it which would take n log n why do we have to sort it because we want to eliminate the monster that's going to reach the city first right this is the first monster that's going to reach the city we want to eliminate it then go to the next monster that's going to reach the city eliminate it etc now what happens if we had two monsters that are both going to reach the city at minute one something like this right well at this point we'll be at minute zero so this monster is going to breach it the city at minute one so that's okay we can eliminate this but now in this position we are at minute one so if we're at minute one and this monster reaches the city at minute one does that mean the monster reaches the city before we can eliminate it well this is an edge case and they tell us yes if the monster reaches the city exactly at the start of the minute it counts as a loss that means the monster did reach the city so if we had a case like this where this monster reaches the city at the same time that we can eliminate it then we lose right so in a case like this what would we say well basically we would say okay we were only allowed to eliminate one monster we were able to eliminate this monster but we couldn't eliminate the second one so we return one in that case but in this example we're gonna see that we can actually eliminate all of them because at minute zero this minute is less than this uh the minute reach so we can eliminate it now we're at minute one is less than three that means we can eliminate this before it reaches the city now we're at minute two we can eliminate four before it reaches the city at minute two right so we were able to eliminate all of these in this case we can return three and this was a pretty simplified example but basically all the things i mentioned that one edge case we have to worry about incrementing the minute by one each time and of course sorting this minute reached input array well it's on an input array this is an array that we're actually building but sorting it this is going to be used for every single example and we'll be able to solve this in n log n time o of n extra space that being said we can now jump into the code now we can get into the code like i said the first thing we're going to do is convert the two input arrays to basically the minute that each monster is going to reach the uh city so let's iterate through both distance and speed at the same time in python you can do that pretty easily like this but we could do it with an index also if we wanted to so now let's compute the minute that this particular monster is going to reach the city so d divided by s now what if we had an example something like this a monster was three distance away but the speed it was traveling at was two in that case we get three divided by two which is going to be 1.5 so in this case we want to be 1.5 so in this case we want to be 1.5 so in this case we want to round this up to two because we're only allowed to eliminate each monster at an even an actual minute right zero one or two if it reached at minute one point five then we're gonna say at minute two we should be able to eliminate it before minute two so we're gonna convert this 1.5 to 2. so when we 1.5 to 2. so when we 1.5 to 2. so when we calculate the minute we're going to say math dot ceiling d divided by s and then for each one of these we're just going to append it to the minute reached array and so that's phase one building this array and the next part is going to be actually calculating the results so of course we want to sort this minute reached array and we're going to have our result initially at zero this is the number of monsters we can actually eliminate so now let's go through every single position in the minute reached array so for minute in range length of minute reached and the minute in this case the variable minute refers to the index that we're at in this but it also refers to the current minute we start at minute zero and keep iterating and so if this minute is less than the value in minute reached meaning that we can eliminate this minute before or actually let's do the opposite if this minute is greater than or equal to the minute that this monster is going to reach the city in that case we have to stop right that means this is a monster that we can't eliminate before it reaches the city in which case we're going to stop and immediately return our result variable if it's not the case meaning if this minute is actually less than the minute that this monster reaches the city then we can actually increment our result by one and then continue to the next position in the array at the end if we were able to eliminate every monster we can go ahead and return result which will basically be the entire length of the array and as usual i had a couple typos so let's update the name of this minute reached and update the name of this we defined this as min reach so we have to use it as min reach but other than that the code is correct and if i scroll down a little bit you can see that yes this does get accepted in this contest who knows maybe there's a linear time solution if there is please let me know in the comments but i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Eliminate Maximum Number of Monsters
eliminate-maximum-number-of-monsters
You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city. The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the `ith` monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon. Return _the **maximum** number of monsters that you can eliminate before you lose, or_ `n` _if you can eliminate all the monsters before they reach the city._ **Example 1:** **Input:** dist = \[1,3,4\], speed = \[1,1,1\] **Output:** 3 **Explanation:** In the beginning, the distances of the monsters are \[1,3,4\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,2,3\]. You eliminate the second monster. After a minute, the distances of the monsters are \[X,X,2\]. You eliminate the thrid monster. All 3 monsters can be eliminated. **Example 2:** **Input:** dist = \[1,1,2,3\], speed = \[1,1,1,1\] **Output:** 1 **Explanation:** In the beginning, the distances of the monsters are \[1,1,2,3\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,0,1,2\], so you lose. You can only eliminate 1 monster. **Example 3:** **Input:** dist = \[3,2,4\], speed = \[5,3,2\] **Output:** 1 **Explanation:** In the beginning, the distances of the monsters are \[3,2,4\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,0,2\], so you lose. You can only eliminate 1 monster. **Constraints:** * `n == dist.length == speed.length` * `1 <= n <= 105` * `1 <= dist[i], speed[i] <= 105`
null
null
Medium
null
1,663
Hello Everyone Welcome Back to My Channel Short Viewers Name Problems Molesting the Giver Numerical Value So Problems in the Married Life of Lower Case Character is Defined a Position in the Alphabet So Value of a Given May for Your Gift To and Leave a Reply On 16th's first citizen go be first a subjective of lower case characters defined s system witch tractors magic tricks program pimple or string tie given kuntu looted person visit that said person human only you teachers and that twitter which graphically swollen string with land And equal dad my value one to one that flexographic ali smallest bone graft chief selection smallest in ascending order basically a co select is luthra ficus molar din singh rai is x comes before violin dictionary water should fear in the string in hair oil no inquiry this Dainik Hukam Good Boy The Best Graphic Chances Are That So Let Us Take Care Over What Mean That You Were Given Any Security Three And Physical Different 7 To Like This Oye Give One To Three Will Take It D7000 Live Within Two Years They Yourself Chhath Festival Something Plus 2 And Pawan Singh Like This That And Want Good E Like This 200 BCE Evil Game Our Economy 07 Torch Off Change Neetu Yadav Liye Graphically Chamoli Distic On This Pig That This Biswal Egg By These Small Attend Spring And Distic Pimple Between 10 And Eggs Hey wow that even an internet is available virus ok go to sleep then hello how to this campaign has been taken in the state also in the state notes of stress test skin problem is the problem read how to take as much as possible to t&amp;c the past t&amp;c the past t&amp;c the past and here Par text molest main aapko graphically small essay tum bin will try The Amazing Latest by Subhash Ghai Drishti weak leg Graphic smallest this which is also in English for exam Bihar How to make them with letters to the times in the water remains basil leaves remove this Do hain to in this raw to speak for 10 class mein to have any record of a zhustzu five latest and lag sympathya solution b 70348 to airtel dhundhu 1 day ago ki i love you beta hai woh singh anil mishri all plasis and all plasis After we are done Rohit all places have s what is leftover Twitter my value from this is it will be one plus one which helps to medical value 153 live voting divide required in chhath the 68th me to back behavior 250 Le Deposit Ok So 189 What We Do I Will Start From Delhi And Will Start From This Position While Starting From Starting Because What Mid Day The Will Help Se Zinda Building In The Beginning And Whenever Possible Will Have Date Of Birth To Find The Smallest Singh Graphical Distinct Which Language OK Subject Urgently Co-Chair Will Place A Letter OK Subject Urgently Co-Chair Will Place A Letter OK Subject Urgently Co-Chair Will Place A Letter Minimum Of Twenty Match What Is Made On The Red It's Right Chilli Want But Invariably Six So He Is A What Means 2ND Year To Face With S Valid Qualities And Easy To Wear So What Is The American President 600 Apart Near About Video 1 - 125 And 600 Apart Near About Video 1 - 125 And 600 Apart Near About Video 1 - 125 And Dare I Love K 16th Voice Messages Minimum Temple Road Price The Meeting Will Be Adding This Affair S Plus One Act Is Chintu That Sushila Watching This Change In Two Ways and share it ok listen like this a me nine gilmoor point this a that and sons mihir who will platform 5 from key value of birthday content on that this spread the required person chat - 25th is will be I just will be bigger than and Four Polythene Ok Navya Coming Years And Will Take A Minimum Of Twenty Five Form Of A Great Being But Its 23-11-2012 Coming 23-11-2012 Coming 23-11-2012 Coming I Will Add Plus Twenty Five Years 220 21.15 2006 Software Testing 21.15 2006 Software Testing 21.15 2006 Software Testing Language Here Is Z2 Done And 68 - 9th Number Itni Abhinav's New Updates 53rd - 25th Of The Candidates From This Will Be 53rd - 25th Of The Candidates From This Will Be Torch Light And 118 Pocket 200 5V Aa English Playlist Suna Ki Nagaur And Will Come Here Point Welcome To Best Players Celebrate And Senior Lawyer And Will Again Check Minimum Of twenty five kill notice ke ATM tell mid 2018 will hide in this current airtel dish oneplus 80 district comes forward in this scholar form into this tomorrow morning egg this website that and only also less vote ke vs 98 - 98 - 98 - 1800 to ke Vikram Samvat 2070 quarter string of these interesting and the day the medical value system will be 73a that by its nature we agree that what he was doing mischief takes the strength which colleges have attracted from the value of these but they have Enough oil that last 100 every time after doing weeding in the string the current character minimum of water shift from hpbos coming days when you are living in the current index finger ring that and give positive singh by that much visible on weeding this quarter inch Waist K And Widows A Bigger Pointer To Move In Here Quantum Of Dividend Plan To-Do List Key Plan To-Do List Key Plan To-Do List Key Drive Once Upon A Time In Python Code And This Is Individual Leo Financial Year Ending This At All Positions Ok Others Like This Some Days And Subscribe King Diet Among and from agreeable favorite and face with f5 this improvement 1225 will be supplied from chemicals phase medical you will find one near 5 this is our full 1.00 today 1.00 today 1.00 today just middling this person that and according to divine shopping exactly the prevention research 200 grams Students Problem Hai Pee Latest The Police Also S Getting Sucked And Time Complexity Is One Side Of That And The Space With Output String Show The Dragon Account Is In Such Content Only Suitable Ok Song Ki Recipe Share Subscribe My Channel And Also In Active On
Smallest String With A Given Numeric Value
detect-cycles-in-2d-grid
The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on. The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string `"abe "` is equal to `1 + 2 + 5 = 8`. You are given two integers `n` and `k`. Return _the **lexicographically smallest string** with **length** equal to `n` and **numeric value** equal to `k`._ Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order. **Example 1:** **Input:** n = 3, k = 27 **Output:** "aay " **Explanation:** The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. **Example 2:** **Input:** n = 5, k = 73 **Output:** "aaszz " **Constraints:** * `1 <= n <= 105` * `n <= k <= 26 * n`
Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
965
cool 965 you know why you'd binary tree a binary trees you know valued if every node in the tree has the same right we turn true if and only if the given tree is unified all right seems straightforward ish okay unless we didn't time to do it this way what motive concrete is new but return true okay otherwise have no clothes otherwise return oops oh let's try the other one yeah they're just amid 1002 minutes emissions always good I'm practicing my speed a little bit on the easier ones yeah I mean this is a general equation thing I think recursion trees everything I recommend for an interview because that's the way they whoa but yeah I think the but yeah and I think the important thing for these kind of problems is try to figure out what do we invariant is for form and then and I make sure that holds true the entire case and in this case what you want to look for is that you know every value has the same value and then you know you could just pass that all around and as long as that or as soon as that in revenue is that true then you could be forced so yeah that's kind of this algorithm is gonna be O of n because well yeah and note and you look and you just know it once you can do faster than that because well yet look I didn't know that these ones in terms of space I don't use any extra space unless you count stuff on a stack in that case technically is linear because you're passing this value along but that's probably not something that thing but uh but yeah general generally pretty straightforward good practice and typing but yeah cool I mean that's why for this problem there's some of this question questions
Univalued Binary Tree
unique-email-addresses
A binary tree is **uni-valued** if every node in the tree has the same value. Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._ **Example 1:** **Input:** root = \[1,1,1,1,1,null,1\] **Output:** true **Example 2:** **Input:** root = \[2,2,2,5,2\] **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `0 <= Node.val < 100`
null
Array,Hash Table,String
Easy
null
1,029
hello everyone welcome to the channel today's question is to cities in Tivoli if you are new to the channel please consider subscribing we sold a lot of into a question on this channel and that can definitely help you with your interview the question says there are 2n people a company is planning to interview the cost of flying that I 8% interview the cost of flying that I 8% interview the cost of flying that I 8% to City a is coast I ate index 0 and the cost of flying the is person to city B is at index 1 written the minimum goes to fly every person to a city such that exactly and people arrive in each city that means we have total to n numbers of people and we have two cities that means we have to exactly send n number of people to city a and exactly n number of people to suitably and vacuum with example so let's move dependent people let's see how we can solve this question after that we will see the code question is simply saying we are to a number of people representing the length of the ring and we have two cities a and P Coast at index 0 is the code to fly to city a and course at index one is the course to fly to TP we need to send exactly n number of people to see the a and exactly n number of people to city B but we need to send the person in such a way that the coast is minimum so if I say but let's see what if I send everyone to city a and then let's see what if I send everyone to city B what is the difference so that we can know sending to with city save us more so let me make a partition and let me name them so let's name 0 1 2 3 and this is a cost of electricity a this is the city P so for person 0 if I fly to city it will going to cost me 10 bucks and if I am going to fly to city P it will cost me 20 that means if I'm flying to ctp so it will going to cost me 10 bucks more rather than flying to CTA so that means if I'm flying to City I'm saving n bucks so if we had only one person and if they're asks us that with city we should fly we would have clearly said we should fly to city because flying to city is saving us 10 bucks rather than flying to city B in the same way if I ask for person 1 to fly to City it will cause us 30 but if I'm asked the person to fly to city B it will cost us 200 so in this way if the person is flying to City it will going to save us 170 bucks but and if the person fly to city B rather than flying to city kosis 170 bucks MO and if I talk about person number 2 if the person's flight to City a it will going to cost 400 and to the person fly to ctp it will going to cost us 50 so with the person fly to City a that will go into course us 350 bucks more then flanked assertively and if the person flight to city B it will going to save us 3 350 bucks same with person 3 if we fly to city a it will going to cost us 30 is the person felicity P it will going to cost us 20 so flying to City a will cost 10 bucks mo and flank to city B will save us 10 bucks so now when we have the difference and if I sort them by the difference of a minus P which is minus 10 minus 170 plus 350 plus then what it is telling us that if I am taking minus 70 in the first position that we went to courses 32 flying to City a then I'm taking minus 10 which just coasting us 10 bucks to flank to CTA then I'm taking plus 10 which is just costing us 20 bucks to flank to CTP and if I talk about plus 350 it is just costing us 50 bucks to flank to say TP and if I add them this turn up to one month then and this is the minimum course so what I'm simply doing here is I'm it the difference of course to flight CTA to the course of length to city B that means course of flank to CTA - course of flank - Citigroup then I'm - course of flank - Citigroup then I'm - course of flank - Citigroup then I'm sorting them in descending order and as we know that we have to a number of people and we need to send and to city a and n to city B that means that we need to send exactly how person to city a how person to city B so now I can send this person to City a and this person to set it be in for that I can simply take a for loop until the time I is less than length of costs in the time I am going to ask the person to fly to city a and after that I am going to ask the person to fly to ctp in this way I can minimize my cost so this is the way we can solve this question if you are still confused here let's see the code I'm pretty sure after looking at the code you will be more clearly the question at line number three I made a salted Coast array in which I am sorting the cost on the basis of difference of course of flank to see da and the course of length to say tbh that I made a result variable which is initially zero then I'm taking the for loop in the length of the coast until the time my eye is less than half of the length of the course that means I am selecting the first half and I'm adding the ko so flank to city a to the result and for the second half I am adding the course of the flying to city B in this way I am sending exactly how people to city a and exactly how people to city B and my course remain minimum as I'm sorting it on the basis of difference of course of flying to City a to the course of flying to city B and at the end I am simply returning the result so this is the code let's see whether it works or not so here I submitted my code and it caught a septum so this was the solution for this problem you can find the code in the description below if this video was helpful to you please give it a thumbs up thank you so much guys for watching the video please don't forget to subscribe
Two City Scheduling
vertical-order-traversal-of-a-binary-tree
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city. **Example 1:** **Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\] **Output:** 110 **Explanation:** The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. **Example 2:** **Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\] **Output:** 1859 **Example 3:** **Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\] **Output:** 3086 **Constraints:** * `2 * n == costs.length` * `2 <= costs.length <= 100` * `costs.length` is even. * `1 <= aCosti, bCosti <= 1000`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Hard
null
67
this function takes the binary string representation of two integers and we have to add them up and return the answer as a binary string so what I'm doing here is grabbing both values A and B converting them to their integer equivalent in base 10 notice that I'm using here this second argument to say that the original value is in base 2 then once I get the integer base 10 equivalent I sum them up and then I use the bin function to get the binary string representation of my sum but there is one issue in Python you will get this prefix z b to your binary string so we need to remove the first two characters and grab the rest of the string this way if you get a and b as these strings when you add them up you get this and that's the correct solution in Python for the lead code add binary problem
Add Binary
add-binary
Given two binary strings `a` and `b`, return _their sum as a binary string_. **Example 1:** **Input:** a = "11", b = "1" **Output:** "100" **Example 2:** **Input:** a = "1010", b = "1011" **Output:** "10101" **Constraints:** * `1 <= a.length, b.length <= 104` * `a` and `b` consist only of `'0'` or `'1'` characters. * Each string does not contain leading zeros except for the zero itself.
null
Math,String,Bit Manipulation,Simulation
Easy
2,43,66,1031
1,547
Hello everyone welcome, we are going to do video number 36 of my channel and before starting I want you to repeat my playlist of DP concepts and questions. You can start that question has started coming in ok and there you can start DP from scratch. Can you understand ok so nowadays lead code number is 1547 is hard marked but it is a very basic recognition ok so it's going to be very easy once you understand the recognition question name is minimum cost tu cut stick and in this video recognition and Will make it through memorization and suggestions have come in my comments that it is okay to make a separate video for top and bottom, then it will come separately in another video, now this is the request, I am making a video through memorization, now bottom up I am using my DP concepts. All these questions are there in the playlist, look at the details, it is given in the question that there is a wood whose length is N, okay and if you take a stick and how have you numbered it, zero one, three four five six, you are looking at its length. Is it six? N = 6. looking at its length. Is it six? N = 6. looking at its length. Is it six? N = 6. Example: N = 6. Its Example: N = 6. Its Example: N = 6. Its numbering is zero, one, two, three, four, five, six. Its lens is now given to you separately. It tells you at which positions you can cut. Yes, this scale is called Cut, here what is the meaning of Cut Sai, at which position you can cut, it is ok, you should perform D cut in order, you can change the order of D cut further. Vishwa, you take anyone like a mother has said that you can cut it on one or but three or you or 5, it is your choice, you can cut the story also, but first you cut the above example. Okay, after that this child and this lesson child, then your mother, did you think of cutting on 3, then you cut on your three, okay then you cut on one and so on, so you can do any obvious thing, you can do it in any order. You can cut okay now see when now what is it not whenever you cut the stick okay Now the cut is of flower length, you have chosen that you will cut it on the third part, so what was its length before cutting, if it was 6 then it will cost you ₹ 6 to what was its length before cutting, if it was 6 then it will cost you ₹ 6 to what was its length before cutting, if it was 6 then it will cost you ₹ 6 to cut it, okay mother, let's take it has become a separate scale, it has become a separate stick. Both got fixed separately. Now now your mother told you that if you cut this part with five, then just before cutting, what is the length of this part? Three lengths. Okay, and your mother told you to cut this part with one. So just how much length is there before cutting? One two three rupees. OK, so the meaning of cost is D total cost D sum of D cost of which cut one you cut off D first explanation, let me explain to you with an example, minimum. You have to cut the scale and stick to the minimum, that is, you have to cut it for the minimum money. Whatever cut has been given by him, see, I repeat one thing again, do not get confused in the whole problem. It has given the cut as to where to cut, but if you look at the scale, it will look something like this. Do n't understand the scale. Don't tell me where to cut. It is okay for you, it is clear till now, just like mother. No, the problem is ok, now reduce it by one in this order, let's see how much my cost is, here I will keep calculating the cost, first I said, brother, look at one pay cat, if mother takes one pay, I gave one pay cat. So if you are looking at the scale, then one part will be cut in this part, zero one and one more part, what will be from one to 7, one, three, four, five, six and 7, okay, so just when it was cut, what was the length of 7, then the cost. What did you think of 7? Okay, now let's move ahead, what are you saying now brother? Let's cut on the third one. Okay, I will cut on the third one. If I cut on the third one, what will happen to my scale sticks? This is from zero to one, this is from one. You went back till three and what was the second part baby 3 4 5 6 7 Okay now look when you cut here on the third, what was its length, I am asking what was its length, one two, three, five, six, okay then? If there is a lens intake then what did I do, I am clear till now in cutting it, now what is he saying brother, cut at the fourth index, so let's see, not the fourth index, it means at the fourth position, so I cut at the fourth index. What will happen 01, this is 123, it will remain the same, do one, two, three, so I did it tightly and added it, now what are you saying last brother, if you show me the cat on the fifth one, what will I do, then what will become of four to five 67 more Rest, this is 3 to 4 and this is 1 2 3 and zero to one, okay sorry, here when cut, it is five, seven minus it will be three, one two three is its length, so I have added three here, we see. We have performed all the cuts. Now let's see how much the cost was. Cost A is coming together. Rs. 13 4 17 3 20 are going. Okay, now what did my mother do in cutting that I cut it in a different order? 3514 I said first ok now look at what he is saying first let's cut it on the third pay ok got cat on third cosme I am going to write here as of now there are cards, what is its length now its 7 so it will cost ₹7 now when it will be cat If given then it will cost ₹7 now when it will be cat If given then it will cost ₹7 now when it will be cat If given then it will sit in two parts, zero one, two on three and what is the second part on 3 4 5 6 7, what are you saying after that, five is correct, so if you cut it on 5, then how will it break into three, five. This will be 5 6 7 This was zero one you till three is ok so the one you have cut see its length how much is it plus I have made three ok so 7 plus 4 is gone Now it is saying cut at one ok then Let me cut on one, here it will be zero seven one you three four five 5 6 7 so cut this one then what is its length 3 - 0 i.e. three plus 3 now it is saying 3 - 0 i.e. three plus 3 now it is saying 3 - 0 i.e. three plus 3 now it is saying kar prakato ok kar but will cut If the tax is here then it is okay then these three commas will be cut into 4 and this 4 will be cut into 5 and the length and the rest will be the same okay what is the length brother 5 - 3 is 2 its length so here we have added two - 3 is 2 its length so here we have added two - 3 is 2 its length so here we have added two see how many rupees It took 7, 4, 11, 3, 14, 15, 16 and 20. How much did it cost last time? ₹ 20 means 16 and 20. How much did it cost last time? ₹ 20 means 16 and 20. How much did it cost last time? ₹ 20 means you cut it more cheaply, there are many possibilities like this, first you tried in your 1345, then you tried in 3514, it's ok to cut. If it requires less rupees, what does it mean that if you cut it in different fashion then it is possible that you will get a better answer. If you are okay then now what can you do in the root way that brother, find out all the permutation combinations of 3514. And try to cut the one which is minimum, that is the answer, but how many permutation combinations are done, the situation will get worse, the solution will be very slow, that is okay, so let's see what will be the butter approach of this, okay, then let's see a butter approach from this example. How will we proceed with this, how will we solve it, okay, how will we build the solution, so let's take our input 12345 N = 7, this had to be stuck and 12345 N = 7, this had to be stuck and 12345 N = 7, this had to be stuck and this cut has been given, where can we cut, okay and I have made a I reduce it, I also make a scale here, how is the scale looking in the beginning, okay, in the beginning, the scale must be looking like this, okay now let's move ahead, now it is up to you can cut on the story also, maybe not. Is it your mother? Can you do it on one also? Or if it is on you too, then you have the option of right. If you cut on the story also, then you reduce one, right? It is because of your mother that you decided to cut on three. If you try then you have utilized three then if you cut at three then let's see what happens if you cut at three, okay so now it is like two will share in the problem no two no yes means if you cut the stick at three So okay here, what cuts do you save, you have one cut and you cut it, okay and four five, you cut it at one cut, you either cut it at 4, 5, now 1 2, whatever is it, on what part of the scale will you cut it, right? If you have cut at 3, then your scale would have looked something like this: If you scale would have looked something like this: If you scale would have looked something like this: If you cut at three, then zero one is three, then what will happen here? Scale here, what will happen if you cut at three, then here 3 4 5 6 7 For that, it has been cut into two parts. Okay, it is clear till now and if you look at the two cuts that we have defined, you are seeing this one comma, you have divided it into two cuts because you have become three, now it is four commas. 5 is the cut, so what I am saying is that in this part of the game, one and two will be done and in 3456 of 3 scale, these four and five will not be seen separately, sometimes we will do four and also 5, we will try from both. Give minimum answer, ok but you are looking here, it is saying here, you can cut on one, yes, here one is present, here it is saying, you can reveal, yes or you are also present, meaning it is n valid all. Is this the problem? The two that we have divided are absolutely correct for the half of this scale. Here there is four five. Here also four comma five is visible. I am okay but if you take our example then it would be something like this. It is okay. If now your Mother Lia, if you automatically thought that now this time you cut on three, okay, then what will happen here the skill will look like this 0123 and here one child has happened, here what did you do, if 3 was utilized then 0 1 2 3 And what will be left of the second half of the scale 34 567 Okay, so for the first half you are saying this one cut and for the second half you are saying this one 452 4 5 2 But look at one thing, see the problem here, one is saying so. By doing it in this half, it is correct. Here, one present can also be cat. Look here, four is saying, you can try on four, yes, you can, here it is four, you can try on five, you can do five. Yes, but you are not present here, you are here, so the problem has arisen, this must be a big problem, how will you solve it, you are stuck here, what does it mean that brother, we have to sort it is fine if you sort it, then see. How will this problem be changed, here you have done it, now see, it will fit perfectly, we thought of revealing this method, then this part will be zero, one, three, what will be this part and the second part will be 34567, so here it will be four comma 5, now see exactly. The correct thing is here, if you try and hit one to cut, then there is also one, if you try and hit 2, then you are present here four is present, here five is present, date is the same, we will have to sort these many. It was important to understand why sorting is necessary. It is clear till now. Okay, this thing is clear to us. Now let's move ahead. Look, here our input is already sorted. You will have to do 12345 till now. It must be clear, so now look here, we thought that let's try it for free, maybe you have tried to cut it on 2, okay then here also we have two problems, if you try it on If we cut then what is our scale 012 and how many cuts do we have left? For the left side we play only one and for the right stick if we cut it then it was 34 and what did the scale look like here? How would the stick look like 234? 567 would have looked similar if you had made a cut on one or made a cut on your four or cut your fiber, then there are many possibilities, right, all of them are very difficult to draw, but this is not so, I just I am writing this in such a way that you have to try all the other things, but I heard one thing that you should cut on the story also. There are many possibilities, cut on three or two or four or five or one. Out of all of them the minimum will come. Now if you choose this, then it is obvious that when you cut for the first time, seven will be added to the cost because you have cut for the first time and look at the scale in the beginning. Well, there must have been 7 additions in the cost. Okay, now look here, now let's come down, mother, let me tighten my three, I am giving this race to all of them, but don't think that yes, there is nothing else, right? There are possibilities here, you have tightened it three times, there are more possibilities here, OK [ possibilities here, OK [ possibilities here, OK Now look here, let us understand further that here, at the first level, the tension will be 7 because in the beginning, the length of the scale is 7. Okay, now let's see here, now see here also you have a possible, either you will cut on one, okay, it is clear till here, then cut here, I will pick this one, then let's take that X, then here also four. And the minimum that will come from five, I will go here, it is A. Okay, so this is the minimum of the left half of the whole stick is Level Se S Plus Ha Here I Plus K N So On Okay, so we will add the minimum of all these here, then in the next level it can be minimum 7 were already there plus minimum of whatever came red plus is plus ks plus five whatever minimum we will add it is ok till now it must be clear everything is ok now understand what is the problem now which is the biggest challenge Isn't that what I am trying to tell you? Look, that is the most important question, so it is okay to pay attention carefully. Now pay attention to one thing. The scale that I have drawn here is in reality not a scale, you have it, you only have it cut. Hey, I have given N = 7, you have it, you only have it cut. Hey, I have given N = 7, you have it, you only have it cut. Hey, I have given N = 7, so I remove the scale from here. The game was visible only then, now I was trying to find out what is the length now and how much will be my score. Look here too, there is a scale, I have removed it. Now how will you find out what is the score? Okay, now how will you find out what is the score and what is the length of the game that I am currently cutting. Okay, you are not able to see it, so let's use your brain to look for it. What will you think about, I am racing on this, what was it here, these cuts were all mine, okay, I know what I will do, okay, let's accept that these are all my cuts, then look, this is a cut, this is also a cut This is also a cut, this is the cut, that is, this is the position of the cut, know where I am, I will excise two elements, tell me what will be my element, a little bit of starting off, in the beginning, the scale which I had drawn, started from 0. Was 1 2 3 4 5 6 7 So the starting scale is zero and what is the ending of scale? If it is 7 then with this we will be able to keep track for current affairs. What is the starting and ending of the scale that I am going to cut? Will you know the length from it? Right, so if I put it at two points, I put L here and R here, okay, then where does the cut start? It starts from L plus one, right, and till where, I am talking about the position of the cut. Cut off. Look, on the left, there is zero on the left and seven on the right. Is that the starting and ending position of the scale? It is inserted just because it will help me in finding the length. What will be the length now, which is 7 - 0 on the R side of the scale and Whatever is on L is now, which is 7 - 0 on the R side of the scale and Whatever is on L is now, which is 7 - 0 on the R side of the scale and Whatever is on L is fine, but where to cut, we will choose from here. From L + 1 we will choose from here. From L + 1 we will choose from here. From L + 1 to 1, it is ok, we will see, but who has to be chosen to cut, then time loop. We will bet from L + 1 to R - then time loop. We will bet from L + 1 to R - then time loop. We will bet from L + 1 to R - 1. If cat is cut on one then this possibility will come but then we will get the answer or if we cut above then we will solve it or if we cut on 3 then we will solve that also. This thing has become clear that now look, now I draw one branch, just one, I will raise the rest so that there is no confusion, I draw just one branch, let's take the decision to cut on three, okay cut on three. If you have decided to do this then see, my cut for the next half will be something like this, zero one, two three and for the second half, 3 4 5 7 is fine, that is, the decision to make my cut from L to G index. Take mother, she has come, either take the index mother, okay, so here the index has gone from L to index and what happened here from index to R. Next, right, this is the second half of this stick here. The cut for that is fine, but then the same mind will think that brother, the left part is the starting position of the scale and the right part is the ending position of the scale, it is okay and but the cuts are the cut positions, both of them are seminal. Like I told here, okay then look here, 3 which is the ending position of the scale, coin and seven which is the starting position of the stick, sorry, 7 is the ending position of the stick and these are 4 and 5, they are cut and that is correct too. Look, here one comma is 2, one comma is here, four five six, four comma 5, on the third, we had cut the third, I have put it here, okay, and put it here too. What will be the benefit of this, see, here also you will know its length, you can find its length easily, see what will be the length, its length is 3 - 0, can find its length easily, see what will be the length, its length is 3 - 0, can find its length easily, see what will be the length, its length is 3 - 0, its length is 3, what will be its length, 7 - 3 will be 4, its length is 3, what will be its length, 7 - 3 will be 4, its length is 3, what will be its length, 7 - 3 will be 4, now see try the liquid also. Let me give you, if you had cut the scale at three, then here it would be zero, here it would be one, here it would be three, look at its length, then how much is one, two, three, two, correct it, and look at its length, do one, two, three, that is, if the ending. This is the position and the extra value that I am putting in the starting position is giving me the benefit of taking out the length from it and why the length is being taken out after making it 3 - 0 length is being taken out after making it 3 - 0 length is being taken out after making it 3 - 0 because I said that I have cut it at third as per my scale. This is 7th starting from zero, I have cut it at 3rd, so that means I have inserted 3rd here and what brother, the ending position of the scale is 3rd, right and the starting position of the next half is 3rd and the ending position is 7th and the starting This position is zero, till now it is clear that brother, we will go like this to find out the length of our scale because that will be my score. Right, this is actually the most important part of this question that how will you store the thing, handle it, right. It is obvious that if I make the complete diagram, it will take a lot of time and it will also become very messy. Now you see how easy the story is, what did I actually say that I have given you all the cuts, it is obvious that you are the function. Will you do it tomorrow? First of all the cuts have been given to you, okay, what will you do in it, you will put a zero separately in the starting and in the last, what is the length of the stick you have given and have given Rakhi, so what have I done? I did add zero here, added more here, it is okay, the rest was given in the cut, what was already 12345, right in the set way, it is okay, this is clear, so what did I say to solve it, left. This will be right, this will be left and right, sent, okay, now I am solving the solution here. Okay, so when we say left and right, what is left, what is the starting index and what is right, what is my ending index, what is the new size of the cut. The last index that we take will be size cut dot size -1, we have to cut dot size -1, we have to cut dot size -1, we have to solve it and write it exactly like the story, it is ok, no, sorry, I will not help, remember, I will try it with plus one, ok, so this is what I am saying. From plus one to index, take it equal to R - 1, index plus is fine, I want to try by cutting at all the positions, if I cut at three, one, then the scale will break into two parts, I will expert it, if I cut, then I am trying to cut it into two parts. Right now, if I take the cut then see what will be my cost. Cost bill will be equal. First of all, what is the current length? Remember the cut of our stick which is on the right. Value - The value which is on the left side of the cut, Value - The value which is on the left side of the cut, Value - The value which is on the left side of the cut, from this I got the length and made the profit. Then what did I say, I cut it on the index, now it has been cut into two parts, okay, so let's solve both, we will have to do it, okay. Now the cost is set and what will we do in the end, we will do the return result, it became quite simple, so what was the most important thing actually, why did we have to sort yachting, I have shown it to you, okay from the above, what is the second important thing? Brother, sort of, we need length, neither is the length of strike on each position of the coin, nor is the length of tick on each position, so for that what I did was to add zero on the first index and on the last index and what I did on -1 was to add an extra value. what I did on -1 was to add an extra value. what I did on -1 was to add an extra value. Given here is the starting of D scale. Here is the last thing and the most important thing. What did I tell you that I want to try on every cut. If you have seen the minimum result then do this. Sorry point is the most important thing. Write in and if you pay attention to the sorry point. So if you write the code, you will be able to code it very easily, okay, so let's do this, let's write the code from the sorry point, let's see if usable, you solve it by seeing the test cases, science, okay, so what will we do, we will also do memos, this is No, we will also memorize it and to memorize it, you must have noticed that two variables are changing, left and right index is changing, so our 2d, our dynamic sorry DP arrangement will also be of three dimensions, okay. And science, what can be the maximum length? Our cuts can be Saregama, so here we will make N + 1 and N + 1 sizes, we will N + 1 and N + 1 sizes, we will N + 1 and N + 1 sizes, we will also do our 2D and see whether it is being submitted or not and a separate video will be made for bottom up. Because its analysis itself was very good. Okay, now look, before coding, let me tell you a very important thing. What happens in general, when you study in a tree course, they teach you in such a way that this is the template for cutting problems, on the return template. Other Cutting Problems Most of D Cutting is either called partitioning or this is actually a template but I don't want you to take the night you are looking at this template right now without rate we have written it if I want to tell you that this template Memorize this for every partition problem, apply this then it should be a good approach, is n't it logical? You have derived it, give this temple a butter, learn something, it is okay, you have to apply the logic yourself, it is a little okay, now the people with DP concept, who There is a playlist where I will teach all these topics, so there we will go into more detail about all these and now we will see the bottom, how to write bottom up, so let's solve all these through memorization, let 's do the same from the story point, it's 's do the same from the story point, it's 's do the same from the story point, it's okay to move ahead. First of all, before coding, let us understand one important thing, look, pay attention like a mother, in the beginning we had 1345, in the last we had put zero in the starting and in the ending we had put $7, which put zero in the starting and in the ending we had put $7, which put zero in the starting and in the ending we had put $7, which means whatever had to be stuck in the beginning, we had Will try many solutions and in the end let's take Maa, see how long will it take in recovery, look at that no means I am trying to find the base, what is the best way, what will happen brother, there will be something here, there will be zero, Maa take someone in between. There will be a cut and here the length of the one on the right side which will be the right hand of our stick, let's take three, okay, at least it will be on the left, it will be on the right, so you are seeing how R - L, if you do, then its seeing how R - L, if you do, then its seeing how R - L, if you do, then its length. At least how much mother do we take, it is zero, it is one, it is you, its index will be 2 - 0 2 A. you, its index will be 2 - 0 2 A. you, its index will be 2 - 0 2 A. Okay, so at least R-L will be Okay, so at least R-L will be Okay, so at least R-L will be less than what you should be, so it is obvious that we will find something. Can't, at least give greater, you should be equal. Okay, I am repeating again that here there was left side of our scale and here there was right side and there were cut positions in between, wherever you have to cut, you are right. So it is an obvious thing, at least you should either be bigger than him, okay if one is either younger than you, let's take Ma, if we take one, then it is an obvious thing, here there will be only two elements, one will be L and one. R will be okay if equal you become one four minus three one will become okay cut and appended zero in the bag at the very starting and cut dot push underscore back cut and in and what is zero run zero is my starting point of stick Here I have put more N = Here I have put more N = Here I have put more N = Ending point of stick and how will the length be calculated? How will the length be calculated? What will it do? It will try all the possibilities, it will try to cut at every position and will give our minimum answer. Okay, so You are sending cut, okay, if you send left and right, then left is my zero and what is my right? What is the new size of cut minus one, which is right most, which is the index. Okay, now we have to write our solve function, what are we sending vector of and Off Cut is sending Inter Left is sending Inter Right. Let's take L and R. Okay because we will need at least 3 elements right here which will be the left most and in the middle you are seeing the cut position, we will get three. Where is the position? Okay, and take this index, equal to R - 1. Remember the index, what was the starting value of the stick, what was the ending value of the length. Find out how much will come, where to cut, that is L + 1. From R to R-1, that is L + 1. From R to R-1, that is L + 1. From R to R-1, you must know that I had explained that now we are doing index plus, so what was the first thing we used to do to find out the cost, that now when you are cutting, then the same amount of money will be spent for the current length. I have to find out the length of tick. If the current is ok, then what will be the length of six? What will be the value in cut off right? Minus has been cut off. So much money will be required. Further, the two sticks that I have got by cutting are of two different sizes. Solve it. If we have to cut it on the left side then it will be on the left side and if we cut the science in the index then it will be the index and where will the one on the right side come from, instead of right it will be minimum of result comma, whatever cost came to me, then we will see by cutting all the indexes. We will go and will update the result on the best result that will come, we will return the result here, okay, let's color it and see if you are able to pass all date on late C, here we also had to send the cut, okay yes, it has been passed, now see. If we submit then we will give one seat even in the maximum time because we do not have a solution, we are trying all the possibilities. Okay, so the time limiting seat has been given. Now let us memorize it. So, we will memorize it. So see how many variables are changing in this. The index is changing, what was it, whose index is the cut and there is an index, okay, so let's see what is the maximum length of the cut, it can go to 100, it is given here, it can go to 100, but we have added two elements. If we are doing it right then what do we do, they take 103, okay and what will we do here, before doing everything, we will check here that if tee off is left waist, return it to the right, okay after that submit. Let's submit, then let's see the time. Did they solve this question? Now try to understand its time complexity. See what I am saying. You are choosing different left and different rights, just like you would a mother. This is yours. C1 c2 c3 c4c5 and so on ok you are choosing different na left comma r which you are choosing ok so there are different ways of chunni na l ko there are different ways of l there are n different ways of chunni and r There are n different ways of sardine. Okay, total is n length. So there it is O of n². If you choose different L's and different R's then total there are n different ways of sardine for both of them. So n² is done, here there are different methods of Chunni, after that what is that in each method of Chunni, you are putting a loop on it, whose length will be max, what is the length, let's take the size of the cut, isn't it? So there will be m², right here, now what are you doing every time, in every possibility, you are running a loop on another one, whose length is this much, that is for the size of the cut, I just how am I, okay, so extra m and c. It's ok so in m extra lagga see you gas video thank you
Minimum Cost to Cut a Stick
destination-city
Given a wooden stick of length `n` units. The stick is labelled from `0` to `n`. For example, a stick of length **6** is labelled as follows: Given an integer array `cuts` where `cuts[i]` denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you wish. The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation. Return _the minimum total cost_ of the cuts. **Example 1:** **Input:** n = 7, cuts = \[1,3,4,5\] **Output:** 16 **Explanation:** Using cuts order = \[1, 3, 4, 5\] as in the input leads to the following scenario: The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20. Rearranging the cuts to be \[3, 5, 1, 4\] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16). **Example 2:** **Input:** n = 9, cuts = \[5,6,1,4,2\] **Output:** 22 **Explanation:** If you try the given cuts ordering the cost will be 25. There are much ordering with total cost <= 25, for example, the order \[4, 6, 5, 2, 1\] has total cost = 22 which is the minimum possible. **Constraints:** * `2 <= n <= 106` * `1 <= cuts.length <= min(n - 1, 100)` * `1 <= cuts[i] <= n - 1` * All the integers in `cuts` array are **distinct**.
Start in any city and use the path to move to the next city. Eventually, you will reach a city with no path outgoing, this is the destination city.
Hash Table,String
Easy
null
69
hi my name is david today we're going to do number 69 on the code square root x we're giving a non-negative integer x we're giving a non-negative integer x we're giving a non-negative integer x compute and return the square root of x so in this example the input of x is 4 so the square root of 4 is 2. and there's another edge case here in that case that the square root is not an integer it has decimals to it for example we have an input of 8 the square root of 8 is 2.82 the square root of 8 is 2.82 the square root of 8 is 2.82 and so forth it only wants us to return the integer part of it which is 2. so assuming this problem we can't use the square root functionality or the button exponent function for it as well so it's going to be a pretty more math using math to solve this problem programmatically so how we're going to do this is that there's a couple of edge cases that will improve our code's efficiency where the square root of x will be itself so in this case our constraints starts from zero so zero and one the square root of zero and one is the same number so we can return x if it's 0 1 if x is 0 or 1 return x so this is the case where the square root of the number is itself and this is going to improve efficiency because we're going to have to do a further and we can skip these numbers so now we can loop through x starting at 2 from 2 to x since we know that it's happening with 0 1. and inside of this we can multiply that number by itself and if it's equal to x that means it's a squared number so we're looking if that number is the square root of it so if i times i so i is going to be the number we're currently doing the four loop in times i is equal to x that means it's the square root so return x and then we're going to keep doing that so in this example 2 times 2 is for it gets us automatically return x so now we have to look at and then if this was like nine it would be two times two is four that's not it so it doesn't do anything it keeps going into it and then it goes through the loop again for three times three is nine so that'll give us a square root so now we have to take account this part so we do this one so we start at 2 times 2 is 4 so that's not it and then we go to 3 times 3 is 9. so as soon as it gets to one that's above x as soon as this product multiplying the i by itself gets above it the first time we return the previous i so we turn i minus one so if i times i is greater than x return i minus 1. so that will give us the number before it that we need so that should do it so first we do our edge cases if making us do x is less than or equal to one return x so now we loop it so for let i equals two i is less than or equal to x i plus and now we're gonna check if it's a square root so if n square root is when it times it by the same number i times i is u sorry not x i times i that means we hit the square root so we turn i now we do the case where is a decimal so if i times i is greater than x return i minus one great we got it so now the time and space complexity so although we're looping through all of x well we'll see what case of n the highest it will ever go it'll be the square root of it so but we couldn't really use the square root um functionality the method in it so it's going to be o of log n because as it great gets exponentially bigger the square root doesn't get it goes like that because once i gets bigger it doesn't proportionally get bigger it gets narrowly bigger because it's only go up to the square root of it which is log of n but we can't use it won't go as far as this and then the space complexity is going to be o of 1 because we're using constant variables here um constant space and that's how you solve this problem is a pretty math problem but it's a good one thank you so much
Sqrt(x)
sqrtx
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well. You **must not use** any built-in exponent function or operator. * For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python. **Example 1:** **Input:** x = 4 **Output:** 2 **Explanation:** The square root of 4 is 2, so we return 2. **Example 2:** **Input:** x = 8 **Output:** 2 **Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned. **Constraints:** * `0 <= x <= 231 - 1`
Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)
Math,Binary Search
Easy
50,367
645
hello guys welcome to algorithms made easy today we will be discussing the question set mismatch in this question we are given a set of integer s which originally contains all the number from 1 to n unfortunately due to some error one of the numbers in as got duplicated to another number in the set which results in repetition of one number and loss of another number you are given an integer array numbers representing the data status of this set after the error and we need to find the number that occurred twice in the number that is missing and return them in the form of an array so in the first example we can see that there are total of four numbers and two is being repeated and three is the missing number so we return the output as two comma three and similarly in the example 2 so it's an easy question and we just need to find which number is the missing one and which numbers has occurred twice we'll count the occurrence of each number and then we can just return the two numbers one whose count is zero and one whose count is two so let's see how we'll code that so we'll have an array which will be of the size nums dot length as it is given to us that there will be one to n numbers now here we are taking nums.length so we now here we are taking nums.length so we now here we are taking nums.length so we need to take care that the value starting from the array should be from 0 to n minus 1 so we will take care of that while we are iterating over the r in nums now we will have a result array which we need to return and this will be of the size 2. at the end we just need to return this result array first we'll iterate over the array nums and for each of the value we need to increment the count of it we are doing i minus 1 because the array is starting from 0th index and now we will just simply loop from i till the array.length finding if the till the array.length finding if the till the array.length finding if the value at this position i is equals to 2 means the number has occurred twice so we will put the index plus 1 at 0th index of resultary we are doing plus 1 because the number ranges from 1 to n and now the second condition for the missing number if the value at ith index is 0 that means it is the missing number and we'll just put this value at the first index of result i plus 1 so this completes the coding part let's run this code so it runs successfully let's submit this so it got submitted successfully the time and space complexity of this approach is often now we'll see how we can solve this problem without using any additional space so as the quotient states that the number will be between 1 to n so all the numbers will be at least positive we will see how we can solve this so let's see that with the help of an example suppose this is the example given to us and we need to find the missing number and the repetitive number so first we need to see that these values are in the array so they will have any index assigned to them now we will be using the index heavily in this approach so let's see how we can do that we'll start off with iterating from the 0th index all the way to the end of the error and at each index there will be a value present what we need to do is we need to take that value and find the index from that value so the index of 1 will become 0 and so we will convert the number at 0th index into -1 in this case it is the same into -1 in this case it is the same into -1 in this case it is the same number but since the array can be unsorted the number and the index can be different then we move the pointer to the next index and now we come across index 1 whose value is 2 so we convert the value to minus 2 in this case also what we are effectively doing is we are turning the value at nums of nums pointer minus 1 to negative so we are finding the value at this pointer which is our current index taking that value doing a minus 1 as an array zero index based data structure and then negating the value present at this new index that we got so this nums of pointer in this case was 2 so what we did is we change the value at nums of 2 minus 1 that is numbers of 1 to negative which in this case becomes -2 -2 -2 now we move again the pointer to the next index and in this case the index whose values is to be negated is index 1 as we have nums of 2 minus 1 again so in this case we see that we have already turned the value present at this index 1 into negative which implies that we have already seen this value so this value is nothing but the repetitive value that we need to find so we'll store that into a variable we'll continue turning all the values to the negative values by moving our index till the end of the array and at the end we will get this array now how do we find the value which was missing now when we again go through the array from 0 to the end of the array we'll find one index whose value will not be turned into negative value that index plus 1 is the number which was missing from the array so now let's see how we can code this and it will be more clear then so let's remove this for loop and this array and we'll still need this result we need to first iterate over all the values of this nums so if the value present at this position is already negative that means we have already seen this value and this value is now become the repetitive value so we'll store that into the result array at zeroth index so store the absolute value at i else we haven't seen this value before so we'll convert this value into negative so we have found the repetitive number with this first for loop and now we need to find the missing number you know to find the missing number will iterate the loop from i to nums.length and if i to nums.length and if i to nums.length and if any of the value is greater than 0 then this index plus 1 is the answer so we'll put that at index 1 let's 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 are many other ways to solve this problem one using bit manipulation also we'll discuss that approach in further videos thanks for watching the video see you in the next one you
Set Mismatch
set-mismatch
You have a set of integers `s`, which originally contains all the numbers from `1` to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number. You are given an integer array `nums` representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return _them in the form of an array_. **Example 1:** **Input:** nums = \[1,2,2,4\] **Output:** \[2,3\] **Example 2:** **Input:** nums = \[1,1\] **Output:** \[1,2\] **Constraints:** * `2 <= nums.length <= 104` * `1 <= nums[i] <= 104`
null
Array,Hash Table,Bit Manipulation,Sorting
Easy
287
1,463
hey everyone welcome back and let's write some more neat code today so today let's solve the problem Cherry pickup 2 this is definitely a hard one but it's not crazy hard at least in my opinion it's not as hard as the first one which is why I'm not going to recommend that you solve the first one before this one in my opinion is easier so we're given a matrix let's just focus on the visuals here and we have two robots they start at the top left and the top right of the grid and for each robot we have three choices on every move we can either go down left down or down right and the other robot makes the same or not the same choice but it has the same set of choices to make so it can go here it can go there or it can go there so maybe this one goes down this one goes over here and they both make choices at the same time so they're always going to be in the same column now given this each robot picks up all the cherries or whatever thing you want to consider it takes the value in the position of the grid that it lands on and we want to determine the paths of both of these such that we maximize the points or the cherries that we collect and that's what we want to return so in this case you can see the paths are going to be like this and here like that so the total for this is going to be 24 now they also tell us that if both of the robots land on the same position then both of them can't pick up the value only one of them can pick up the value so you might think we need some additional logic to handle that but my claim to you is that we are guaranteed every value in this grid is going to be greater than or equal to zero why would we ever want both of them to land on the same position that would never lead to the maximum result because we are guaranteed the grid is always going to have at least two columns why would I ever want this value to be in the same position even if there's a big value there cuz they both can't collect it so I'd at least want this guy to collect something over here it'll get something that's greater than or equal to zero and if both of them were to land in the middle our set of next choices would be limited to only three but if I have one over here and one over here now my set of choices is going to be at least four so again why would we ever want them to land on the same position next we kind of think about this in terms of choices it's not hard to kind of visualize this as a decision tree because that's kind of what we're doing you might think before going down the brute force method the backtracking solution you might think is there a greedy way don't we just want the robot to pick the maximal of its choices not necessarily because what if this guy says Okay I want to take the five because there's a one here and there's a one here but what if there's 100 over here we can't be greedy and take the five we have to take the one in this particular case so we can then get the 100 no point in trying to be greedy we do have to consider all possibilities we don't know what lies ahead now when you think about the Brute Force you think what are the parameters of the Brute Force going to be the base case is kind of obvious once we reach the last column we can't really go any further and we do have to do this simultaneously because we do have to make sure that both of them don't land on the same position cuz we definitely don't want to overcount the solution we don't want to collect the same value twice so we do have to maintain what is the column of the first robot I call that column one column of the second robot I call it column two now you might start to be naive you might start to think we need another parameter Row one for the row of this robot and another parameter Row Two for the row of this robot but remember it's easy to miss this they are always in the same row so we only need a single parameter for the row this is actually enough when we take this Brute Force solution and optimize it with caching which I'll show you how to do in the code we can actually pass this problem that's why it's not like a crazy problem in my opinion now what does the decision tree look like for a single robot we have three choices but we have to make a choice with two robots so it's not that we have six choices let me make this very clear we don't have six choices we have nine choices three times three because we consider the case where this robot goes here and this robot goes there or the robot goes here or the robot goes there that's three choices the next three would be this go down this one goes here or here that's another three choices and I could continue with the rest of them but you get the point that's what we will consider as well and then let's consider one possibility where let's say we go here and then this one goes here next we will recursively make the same nine choices in terms of time comp complexity this looks like 9 to the power of how many columns we have or the number of rows sorry about that I always get those confused so it's going to be something like this 9 to the power of R of course we want to optimize this we know the parameters are going to be row column 1 and column 2 what are the possibilities for this well R could be the number of rows I'm just going to use capital r for that for each of these it's going to be C so time c^ 2 that's the time C so time c^ 2 that's the time C so time c^ 2 that's the time complexity that's also the number of sub problems so this is the size of our cache when we apply caching when we get to a sub problem we don't always want to recompute the result so we store the result of it in the cache okay let's code this one up let's start with the DFS it's the recursive Brute Force solution and I'll add caching to it at the end so we have the row column one and column two the base case is well the main base case is going to be when we reach the last row so if R is equal to number of rows minus one I should probably compute that so we have number of rows and number of columns I like to do this just because it makes things more readable that's also why a lot of people you'll see will use I and J for rows and columns but I think that's less readable it's very clear what we're talking about when we have R and C so I prefer this base case is when we reach the last row in that case we are just going to Simply return the sum of the values in the positions we know they're both in the same row so we can do it like this the value at column 1 and the value at column two from the grid but what if they were the same what if column one and column two is the same we probably need another base case to check that we don't want to overcount the solution like I said so let's check if column 1 is equal to column 2 let's return zero let's just not consider that it'll make our life a little bit easier but there are other cases where we might want to return zero I didn't talk about it in the drawing explanation but what if we go out of bounds well the row is never going to go out of bounds we keep moving down until we reach the last row but the column could go out of bounds it could be that the column one or column 2 is less than zero and the easiest way to check that is take the minimum of both of these this is kind of a shortcut take the minimum and check is the minimum less than zero or opposite take the maximum of both of them and check has that gone out of bounds is the maximum equal to the number of columns that's the only way it would go out of bounds if that's not the case let's go ahead and compute the result so I'm going to compute the result initialize it to zero actually and then out here we're going to return it but now's the fun part how do we enumerate all of those nine decisions I don't want to write nine recursive calls so the easiest way to do this is two Loops I'm going to call this c1d the delta or the difference in C1 we know we can either move the column to the left I'm going to call that negative 1 we can either keep the column the same I'm going to call that zero or we can move to the right I'm going to call that one and we can do the exact same thing with column 2 so just have this hardcoded array I probably could have saved a little bit of space I guess if I put this in a variable but it really doesn't matter now is the recursive call when we call DFS what are we supplying here well the row always increases by one that's the easy part row plus one what about column 1 and column 2 well that's why we have this Delta column 1 is now going to be C1 Plus the Delta and C2 is going to be the same C2 plus the Delta and we're trying to maximize the result so let's just set result equal to the maximum of the result and the maximum of the recursive call there's one thing I missed here as we are traversing the grid shouldn't we pick up the cherries at this position so far we only pick it up in the base case I should here be adding to the recursive call this value right here but that's going to make this line really long so I'm just going to choose to do that here before we return the result let's just go ahead and add this to the result because we know this is a constant and it's going to be added to every single call here so instead of doing that here I'm just going to do that out here so result plus equal to this and then return it this will pass um let's just finish it up so when we call DFS the row starts at zero column one starts at zero and the second column starts at the number of columns minus one all the way top right so this does not pass but we can just add a little bit of caching and then make it pass so I'm going to declare a hashmap for that and here I'm going to add the if statement is this key all ready in our hashmap if it is go ahead and return it if it's not go ahead and compute it and then return it so when I compute it I'm actually going to store it right in the cache so I'm going to do this now result plus that and then I'm going to return that just like this and it looks like I have a little typo here don't know why I put R1 here and now we also have R1 up here sorry about that we also have a little typo here I forgot to take the maximum of these we don't want to assign the result to a tupal and another R1 here but other than that let's run the code and you can see it works and it actually is pretty time efficient this is about as time efficient as you can get it but we can improve the memory so right now the memory is three-dimensional it is going to be the three-dimensional it is going to be the three-dimensional it is going to be the number of rows times the number of columns squared we can actually improve that because you notice if we're Computing this problem we only need the result of the sub problem from the next row this row depends on the next row we don't need every single Row in memory at any point in time so when we implement the tabulation method we can improve the space complexity to actually be c^ S the space complexity to actually be c^ S the space complexity to actually be c^ S the number of columns squared let me show you how I'm going to do that so I mentioned that we don't need the memory for every row to be in memory at the same time instead of like going recursively we compute the solution top down we can work our way up we can compute this bottom row what is the sub problem of the bottom row it's basically if robot one and robot 2 were to be in any combination of those positions what is the maximum result we could get for example consider like if robot one is here robot 2 is here to compute the value that goes here we would recursively well not recursively but in our solution we would try all those nine possibilities I talked about but we'd kind of go out of bounds wouldn't we so let's just implicitly put a bunch of zeros here so we don't have to consider the case where we go out of bounds this way of visualizing it is not entirely enough actually because what we found is our space was three-dimensional and we our space was three-dimensional and we our space was three-dimensional and we reduced it to two dimensionals at least Le that's what we're trying to do and that 2D grid is going to look like column squared it's going to be the number of columns which in this case is three and we're going to square that so 3x 3 now what does this represent let's say this is column 1 this is column 2 we're basically saying if robot one is at column 0 and robot 2 is at column 0 what is the result going to be well we skipped that because we don't consider the cases where they are equal remember so that's easy enough what about when column 1 is at zero and column 2 is at column 1 that's going to be over here that case it looks like we'd get a 2 + 1 that case it looks like we'd get a 2 + 1 that case it looks like we'd get a 2 + 1 and then we'd put a three over here and we can do the same thing here in column one we have a two and in column two we have a one this is column zero sorry about that so here we'd also put a three and you'd kind of just go through all of them and do all of that fill those values in even though it's really hard to visualize this cuz this is three-dimensional we're going to have three-dimensional we're going to have three-dimensional we're going to have these stacked on each other and we're trying to reduce that now to two Dimensions so what I'm saying is okay we compute this first one I'll just kind of fill these values in 1 and Z is going to be the same as 0 1 so we'll put a three here 2 0 is going to be the same as Zer of two it doesn't really matter which robot is in which position so we'll have a three here 2 1 two are going to be the same which is going to be 1 + 1 and the same which is going to be 1 + 1 and the same which is going to be 1 + 1 and that's going to be a two here and a two there so at least in the last row if we were trying to maximize the result the most we can get is a three that's what we've discovered so far now one more optimization I'm going to make if we were trying to fill in this grid we'd need two nested for Loops iterating over the number of columns right but we actually don't need that I'm hypothesizing we can actually only fill in this part of the grid and skip that part it doesn't really improve the time complexity this is still proportionate to c^ S but it's just an easier way to c^ S but it's just an easier way to c^ S but it's just an easier way to code it up and you'll see that when I code it up basically what I'm going to say is for C in range from zero all the way up until the number of columns minus 2 and actually I think even this is more than we would need because when you look at the picture over here would we ever want the two robots to cross each other would I ever want this robot to end up on the other side of this robot probably not because it doesn't matter which robot picks up what we care about the total that we pick up so if we were ever able to create a path like this we could have done the opposite and created a path like this so why would we ever want the robots to cross this is something that's not super important but knowing this can actually make the code a little bit easier to write so that's what I'm going to be doing so this is what we computed for the last row now let's compute the next thing for the next row and I'm not really going to do a lot of it let's just consider this one cuz we know this is what ends up maximizing the result so where robot one is at column one and robot 2 is at column two so we're looking at this and this so how do we get the value that goes here well we of course take the values existing in the current position so we'd find a five here and a five here we are keeping track of another variable remember the current row that we're in we're working our way up as we do this and remember to compute this row we only need this Row in memory and the word row is misleading because the values for this row actually are represented in a two-dimensional are represented in a two-dimensional are represented in a two-dimensional grid so what I'm saying is let's say this is our DP grid our previous DP grid and I'm right now Computing the current DP grid of our current row also I think I was wrong when I said we're at this column I'm sorry I don't know what I was thinking robot 2 is here of course it's at column 2 so we actually want the value that goes here but yeah the first thing we do is take the values of this that's 10 and now we want which one of the sub problems was maximal again that's nine different possibilities so basically we look at the grid and just so you know coincidentally the size of this grid is nine and that's because the number of columns is 3 * 3 that's not number of columns is 3 * 3 that's not number of columns is 3 * 3 that's not always going to be true it could have been possible that this grid was 5x5 even if the grid was 5x5 we still only have nine other choices that we would be looking at I want to make that very clear this is simple for us we have up to nine choices to look at and those nine choices would be basically this or this we really don't have many choices there's really actually only two valid choices either robot one goes down and robot two goes here or robot one goes here and robot 2 goes over there all other choices are invalid because we don't consider when they're on the same we don't consider when one goes out of bounds so there's two choices and it looks like this one is maximal where is this stored by the way in 0 1 the value is three so we take what we computed which was 10 + 3 and store that computed which was 10 + 3 and store that computed which was 10 + 3 and store that in this position which is 13 so that's what you would pretty much do filling in this entire grid pretty much now since we only want two of these in memory at a time we would take all these values move them up here this is our previous DP and now we'd compute the next one our current DP as we work our way up as we get to this row and then eventually this row when we're finally done what value are we going to return well we know we started here and here so whatever our DP array ends up being we will return the value that is right here column 1 is zero column 2 is the last column so this is all the memory optimization and the tabulation solution basically the space is going to be number of columns squared let's code it up so I'll leave this code here but we aren't going to be reusing any of it but sometimes when you're writing the bottomup solution referencing the recursive solution can be helpful first thing I'm going to do is just declare our previous DP grid and like I said I'm going to default assume that they're all zero so we're implicitly saying every value below the last row is implicitly zero so just like that and I want to work my way bottom up some people don't like that because you have to go in reverse order so this is what I do you don't have to write it that way but then if you write it the other way you end up changing the logic of the problem kind of a lot and that makes it very different from the recursive Solution that's why I prefer doing it this way but again you don't have to now for this row we're trying to compute the current DP so all I need to do is just copy that and assign it here okay so next we want to enumerate all of the columns so column one could be in any of these valid columns column two could also be any of these valid columns but like I said I want to take a bit of a shortcut I know column one is never going to cross column two so why don't I just put columns minus one over here for column two I'll put column 1+ one column two I'll put column 1+ one column two I'll put column 1+ one because I don't want this to start at column 1 that would mean they're at the same position then I go up until tell the number of columns this way not only do we not consider the case where they've crossed each other which would be redundant but we also don't consider the case where they overlap we don't need an if statement now to check if they overlap that's pretty convenient I even would consider that pretty Neato so now for this sub problem we want to compute the number of Max cherries and for us to do that I'm going to assign this to zero and after we have computed the number of Max cherries we want to store it in the current DP grid and what is the sub problem that defines the current DP grid is C1 C2 I don't need to put the row here because we automatically know current DP corresponds to the current Row the previous DP corresponds to the previous row AKA row minus1 but how do we enumerate those nine decisions well how did we do it recursively it looks like I just had a couple nested for Loops I can just copy and paste that it's just that easy now we're getting five layers of nesting deep so I might as well show you a bit of a shortcut that I actually learned today we can take these C1 C2 and we can enumerate them by taking the product of two arrays so I put the first array as this and the second array is going to be the same so when we say product we're just considering all combinations of this the first of them is going to be assigned here the second is going to be assigned here so it's pretty much doing what we had earlier we just don't need to do one extra layer of nesting with this Delta I'm actually going to put the new columns in separate variables cuz we're going to be needing them many times so just like this column 1 and column 2 now while we don't need to consider the case for column 1 and column 2 are equal we kind of do need to consider the case where the new column 1 and new column 2 are equal don't we shouldn't we consider that case no because for this if we try to reference current DP or the previous DP the value stored there is going to be zero because we never assign it in the first place we never consider that possibility so we don't need to consider when the column or the new column are equal but we do need to consider when the columns go out of bounds new column one could be less than zero new column 2 could be less than zero actually it can't because we guaranteed that's not going to be the case they never cross each other column one is always going to be on the left column 2 is always going to be on the right this simplifies things even more for us now we check is a new column 2 equal to the number of columns we don't need to check if column one is it never will be if that's the case by the way we just continue we skip that if that's not the case we want to compute the max number of cherries well what's the current number of cherries it's going to be Grid at the row column 1 plus Grid at row column 2 and we can probably just move this up because this is not changing within this loop we're using the original column so I'm actually just going to take this and move it up this is the current cherries this is the max cherries now to compute the max cherries we can say Max cherries is going to be equal to the maximum of itself or the result of the number of cherries in the current position plus the sub problem this is surprisingly the easy part how do we know where the sub problem is it's in the previous row aka the original DP grid and what are the coordinates of it is it column 1 and column two or is it the new column 1 and new column two well if we're starting at column 1 and column two and this decision represents the sub problem we have to consider all nine valid sub problems then of course we want to do the new column one and new Colum column 2 and if you look down that's exactly what we did in the recursive solution when we call DFS so nothing crazy lastly we want to out here before we do that over here current DP should be assigned to Max cherries after it's been computed and also we always want to update our previous DP with the current DP after it has been computed so just like this and what is the return value again well it's going to be stored in DP the coordinate is going to be the First Column start starts at zero last column starts at number of columns minus one so this is the entire code a lot of work usually the tabulation method is not this much code I mean there probably are ways we could make this more concise but I didn't want to like make it too unreadable so hopefully you can translate this into other languages if you're trying to do that let's run it to make sure that it works and it does it's pretty efficient you can see for once leak code is actually accurate this solution is definitely memory efficient if you're preparing for coding interviews check out ncode doio thanks for watching and I'll see you soon
Cherry Pickup II
the-k-weakest-rows-in-a-matrix
You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell. You have two robots that can collect cherries for you: * **Robot #1** is located at the **top-left corner** `(0, 0)`, and * **Robot #2** is located at the **top-right corner** `(0, cols - 1)`. Return _the maximum number of cherries collection using both robots by following the rules below_: * From a cell `(i, j)`, robots can move to cell `(i + 1, j - 1)`, `(i + 1, j)`, or `(i + 1, j + 1)`. * When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell. * When both robots stay in the same cell, only one takes the cherries. * Both robots cannot move outside of the grid at any moment. * Both robots should reach the bottom row in `grid`. **Example 1:** **Input:** grid = \[\[3,1,1\],\[2,5,1\],\[1,5,5\],\[2,1,1\]\] **Output:** 24 **Explanation:** Path of robot #1 and #2 are described in color green and blue respectively. Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12. Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12. Total of cherries: 12 + 12 = 24. **Example 2:** **Input:** grid = \[\[1,0,0,0,0,0,1\],\[2,0,0,0,0,3,0\],\[2,0,9,0,0,0,0\],\[0,3,0,5,4,0,0\],\[1,0,2,3,0,0,6\]\] **Output:** 28 **Explanation:** Path of robot #1 and #2 are described in color green and blue respectively. Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17. Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11. Total of cherries: 17 + 11 = 28. **Constraints:** * `rows == grid.length` * `cols == grid[i].length` * `2 <= rows, cols <= 70` * `0 <= grid[i][j] <= 100`
Sort the matrix row indexes by the number of soldiers and then row indexes.
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
Easy
null
463
hey guys welcome back to my channel and i'm back again with another really interesting coding interview question video this time guys again we are going to solve a graph question called as island parameter which is question number 463 before i start with the video guys just want to request you that if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications or more such programming and coding related videos and let's get started now with the problem statement so the problem statement is called that we are given a matrix basically a row into column grid matrix where grid i j is equals to 1 it means that it's land and if grid i j equals to 0 it means it's water so you can see that we have got this green cells which are brown in color and these are all lands and their values are one and the grid cells which are having zero value are blue in color so they are called as water and we can say that grid cells are only connected to each other either horizontally or vertically not diagonally so if this is a grid cell we can see that we can say that its neighbors are the cell which is above it with the cell which is below and the one at the left and the one at the right okay so we can say that this island uh these islands does not have any lakes so which means that there is going to be only one island in the entirety it's not like there are some islands here and then some islands here and they are not scattered all over the place in the whole grid there is only going to be one whole island and that island is going to be represented by the grids which are connected to each other horizontally or vertically okay now we want to determine the parameter of the island how do we determine the parameter so the perimeter is basically the boundary of the island okay and how many uh if we can say that the width or and the height of one grid cell is one so we can say that the boundary of the island uh will be just adding those one values which are actually covering all the island uh cells okay so here you can see that the yellow lines which represent the boundary of each grid cell that are at the periphery or that are not landlocked so if you just add all these yellow lines you will get a number 16 and that 16 is a perimeter okay so notice here guys that the yellow lines are only covering the grid cells which are actually at the periphery of the grid that means uh they are just at the ending of the grid all these yellow lines are encompassing those grid cells which are surrounded by water on their sides okay so we have to count the perimeter only of those cells which are surrounded either by water or either they are at the periphery of the grid okay now there is there are other examples also guys which are also similar to the previous one so i hope that is clear the constraints are that the grid length and grid columns they both range from one to one hundred value of the grid is either zero that means its water its either one that means its land and there is only one island in the grid okay so there are no lakes there is only one island in the group okay so i hope the problem statement is clear you guys now let's jump to the solution part of it so to solve this problem guys we are going to use the approach of depth first search which basically means guys that we are going to take one grid cell and then we are going to traverse through all its horizontal and vertical neighbors to find out if they have land or if they are water we will simply add their parameter to our current parameter value if they are at the periphery then also we will add their value to the current parameter if they are also a land then we will simply skip it and move to the next one okay so this is how we are going to solve this problem guys and let's jump to the coding part of it so the first thing which we are going to do guys we are going to actually find out the first cell in this whole grid which is the land so that becomes our starting self okay because in depth first search you have to start with the cell and then only you can do the depth first search of it so in my main function here i'm just going to run a for loop from i 0 to i less than grid dot length and then i plus and then there is going to be another for loop which is going to be j 0 to j less than grid 0 dot length in which we will be covering all the columns of the grid and then j plus and now i'm just going to find out if grid i j is equal to z equal equals to 1. once we have found that first grid cell which is a land it means we have found our starting point that becomes my starting cell and now we can take this starting cell and we can feed this starting cell in our recursive function so what i am going to do is i am going to call a recursive function which is again going to be called grid sorry island parameter in this recursive call i am going to pass my grid value my ith position and jth position value and in the end after this for loop is completed if we don't return anything from this recursive function i am just going to return 0 okay now it's the time to implement this recursive function let me copy this private integer island parameter the first thing which we are passing is the grid the second thing which you are passing is the x coordinate the third thing which you are passing is the y coordinate okay so this becomes our recursive function now we all know that in a recursive function which is the most important thing that means so that is the base condition and what is our base condition here our base condition is that you cannot reverse the grid if x is less than 0 if y is less than 0 because that means you are obviously outside the grid now so this becomes our base condition other base condition that if x is greater than equals to grid dot length that means you are at the end of the grid or same case with y that means y is greater than equals to grid zero dot length that means you are outside of the total number of columns and there is one more grid condition and that grid condition is if the grid x and grid y value is equal equals to zero that means you don't have to process that grid cell if it's water if it's land only then only you have to find out its neighbors right if it's water you don't have to find out the neighbors but what if we have found a cell which is either outside the grid that means we are on the periphery or the cell is water what do we do then we simply count its perimeter value we count its periphery line and we return it okay so if we take any such if we encounter any such cell which is uh not land the cell which is outside the grid's total size it means you are at the periphery or you are on the water cell that means you are going to return one for its that perimeter line okay so for example if you are on this cell you are going to return one for here and then if you are outside this cell you are going to return 1 4 here if you are on this cell you will return one for here and when you will come on the middle cell you will again return one for this one you will i mean so on and so forth so as long as you keep on encountering the cells you will simply return one in the base condition okay now coming to the next part if grid x and grid y is equal equals to minus one then we simply return zero now you can ask the question what is this minus one so basically guys if grid xy is equal to one it means it was land then we will process it but once you have processed that particular cell you don't want to visit it again and there is a chance in dfs that you might visit it again so that's why if grid xy is equal equals to 1 after processing we will simply set it to minus 1 so that if we land on that cell again in this condition we will simply return 0 we will not add its parameter value or anything we will simply return 0. now we are at our current cell which is x y and we know that x y is not a cell which is visited we know that it is not uh one of the base condition cell as well so now we have to process it for this particular cell let's say it's this middle cell let's assume that this particular cell we are not going to add any perimeter value so for this particular cell the parameter value will be zero if the cell is a land you will simply assume that its perimeter value is zero you will only add the parameters of its neighboring cells and that too if the neighboring cell is coming out of these base conditions okay so first of all let's check if grid x and grid y is equal equals to 1 if it is the first thing which we are going to do is set it to visited that means set it to -1 to -1 to -1 and then the simple thing we are simply going to add in this parameter the perimeter of all its neighboring cells so i'm just going to call island parameter here pass grid and then the variation of x and y so x plus 1 y and then just going to copy paste it 4 times so x plus 1 x minus 1 x y plus 1 y minus 1 so that becomes our total parameter for that particular cell so for this particular cell this becomes my total parameter finally i'm just going to run uncount okay now we have already called this recursive function in the main functions all that's left is just to run this code so there you go you can run this code and it is accepted for one example and you see it's now submitted as well successfully now talking about the time complexity so guys for the time complexity it is going to be order of uh m cross n where m is the number of rows and n is the number of columns okay because you can see that in this for loop also we are running two loops from rows to columns and obviously the dfs function is also taken into consideration or it is getting called once for every cell and because we have got m cross n cells that's why the time complexity becomes m cross n now space complexity is also the same guys because we are using a recursive call and the implicit stack will also take this much amount of space so you can see that the recursive call is again called for each and every cell and because you have got m cross n cells there will be m cross n calls and that's why the stack will take this much amount of faith okay so that was the solution guys i hope you guys like the solution and i hope it was clear to you if it did help you guys and do not forget to like this video and share this video with your friends if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications also guys if you have any questions comments suggestions any alternative solutions which can make it much better please do write down in the comment section below so everyone can benefit from that thank you so much for watching guys i'll see you guys in the next video until then take care and bye
Island Perimeter
island-perimeter
You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water. Grid cells are connected **horizontally/vertically** (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes ", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. **Example 1:** **Input:** grid = \[\[0,1,0,0\],\[1,1,1,0\],\[0,1,0,0\],\[1,1,0,0\]\] **Output:** 16 **Explanation:** The perimeter is the 16 yellow stripes in the image above. **Example 2:** **Input:** grid = \[\[1\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0\]\] **Output:** 4 **Constraints:** * `row == grid.length` * `col == grid[i].length` * `1 <= row, col <= 100` * `grid[i][j]` is `0` or `1`. * There is exactly one island in `grid`.
null
Array,Depth-First Search,Breadth-First Search,Matrix
Easy
695,733,1104
49
A high-rise is ready today, we will do the playlist's A high-rise is ready today, we will do the playlist's A high-rise is ready today, we will do the playlist's question number at 11:00. The question number at 11:00. The question number at 11:00. The question is kept medium. The name of the animal is Liquid 149. The name of the animal is Group and Grams. The question is very popular in this Banarasi. Amazon is multiple times and agonizing. Google is Uber Meta. Other companies are fine. It is quite popular, it is a very good question, okay but it is very easy to understand, it will become quite easy, the input will be given to you, this input will be given in number of frames, okay, what you have to do is to collect all the ad grams of gold at one place. Have to do for example 98 and the team, look at this, people of the same category, both of them are from each other's village, drink 98, okay, this is the family of both of them and Hindus are the family of TB, is there anything else, is there a lesson to be learned, this is a family. Gone is this city, we have cut it, now let's see what time it is and whether there is net, either 10:00 and net or have done it separately and whether there is net, either 10:00 and net or have done it separately and whether there is net, either 10:00 and net or have done it separately and what is the blast, when we sat down, it happened that we have combined all the anagrams into one family. A family that we have gathered at one place, it is okay and this is our output, pay attention, you are sitting right, you have taken the tan right up to 830 1 America, it is okay to gather all the villages and police stations of yours at one place, how can you find any solution? Now look at this, okay, you know this, it is a very important point that if we assume that there are 2n grams, we assume that R and any side effect of this, find out the nongram Rf, okay, you will destroy both of them in the standing order, so both are the same thing. It will become I, set this off, that R, I set this, F in ascending order. That man got both the beans, so what does it mean that if you sort them in the same way from all the anagrams, then take the same trick of all the beans, then that. Take your brain, we can use it here, you set each drink, okay, now look as if it is effective, okay, I am talking about anti, now I am okay, if I have sorted this trick till Saturday. ABT will come, okay, now I will talk about TA, okay, TGT, I have set it, then what will come, if the Acidity Sam thing comes, then both of them have different RAM, so I will race it and get it pointed here only. Isn't it, Sam thing is coming after both the pain, now let's come to the time, if you accept that I have set the time, then what is a sister team, right, aren't you, this is physical that I have set the time, so what or anti after this What is the TV, if you set it, what will happen, what will come if you start it will be given, meaning the same will be appointed to this one, so friends, these three are sorted, this has come, has n't it come, we will join the net, I will start the net. So what will come when the day is over? Simreli, we will start by sitting, we will set by sitting, so look at this BT, every family had gathered within itself, I am seeing, so it means that we have gathered, see how the acidity which is This software was sorted, what is this case pending, my ABT was there, my husband and daughter were fine, and now let's look at this, who were the anti option trading, who were there, who were the surveillance, but anti was a bigger AB vaccine. Girls Wedding AB TK was refined daughter now pay attention here you have got the answer then you understood it means you don't have to do anything you have to make a map take a map which is sorted string one that ring whatever Vikram Singh will appoint you in Vector of Prince, all these will be there and okay, your answer will come out like this, okay, you will take the Indian string, sort it, okay, if you set it, then accept it as a given and apply this trick of lagging behind in your set. Solved it in school spreading sector, I had set Tasty, next comes TA, set TA, then there is President in Agri map and put teacher in it, I assume cigarette, OT came, what is ABT when I start my daughter? Again, this course is a solid entry in funding and is just running. I have also put in one but it has passed. Similarly, the time has come. Suppose the time is there, now let's set the time. First, this is the map of the anti. If there is no President then I have put it in the map and the previous post was about leaving the entertainment team, now let's come to the knot, okay, if we will join the net, then why will anti come and anti is a new entry, so we will put the net here. Who is the last one, if you set Baith, then is ABT an entry of ABT? If I am not mine, then this will become an entry of clay and who had set it, BT had set it. Okay, so I will make you a favorite among you and make it straight. All these seconds which will give their return are ok in the answer, it is quite simple, so let's solve this, let's code it and let me tell you that there is another good one too, okay, in this we If you are using dry ginger, then it seems to have a different complexity and login to soften it. It will take time to clean it. Okay, let's assume that the length is like a string and the maximum is interesting and it is going to be like Ann Morgan's setting. Then you should also make it straight, right? I am giving you a number of princess cut. Suppose its length is A, then what will happen if Mintu is not unlocked, then there is another solution than this, I will tell you in this video, but first this approach clears this question for you. Requests, I will look at the question once, you will see one coming, Singh will be given, okay, you have to group everything with STRCMP string, okay, you can return the answer in any order, okay and you have been told what is Nagaram. When signup is already known, then that question is very small, there will be no problem in long time, okay, let's solve it exactly as we explained, so first we find out the length, n is equal to STR s.no s.no s.no i length. Okay now what do you do then let's attract the point eye mean equal to zero eye lashes one and half inch plus okay what do I am coming 1st in time I hand over that I also have to do a temple shot neither Celeste let's do this is my times and it is done, okay here what I said, we will start in the map that Noida takes the map, the shot of a lion standing will be here and then good morning which ones Words are the one who belongs to his family, then that person will be the film, right is MP and our result is that backdrop will be actor free, okay, they make it the default, okay, now what did I do, I took a string and softened it. Given, now I will not do anything, I am indebted to that love in you, that when I am an actor, I will confirm it. SSC is in RSI, so that's it, all the entries in my map are gone, now I will straighten the map in the result. If I push all the answers then I do my tweet and to it in MP is good ok result dot pushya back side dot second day hai na secondary to first this second Amritsar person fitting is ok and we will return the result one pan TRS How To's Sorry E And Correct Medicine Is Targeted Wearable 25 Gram Pulse Rate Liquid That And Guest House Pass Tod Test Cases Related To December Sample Solution Will Do Your Test And Leave It Good Morning Jayaram Ashram Up Map Then I took out the time complexity of it. If I look at it, this is the end size. You are getting fed up with it. Okay, so it will be N. It is okay, but now look, now soften each string also, like, what will be the quantity? They accept the size of each lion, which means see, whatever maximum number has been given to the lion, it accepts the maximum size, okay, so its America or it is okay for people's shopping and you will do it at the end because its side. And which is my given importance to enter into clock, its complexity will be a what write * k log k ok where k what write * k log k ok where k what write * k log k ok where k request to maximum size of the ring in the input ok and a sensible two sides of input ok so this There is also a better solution for this, which I will tell you in this video, if you pay attention to the constraints, it is written here that Asia Ras Aayi is made from lower case English letters, only Harik Hridaya Ko Loge is an English status, which means it also wants something. There is something in her which helps due to which this reference has been given and always pay attention to the constraints in the interview, constraints are given for some reason, it is okay for you to use that, then in the next video you will see how to use this girlfriend with these constraints. By doing this you can make more batter solution, ok Shiva's birth x video thank you
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,970
Hello friends welcome to code Sutra in this video we'll be solving lead code 1970 last day where you can still cross in this problem actually this is not a very difficult level problem this problem has two concepts or topics that is combined with it if you understand the problem step by step it is actually very easy to solve the only thing is to understand the problem statement very clearly and follow this problem step by step that's it so in this problem we are given the number of rows and the number of columns and it will form a row cross column Matrix for example rho is equal to 3 and column equals three so this is the Matrix that we have that is 3 cross 3 Matrix then the problem constraint is that we can travel in four direction for example if you are in this cell you can go to this cell and this cell that is you can travel in four directions then what is given is the water is filled into these cells one by one on day one this cell is filled on Day 2 this cell is filled for example on day one here this is not zero Index this is one index which means 1 comma 2 means this cell is filled on the day one so this is filled on the day one so if you are traveling from the first cell say you are traveling from this cell can you go to any cell in the last column yes right you can go because filling this cell has it is not blocking our path we can go from the first row to the last but let's fill the next day that is 2 comma one this is also filled with water when was this filled on day number two so can we go again from this we cannot go because on both the directions it is blocked but from this cell can we go yes we can go we can take this path and we can go to the last row so if already the water is filled on day two we can still go from the first row to the second row so day one we were able to day two we were able to let's check after day three can we go that is three comma 3 is filled this cell is filled can we go yes we can go right we can take this path that is will have to travel four cells but we can go to the large cell so on day three also we can go next day that is 2 comma two cell which is this cell is filled so once you fill this step is there any path you can go to the large cell no rights so on fourth day you can never travel from the top row any cell in the top row to any cell in the bottom row so we are blocked our path is blocked so in the answer of this problem is to find the last day which you are able to travel from the first row to the last row this is the problem statement so if you are not able to travel on Fourth a day then definitely not on fifth or on Sixth so this will be meaningless so our answer will be 3 in this particular case you have to find the last day which we have to which we can travel to the last so now let's try to there are two approaches one is you can travel with breadth first search or you can travel with depth first search let us first look at depth first search okay what is depth first search here is first thing is you will travel in the depth first as the name indicates suppose you are at this cell you will first go to this cell then again go to the next cell right however in BFS what we were doing is we were traveling to all the neighbors say you are at this cell you go to this first but in DFS what we are doing is we are going to the deepest self first so here at depth first search algorithm will make such make sense more than a BFS algorithm right why because we will go to the last node first if you are going to the last node first then this will make sense suppose if there was any water here it will just take an alternate path and it will reach try to reach the RAS last cell so here DFS is better than that now what is the objective of this DFS see usually DFS will be a what function but we will have a Boolean function here because this DFS will be having an objective with that right what is the objective of that the objective is to reach the last cell so once you have reached the last cell there is no meaning in containing once you have list the last cell we will return true that is any cell in the last row will be returning true if we can't reach the last that is we are say we are here and we cannot travel to any of these paths then we will written false that is you are you have tried all the options but you are not able to go to the any cell in the last row then in that case will be returning false so this is one of the powerful tool that we have to solve this problem that is the DFS algorithm always it is three Tools in this problem First Tool first powerful tool we got that is depthful search whatever will be doing here is DFS is a recursive algorithm what we'll be doing here is DFS will call all the full directions again it will call DFS in all the four Direction so that is what we will be doing and if the row or column is not in the range for example rho is less than 0 or rho is greater than the number of rows already present or the columns are not in the range we will return false in that case because it is out of range right for example you are at the first cell and you try to go to left which is not valid so that in that case it will just return false that is you cannot go then if we are already at the last row we will be writtening a true statement because we have already reached the objective then this particular cell that you have already there it will be marked with Y minus 1 which means we have already visited this node please don't visit this cell once again that is what this function is doing and for all the full direction we will call the DFS of I comma J what is I comma J that is the left all the four Direction Left Right top and bottom so if any of this is true that is if you are able to reach the last cell in any of these one of these DFS will be returning true if you are not able to reach in any of them will be returning false so I hope this function is clear we got the first tool to solve our problem that is the DFS the next thing is see okay we filled the water and we thought that we will we be able to go to the last cell or not say but the thing is who will fill the water right you only have to fill the water so I the idea is we will have another tool with us which will fill this cells and it will check if you are able to Cross or not we already have got one of the tools that is DFS now the next tool is we'll fill the water how do we fill the water we are given the cells here right in the first problem we have the given cell in this order the cells will be filled so what we will do is let's check if after day one we are able to travel or not which was the first that was filled 1 comma 2 was the first cell so we'll fill this cell or mark this with a different number that is one and we'll check if you are able to do how we will do it we will do DFS of this cell and we'll also do DFS of this cell what does it say are we able to go to the last cell from this or this if you are able to go we will just return true right after day one we are able to go then after day two that is we'll be filling this cell we'll again be calling will be filling this that is changing the row and column of this to one and after you are done with this again from this and this will be calling DFS if the DFS return true in either one of the case our total function will be returning true again after filling the water on this day and this day we'll again be calling where we will not be able to reach the pseudo code is very simple here but the one new tricky thing is we have to have a grid at every stage right we are given the number of days say for example you are given four days what it will do is it will fill water for the first four days in this case this are filled and what it will try to do is it will call the DFS of all the top empty cells and if one of them is successful it will return true if none of them are successful it is it will return false so what does this mean it means that on fourth day you can never travel from the first row to the last row if it is returning fourth similarly if our input is 5 what it will say is after five days the water is filled you cannot travel further similarly if the day is equal to 2 what it will say is yes you are able to cross me after two days of filling the water first thing is we'll fill the water and we'll check the with the DFS which we have already taken but do we have to check for every day that is Will D will fill on first day and we will do the DFS or we will call this function then again we will do the second day we'll call then the third day fourth day and fifth day say we are able to do on third day and we are not able to do on fourth day this will be our answer right yes so instead of doing a linear search on all the days let's think about it say we have eight days and you pick up a random number that is you pick up 5 here and you are not able to cross on this day right will you be ever able to cross on the day 6 7 or 8 no right if you are not able to cross on the fifth day itself that is our path is blocked the water will be more filled on day six seven and day so if you are not able to go on the day five you will never be able to go on the day six seven and E so we can safely eliminate all of this similarly on the other hand side say if you were able to go on day three is it meaningful to check on day one and day two no right because if you are able to travel on day three you will definitely be able to travel on day one and day two so where this is leading us is to binary such what we'll be doing is we will be checking on the midday and if you are able to travel on this day we can safely eliminate all the lower numbers similarly if you are able not able to travel on this day you can safely eliminate all the numbers including the same number on the right side so that is the key idea what will this function do first thing is we will have a range that is the left will be equal to day one that is the first day and what will be the right that is the maximum limit that will be equal to cells of length this is the number of days we will be filling water after that we will have a Boolean or binary search where left is less than right and we will find the mid value and if we are able to cross on the midday our left will change to Mid and are right if you are not able to do we are safely eliminating the right side of everything finally we'll be returning the left so there are very similar problems to the problem that we discussed here and if you have any doubts regarding these problems or today's problem please join the telegram group where we can discuss the solution or any doubts that you have with you so let's dive into the code the first function we have is the DFS function which will say from this cell whether you are able to travel to the last cell or not the first thing is if it is out of range that is these two conditions and we have one more condition which is we should only be having Land There we should not have or an empty cell and if it is equal to 1 or if the cell is already visited we will return false that is the first condition the second condition is we have already reached the final row so we'll be returning true and we'll mark this as minus 1 to mark it as visited then we have a directions array what is the direction array this will be our Direction array so we are giving all the four directions here and if we are able to reach the end cell in any one of them we will be returning true and finally if not will be written false this is the tool number one that we have got the second tool is we'll be marking all the cells in the grid as one that is we are filling up with water and we are filling up till day for example days 3 will be filling water only day three after that we'll be calling DFS on every grid and the condition here is we need not write this but it is good to write this why because if the first cell is only one that is we are having water it is we can't continue further right so it is checking this condition and finally it will return true or false finally we have all the three functions combined and it would be very helpful to make this as Global variables since it will reduce a lot of passing the parameters in the function so we will keep this as Global variables then what we'll be doing here is we will be doing a binary search where the left and right are the ranges and we will be doing a simple binary search and changing the values thank you for watching the video please do like share and subscribe
Last Day Where You Can Still Cross
sorting-the-sentence
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`). You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down). Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_. **Example 1:** **Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\] **Output:** 2 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 2. **Example 2:** **Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 1 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 1. **Example 3:** **Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\] **Output:** 3 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 3. **Constraints:** * `2 <= row, col <= 2 * 104` * `4 <= row * col <= 2 * 104` * `cells.length == row * col` * `1 <= ri <= row` * `1 <= ci <= col` * All the values of `cells` are **unique**.
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
String,Sorting
Easy
2168
35
hi today we'll talk about another binary search problem search insert position let's say what this question is all about all right so they will provide us a sorted distinct integer array and a target value and they're asking we have to find this target in the particular array if it is found then we have to return the index if it is not found we have to look not found so we have to see that if that target was available in this integer array what should be syntax let's understand with an example if we have an array of say 1 3 five six they give us a target five so we will find it here and then we will return the index to as an answer the other example suppose we have an array now they ask for 4 when we try to find this 4 in this array we never found it but if that 4 will be the part of this array in sorted order what will be its index so that will be here so we will say if it will be the part of the same array it will be one three four five and six so that will be its index and we would we have to return to here and that again falls to the bonuses because we can look a few things the first it's a sorted integer array and we have to find something and we can better find using binary search and we can find the element using log of n complexity so take an example we will always try to take a simple example like one three five seven suppose that and the target value is 4 and if we look at this target value should fall here at that point so within x2 so how we will do that binary search we'll take simple left index we will take a right index we will find the mid that mid will fall here in that case we will look that oh 3 is less than 4 our target value so we must found it here on that side of the array so we will move our left index to next to the mid at this point and we'll try to find it so after keep on binding search multiple iteration we will come at some point where left will be so one three five and at some level when we never found it right will be pointing here and left will be pointing here so left will be greater than left index will be greater than our right index but you can see that left will be pointing the index where our target value should be which will be 2 so that will be the answer so if you never found we will just return the index value of left pointer index let's see how we can solve using the code and functional programming welcome back now let's see how we can solve this question using binding search we'll make a function by search we'll see it's left index is zero and its right index will be our end array and we defined by insert function we'll say this is left that will be right and we were going to return the answer the index now that function what we think at the first step we can think that yeah if left will cross over right that left will be the answer it is our base condition and else part we can use the binding search here we will say wall mid is left plus right minus left one by two we find the mid and then we'll say if we found nums.mid is equal to our target nums.mid is equal to our target nums.mid is equal to our target if we found that we will say mid is our answer if we never found it and we see that nums at mid is less than the target so it means we have to find our answer on the right side of the array so we will bind search again and we will say find left index will be mid plus one and in the right in the else part means that when nums mid is greater than our target in that case we will use a binding search from mid from left to mid minus one and that's it now let's run the code so it works thanks
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
1,684
all right so let's talk about content number of consistent strings so you are giving the string a lot of consistency of the same character and an array of string word so string is consistent if all the character in the string appears in the string alone so you just have to return the number of consistent string in the array work so basically that you create a headset and then uh add every single character into a set and then traverse the entire world string and for each ward you traverse every single time and if you see there's a uh there's a character in not in a set then you just ignore and if there is a character uh every character inside the set then you pretty much just increment your counter and then you just return the content so let me just dive into the questions so in this case i'm going to just change the name this is going to be a and this is going to be string okay so uh i will have to create a set grab it and everything is important right character and pretty much just add that and i need to contact and i also need to know my stream for traversing type strings so and i would also need to increment my concrete every single point no matter what but i need to check every single character inside the world right so for r c inside the water tube array and then if there is uh something that is not in the set i need to break pretty much right so here okay so i'm not in your set see i will have to break so uh before you break since you add the contour right uh right after you uh enter the for loop right so i mean right before you enter the folder you increment your counter right but you somehow find out there's a character nine uh string word right so you have a bigger manual complete so this is pretty much a tricky way you have to notice so you just have to return a content so this is a solution and an enemy warning all right so let's talk about time in space this is space so it's going to be all of uh pretty much it's all of a right the length of the a and for time this is all of what all of s times follow w and w sets the maximum of the word be honest so here's my note so time is always times w is represented on the string of the word like the end of the string and the other represent the length of the word and this is the maximum the longest word inside the shrinks s and the spaces of a and a is a length a and this will be a solution and nothing is die
Count the Number of Consistent Strings
find-latest-group-of-size-m
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\] **Output:** 2 **Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'. **Example 2:** **Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\] **Output:** 7 **Explanation:** All strings are consistent. **Example 3:** **Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\] **Output:** 4 **Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent. **Constraints:** * `1 <= words.length <= 104` * `1 <= allowed.length <= 26` * `1 <= words[i].length <= 10` * The characters in `allowed` are **distinct**. * `words[i]` and `allowed` contain only lowercase English letters.
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
Array,Binary Search,Simulation
Medium
null
139
legal questions 139 word break basically this question want to check if a given string can be break into multiple valid words so the intuition is pretty simple we iterate through the strings at each point such as first number givens a little code so we start from l followed by e t until you find a valid word then we speak this word and we only check code later so once a value is being filed we will split the word and check the subsequence strings see that are they can they be four means a valid words so if we reach the end then we return true otherwise means that there's no valid pin forms between this given strings then repeated false so let's start coding yeah so it's valid let's build a nested functions for invalid we give a word it works set and then current start index yeah so let's build the word step first because the given word did is in a form of array so you want to put it in a hash set which can be done by word set you go to new set work date and then with new return is valid as what's that and we start from zero yeah so starting from zero starting from start index so we iterate from the start index by doing for i equal to start index is smaller than s dot length i plus right yeah check if s start index to i plus 1 is already work so we say 10 is equal to s dot slide start index i plus 1 if what's that has 10. if this is a valid word then we'll check the subsequence i plus 1 2 to the n right so constant subsequence remaining is valid equal to is valid s what's that start here starting test equal to i plus 1 right so if remaining is valid then we simply return true otherwise we'll continue in this loop to check for the next question yeah so when we will when we want to end this when we want to end these recursions we do that base case so if the start index is equal to the x dot length means that we are reaching the end for example if s equal to liquid then we are at i equal to 0 two three four five seven eight which is here it implies liquids it's valid right so we can shoot otherwise we'll keep on going so let's check i'll use a more complicated test case force y force because we are returning undefined means after the whole iterations we didn't return the value false so let's do it again it is taking longer than expected but anyway is able to complete yeah it's taking pretty long why is the time limit acidity basically it's because we have a lot of repetitions while performing is valid so for example we have checked us we have start checking from a certain start index multiple times because we didn't put a recorded status so let's use a dictionary to record the states yeah dp yeah so before we want to iterate from the starting text we will check if we have chatted this start index so if dp dot index is equal to true right then it returns false because it's invalid yeah so how's this dp in true and here we are done so for the time complexity analysis since by using the dp we only iterate we only performs or the iterations at every start index at most ones so there will be atmos and iterations for all start index so for site for start index e42 1 we will have a performance of substrings for from s equal to 0 to 1 s equal to 0 to 2 s all the way until s equals 0 to n so which give us a time probability of and of one plus o two plus o n is equal to about o n power square so since we have n such start index we can simply say that the overall time capacity is n times n squared which is bounded by o and the power q and for the space complexity space combination the dp structure cost product o n and the substrings cost at most om so in the end it's still on and for the stack space is also at most o n because n is the length of the strings yeah so conclusions times complexity of n power o n cube space o and yeah so that's all for our solutions the source code can be referred to the link further below as the other solutions for legal questions done in javascript that's all for this session
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
34
okay let's go Challenge number 34 finding personalized positions of Target in uh number list that was passing a parameter so we're going to find the Target in our numbers list now we're going to use binary search and we will Define concur our list okay so we're going to need first we put your first search we will be so we're gonna have to copy this and use it for the last next positions so it will be last search so this first and last will be the index position yourself the Target in the nums list and we will return that first and last next positions okay we're going to need to write the first search functions and it will take notes and it will be less right bits of integer and the bracket will be integer and we'll return that in the index positions so now we're going to use binary search before that we have to make sure if we couldn't find the Target in our nums list then we will return negative one as request okay so uh left will be equal to zero and then we're going to meet um nums length for our lengths and it will be the right leg the limbs and I can go to that so now uh the wall Loop will be left is less than right yeah they can be equal to I guess they can make in the middle right um and then if we will compare the mid with the target so nums oh don't forget to calculate our net mid will be left first right minus left and if half of that will be the mid positions so now it's the same circuit it is the same then we will return our mid positions so now um we still need to write the more logic in right here right before that we will have to make sure the binary search is working correctly and the logic of the binary research is basically we are uh comparing against with the target again with the mid is greater than the target then we have to update our right under this position and we are moving forward to the Lesser number for uh as to find the right target so now if it's not that the case if nums at the mid is less than the target then we have to update our left positions we just meet plus one okay so now we're gonna write the logic inside here say the logic it's basically is it the first number is limit the target or if ready for the number and the mid all right so it will be mid minus one is uh not the target so get the current the mid is the target that's what we're making sure we are making sure that so if it's uh right before current mid is at the Target right is it the first Target in our list and um we will if the mid is or equal to uh zero that means are we including the boundary if all these are true you will return the mid okay so if it's not true then we will have to update our right submit minus one meaning we have to move lesser uh to the Lesser number or less okay so now the last search so everything else the same but we're gonna have to change negative minus into plus and then we will change this into uh numbers Lane and then that's one of the nounseling and less than or equal to limit so all right is it within the boundary yeah is it the last uh Target it's the myth is the last Target and now we're going to have to change the left before these are not true then it should be moving forward to the larger number we're moving forward to the larger number so we're doing right so let's make this bigger so that's our answer now and let's try and demonstrate this in my code so of course uh it's gonna be um search range okay so we are processing the number from uh given list so it should be three five so all right seven eight and there will be 10 and the target is so make sure we're returning green four yeah that's correct so um the solutions because of uh the town complexity will be a big go of lock end because binary search right
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value. If `target` is not found in the array, return `[-1, -1]`. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[5,7,7,8,8,10\], target = 8 **Output:** \[3,4\] **Example 2:** **Input:** nums = \[5,7,7,8,8,10\], target = 6 **Output:** \[-1,-1\] **Example 3:** **Input:** nums = \[\], target = 0 **Output:** \[-1,-1\] **Constraints:** * `0 <= nums.length <= 105` * `-109 <= nums[i] <= 109` * `nums` is a non-decreasing array. * `-109 <= target <= 109`
null
Array,Binary Search
Medium
278,2165,2210
332
hey what's up guys this is John here so this time let's talk about some a graph problem here so it's called I turn number 310 30 and 32 reconstruct a ternary so you're given any input for the I turn rate with each element in the array gonna be the flight from airport and to airport so this one from Munich right I am you see two lhr I don't know where it is and this one from JFK I'm UC San Francisco to SJ say yeah so and so forth and you need to return a path basically right basically a path starting from JFK so basically you have to start with this JFK and starting from JFK and you need to use all the tickets once and only once right so what does this mean so basically you're giving like the tickets you have you can only use those tickets once but you have to use all the tickets all right so obviously this is gonna be a graph or graph problem right because we altered the ticket here with from and to we'll be getting will be constructing a directed graph right and so the problem will can be converted to traverse right to traverse each edge of this so each edge will be from and to right so it's going to be traverse each edge of the graph once and only once right and one thing yeah so if there are multiple like ways of traversing this graph and you need to return the smallest lexical other yeah right for example here like there are two possible with two possible ways of traversing this graph traversing each edge of this graph only once right one way is this the other way is this one but we're returning this one because the alt is smaller still smaller than SFO in terms of the lexical other right so when you see this like to traverse the used traversal edge once and only once you know this is like if you know the term each other you'll areas paths so for the Eulerian path you basically use you traverse this directed graph each edge and once and only once right for example the this one here and yeah I'm gonna write probably right at JFK here I'm gonna use this one I see example here so going to be JFK right from JFK to what SFO right and JFK can will also go to 880 L and SF o will go to ATL right here an ATL okay will also go to JFK an ATL will also go to okay SFO all right so that's the graph right so how should we do it right so they're like mud several ways but I think the most famous one is the there was this Germany mathematicians I think it's called a whole height Hyder yeah ho-oh hyzer yeah whole height Hyder yeah ho-oh hyzer yeah whole height Hyder yeah ho-oh hyzer yeah something like that so he invented an algorithm in I think in nine eighteen seventies 73 yeah so basically what a group algorithm does is from one node you randomly pick any direction right as long as there is a path you just use that direction from you pick one and any direction you just go along with that node and while you're traversing it so every time when you traverse like follow this path here let's say for example at the JFK right let's say we go with the ICF HOFers so once you traverse from this side you just I remove this ID from the graph and then which is recursive calling the same quite same issue a same like method well then will it will go to SFO and from afar as if oh it will also again randomly pick any edge from starting from this one and it will go here and here right until you reach a node that doesn't have any out any outgoing edges right then we simply stop because that node will be our last will basically will be our last visit nodes right because that's the we know we have to visit that node last otherwise we cannot visit odd notes once and only once right and we just keep doing it until we traversed when you will finish traversing all the nodes here right basically every time as allowance that node has an outgoing no outgoing add to edge we just follow that edge and we go to the next one so basically that's how the hi-hi Howser like algorithm to hi-hi Howser like algorithm to hi-hi Howser like algorithm to traverse this like your Arian path but remember here so we're for example here for this path from JFK right we're starting from JFK and as there are two ways right there are two outgoing Idris right when is that to SFO the other ones for a ATL and if there are two options so we it always wants us to follow the other smallest right small is like so lexical other when one realizes a single string so in this case will always traverse the smaller a smaller note first so that will make sure our paths will have this one instead of that one right because once we have all the other notes added to our result we will just come reverse the result irate because we're adding the last not visited note first and then we just keep adding at the back okay so I think yeah that's pretty much about this problem let's try to code it right so one thing is that uh once we build every time we will build to build a graph first but remember when we so you already when we build a graph right what do we will create a graph right and then we just do like the dictionary right but in this case since we want to choose this like the neighbors the name the neighbors of this current node like from smallest to biggest one so we have to either we need to sort that list right or we can use like a prayer priority queue to store that the neighbors so basically every time we can make them be sure we always get the smallest one right so let's use a priority queue here so we're gonna we have to import that first from import queue from Q import price are a priority right queue and then rebuilding the graph first so default dictionary right so for each of the graph you should have to add the element in dictionary we're gonna the value the key will be the iron the airport name and the value will be the prayer our htq right and then we simply just construct this graph by looping all the tickets here right for ticket in ticket right origin right orange in and equals to destination right destination basically you goes to what sort of basically the first one is the origin and second one is the destination right and then we just built this like directed graph here graph from or orange in dot right so since we're using a priority queue we just we need to use a put right that's the method for the product if we put this destination to it so that's how we maintain like a priority queue in inside for this like for this our original airport then we're gonna have like an answered store our reads out and right and now we have we need to create a like a helper function define like a DFS our right helper functions so here we're gonna have the node right and then so what do we do here right so with note right with note we get the next least right so that's the graph dot node so this night next the list will be the out idea all the nodes at the neighbor nodes of the current node right so like what we said about it is like algorithm while right we have we will basically they will keep picking what we'll pick out basically will loop through all the address starting from this node right next basically it's nice next destination right it will be the yes so this since the priority queue to check if it's empty or not we can just check the queue size right the queue size is bigger than zero right so and then we start if it's zero which we know we have already a consumer audio the address starting from this node next please stop get right so basically every time we get the first one which will be the smallest that's how we can be sure we always select the smallest electrical airport right yeah sorry that's my Alexa yeah and every time once we so every time when we finish traversing this node this edge will be basically remove it from the priority queue so the catwalk simply removed that's the first one and then for each of the next which like I said which follow this path we just keep calling right keep calling this same thing over and over until right until we have finished until we finish audio traversing audit all the neighbors other the address starting for this node right then we know we reach the last visit note right so we just do a answer right dot append the current notified the current node yeah actually this is not a node I would say or like it's arranging right so it's not a note it's a string here it's a value so origin and then yeah and once when we finished reversing everything so this answer will have the audio the art answers starting from that from the last so arranging yeah and then we simply return a nice right a reverse step reverse a reverse that result yeah here will be JFK right so it's a fixed starting point basically let's see a pen all right cool yeah it's passed all right so I so why this algorithm works right let's say we have this like JFK uh let's see LAX right and then M you see right let's see we have this graph right it's pretty easy right okay let's see how this thing will give us the final result right so we starting from JFK right so from JFK we have assuming let yeah let's assuming we don't use a priority kill which we just use a random regular list so from JFK and we have two options right so as you can see here there are actually there's only one way we can traverse the tree by consuming all the edges once and only once right how we have to go down first and then go back and then go right so basically we have to consume this path first and then consume this path and then consume this one last all right so from JFK let's say we are we go from this we follow this path first right we go here and then we write like we write every X okay so we don't every X doesn't have any path basically this one will be empty then we just fine okay our X doesn't have a doesn't have any edges anymore so we'll add LAX to this like answer right and then which we just come we'll come back here and then it will keep going it will go back up go up one level so it will keep traversing down here right then it will come here you see oh it's in the Munich right you see I'm you see Airport does this one also have like address yes they still have this one so will also follow this one go back here right so this one is gone and then we follow back to the JFK and then we see Oh JFK doesn't have anything remember this one is also gone was also gone will remove this one after we traverse to this our X so now JFK doesn't have any outgoing edges now we add this JFK to the list right so it's gonna be our ax we add this one and then j FK right and then in the end to the end but so the last one will be mu C right so that's the result and I'm sorry yeah I'm sorry so going down going right and then we come down here right so the first thing will be coming down here the next one will be coming down here oh sorry so it's not done right so basically there's one more here so in the end there's like one there's another lax here in the end because so from JFK to 2m you see right and then from em you see to JFK so they're gonna be to JFK here that's to visit of JFK so the first one will be this one after this one JFK's 0 and then basically that's that this JFK has doesn't have any outgoing does have any outgoing note then it will return JFK but no returns mm you see right em you see doesn't have it but in the end remember Turtles like also another level of Travers here so in the end sorry we'll also add JFK to this one so basically when we reverse it's gonna be a JFK I'm you see JFK and iox right that's how this algorithm works so it doesn't matter right so assume you know let's say we don't trip with that we didn't reverse to the right side for let's say we traverse we chose this the I mean we chose this path first right so we are so we're coming down right so once we coming down here we do I'm you see right so I'm because I'm you see have a note right I'm you see right and then we remove this one right and then does I'm you see have a outgoing yes we go back to jail to JFK all right this JFK hasn't has another one yes we do go to go right because after we traversing down this edge was not there anymore so it will go right and this again will still end up to this like a yaks note first so that's why we'll be adding to LAX and then once we can't we go back to the rich went back to the last trevor our recursion level this one is not there right so it does JFK has an outgoing at no right so all both of the going outgoing riders have already been removed so the JFK will be the second and then come back to here I'm you see is there a I'm you see is there like an old there no right this one is gone so its third one is I'm you see and the last one is still at the starting point also JFK here so will be getting the same result alright guys cool so I think that's it for this problem yeah I hope you guys like it I think so much for watching this video okay let me know if you guys have any comments or anything else right so I'm thinking about like buying a video cameras yeah we'll see okay thank you guys all right see you guys soon bye
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
1,041
hey guys welcome back to another video and today we're going to be solving the lee code question robot bounded in circle all right so in this question we have an infinite plane and a robot originally stands at 0 and faces north so the robot can receive one of the three commands so g is going to say go straight by one unit l turns it to the left by 90 degrees and r turns it to the right by 90 degrees the robot performs the instructions given in order and repeats them forever and make sure you understand that given a set of instructions it repeats them forever okay so return true if and only if there exists a circle in the plane such that the robot never leaves the circle okay so this question by itself is actually not too hard but there's one small thing you need to understand in order to solve this so let's just look at this example over here so we have ggl lgg so what does that mean so it goes straight then turns left and left basically turning 180 degrees and it goes straight again and ultimately what is happening is it's starting somewhere going somewhere and coming back to the start point so that is very important we want to have some sort of cycle so by the ending of the cycle our robot has to come back to the starting point and if it does not do that it's infinitely going to go in some direction it is never going to come back to the starting point and it is not going to be in a bounded circle so it is only going to be in a bounded circle when it returns to its starting point after a specific cycle what do i exactly mean by that so in order to do that let's just draw this out okay so let's say over here i have my starting point denoted in the color green so that over there is my starting point and now what i'm going to do is i'm going to move to the front by one so let's just write out our command so it's going to be gr okay so let's just first go by it and then we can see how we can use a tuple or vectors in order to solve this okay so first we're going to move one unit so we move and then we end up over here great and now after this what do we need to turn to the right so currently we're facing in this direction but now when we turn to the right we're facing this direction okay so now we change the direction we're facing so what are we going to do now so now what we want to do is we want to move uh again right because we're repeating these instructions infinite amount of times so now we move by one unit and we end up over here and right now we're facing in this direction but again we turn to the right ending us uh in this direction so we turn 90 degrees now we're facing this direction now same steps we move one unit end up here and now we turn again and now we move one more unit and we end up here so what exactly happened so by performing this four times what happened is that after performing for a turtle four times we returned back to our original starting spot we came back to our green spot so now let's say we do this infinite amount of times so no matter how many times you do it we're always going to stay in this certain area we're going to be performing the same thing over and let's say there was a circle over here we're never going to go out of the circle but let's say we had different instructions right where let's say we just had the instruction g so what does that mean so we start over here and we just keep moving unit by unit and there's no stop to where we go so there has to be some sort of cycle and in order to detect one of these cycles we must be going around this at least four times so once we go around it four times we can know for a fact that there is a cycle so if four times is going to be the maximum amount of times but there could be a cycle in just one iteration for example look at this one over here and just one iteration there is a cycle right so just going through the instructions one time finds us a cycle but the maximum amount of times that we could find a cycle is four times but if there is not a cycle by four times that means there is no cycle at all right so now what we're going to do is we're going to see how we can actually do this in our program so over here we're going to have our starting point just as before and do remember that we always start at the vector value 0 comma zero and we're pointing at the north direction so we're pointing upwards okay so let's just create our own set of instructions and let's make it pretty simple so you can understand so let's have gg so we move up by two points and then afterwards we're going to have right then go then left then go so this should cover all of our cases and let's just go over it okay so let's just go back one by one and before we do that we're going to have a direction vector over here and this is going to be a tuple values of x comma y values which we're going to add to our position values in order to show change in direction to be more clear to show change in position all right so we're at zero comma zero and we wanna move by one unit so in this case always our direction vector is gonna start at zero comma one since we're pointing north and zero comma one means that we're changing the y value by one unit so we're going up by one unit so now when we do go in the beginning we're gonna add this direction vector to our position vector so what is that it's just gonna be zero comma zero plus zero comma one giving us zero comma one so now we're over here at zero comma one perfect and now we do it again so we add this direction vector again to zero comma one since that's our new position and then we move up leaving us over here so currently we are at zero comma two as position and we use that and we got there by adding the direction vector 2 times but now we want to turn to right so we can do that and we can't use the same direction vector right because this is for going up we want to move to the right so how can we do that so in order to do that what's going to happen is our direction vector so whatever is on the right the y value becomes the x value and the y value becomes the negative x value over here so negative zero but obviously that doesn't it's not a thing so it's just zero so one comma zero is going to be our new direction vector okay so now we have one comma zero and that means that we've turned to the right so now when we call our go function which is right over here we call go and what happens when we call our goal function is we do the same step so we're at zero comma two and we're gonna add one comma zero so that ends up with one comma two so now we have one comma two right and that is our new position so in that case what happened is our new position is right over here uh since the y value stays the same and the x value increases by one since we move to the right by one unit so this over here is our new value and that's perfect so that's exactly where we want to be and now let's perform one more step and we're performing we're towards the right direction but now we want to turn to the left so we couldn't do the same thing right but now we're going to do the exact opposite so what's going to happen is the x value becomes the y value but it becomes negative and in this case it's just 0 so it's just going to stay at 0 comma 1 and we're moving to the left so now we do go and we're doing zero comma one so basically first when we turn to the left we're actually pointing over here and that means we're going up and when you do zero comma one we end up over here okay so one more thing i just want to clarify is what is the purpose of the negative and i know it sounds a little bit confusing but let's say we have something like left comma left right so we have three else in a row and how is that going to look like so let's just uh think about it first so we're pointing here and we turn to the left and then we turn to the left ending up here and one more time ends up here so just for the sake of this let's just do two lefts instead so l comma l right so just two left okay and let's see how this looks like so first we're starting off at zero comma zero okay and our direction so this is our positional vector and our directional vector is going to be uh zero comma one right so now when you turn to the left what's going to happen is that we're going to end up with one comma zero and now again when we turn to the left what's going to happen is that we end up with zero comma negative one so we end up with three comma negative one and now when we perform the go function we're moving down by one which makes sense because currently we're pointing at north then we turn to the left so now we're pointing to the left and we turn to the left again pointing downwards and it makes sense that our y value decreases when we go downwards so that over there is the purpose of the negative and it has the same implications when you're turning to the right all right so hopefully all that did make sense and i think the question is not too difficult once you understand the concept behind it so now let's code it and see how that looks like all right so let's start off by defining our directional vector so i'll just call it direction and what was it in the beginning so we're pointing north so we want to move up so it's going to start off with zero comma one pretty simple okay and now we're going to start by defining our start value so i'll just call it start and this is going to be a tuple value of 0 comma 0 because that's where we're starting and 0 of x comma y okay so now that we have this uh we're going to go inside of a for loop so this for loop um we can just do for underscore and range four and the purpose of this is to repeat the steps four times and like i said earlier four is the maximum amount of times we need to do a certain set of instructions in order to figure out whether there is a cycle okay so we're doing it four times and over here we're going to have our main logic so over here we're going to iterate through our instructions and i'll just call it x so for x in instructions so over here we're going to check what the instruction is so if x over here is equal to g we're going to do something okay so that's one condition uh if x is equal to um left that is going to be our other condition and our last condition is going to be if x is equal to r and that's the same as just saying else but let's just do else if x is equal to r okay so those are our three conditions and one more thing this should be else f okay so now that we have these three conditions we want to see how we move accordingly all right so let's start off with when x is equal to g so in this case uh our this is the only time when our robot is actually moving so how do we apply the move right we're applying the move uh to our start vector right we're changing the position and how are we changing it we're changing it by adding the new the direction value right so let's see how we can do that real quick so we're first going to add the x values right so the x value for start is whatever is at the zeroth index and we're going to add that with whatever for the direction vector is at the zeroth index now we're going to perform the same steps for the y values so this over here is going to be 1 since the y value is at the first index so over here we moved whatever it is so now over here we want to do the rotation for the left or the right so for the left over here we're going to change our direction as follows so direction is going to equal so it's going to be a tuple values like uh defined above and the first value when returning left is going to be negative and this is going to be direction 1 right so we're getting the y value making it the negative x value okay and the y value over here is going to be the previous x value so direction zero okay perfect and that is going to change our direction of vector in such a way that we move to the left now or uh whatever it is that once you turn to the left okay and now that we have this we have our last conditions which is moving to the right i'll just copy paste it over here and the only difference is that this over here is not going to be negative why this over here is going to be negative and that's it so that should be it and at the very ending of this uh we're going to go outside of the for loop and we're going to return if our start value is equal to zero comma zero and that means that we did not move anywhere right we stayed in the same position uh and this is supposed to be double equal since we're checking for comparison all right so i made a really dumb mistake uh so you can't really change the values inside of pupil so sorry about that and so what's going to happen is let's just change it to a list instead so we have this as a list over here and this is also going to change the start value as a list since we can change the values of a list okay sorry about that and submit and as you can see our submission did get accepted and i do want to show you one more method so over here we can actually uh use the same logic but make it a slightly bit faster so we're doing the same thing but we're iterating over it four times which sometimes is completely unnecessary so now what we're going to do is we're going to iterate it through it only one time and a smarter solution to this is after one iteration if our direction vector still has a value of zero comma one that means that we're still moving upwards right then in that case we're not going to have a cycle so what we want to do is we want to check if it is not equal to zero comma one because that's what we need in order for it to be true okay and now that we have this we can just submit it and this is also accepted so finally thanks a lot for watching guys do let me know what you thought about the video and don't forget to like and subscribe if the video helped you 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,292
all the training lead coder solution if you want the best mock interview experience in North America feel free to check us out at depository in the Lord we're here to help you lend your next big offer today we're going to talk about well lead coach solution 1292 I cannot believe right now it has like more than one thousand problems so simply put it right there's no way there's absolutely nowhere then it's absolutely not necessary for you to finish all of those questions before you go on interviews remember it's actually you know just the it's not time and cost efficient to do this all we need to do is basically for each of the data structures you just brush up like five questions that most and then actually the lead code balls of training on equal solution that YouTube playlist if you finish all of the videos you're pretty much done so okay let's get down to this problem that actually looks pretty familiar so it's not the best of well-defined a problem so given a well-defined a problem so given a well-defined a problem so given a two-dimensional matrix M times n this is two-dimensional matrix M times n this is two-dimensional matrix M times n this is a column at and integer threshold return the maximum side length so what exactly the side length right it didn't really explain to well the side length essentially is like if you only have one number the side length is what if you have three numbers a square is 3 so the side length of a square with the sum less or equal their threshold or return 0 if there's no such square which is totally possible so if you look at this graph right so the output it will be cubed because the threshold is 4 because at most you can have like 1 so this is equal less or equal than threshold all the rest are actually bigger so they want you to return the maximum one and then this one you know threshold is why every single element is larger than one so we should return zero so this one it's a six so if you pick those down you can see sorry not six three okay so give it this problem what is your thought so there's a definitely absolutely false way right so is like for each of the left you can start from the minimum of the row or column you literally do another kind of M times n just to calculate the sum so we know that's definitely not optimal and at that moment we should remember we used to have this problem I cannot find it but I definitely saw this before it's like a prefix some matrix what so what is the prefix sub matrix so a prefix sub matrix a matrix and for each of the cell in the matrix representing the sum you know original matrix the sum in the original matrix from make sure is eros zero two matrix I energy so this is a kind of the mathematical formula so quick you illustrate is so let's say if this is a matrix right so if I want have this point so the prefix some matrix of this point is essentially this area okay and then let's say if you have you're on this point the prefix some of this matrix at this point so for this one it is actually the element itself and then if it's this one it is looks like this and then if you are here so it's like this it can be a rectangle and it doesn't necessarily need to be a square so that's basically the way it is so once you have that you have this kind of thing so now if I'm telling you okay so what is the sum of this area so what you can do is you can use the sum of this area right you have miners the some of the left apart and then you - the some of left apart and then you - the some of left apart and then you - the some of the top part and then you've some back this part or this part you - it twice a this part or this part you - it twice a this part or this part you - it twice a day you have to summon it back then essentially you will get the sum of this part sorry I draw this line wrong this line should be drawn up here right so which is like essentially this is kind of great sorry this is great you have to draw it back so yeah that's certain see it has to be like either I minus one or if this is a J this should be the J minus one so if you see so this is basically a formula so you have I plus let you have the sum at this particular case minus I minus 1 i minus 1 in the previous row now this row the previous row the length of that and then minus this part and then you plus back the other part so this is how you calculate sum so that said you can actually have a relatively you know it's easy efficient you know whether it's old times the time trans is o M times n times minimum of n times n so it's actually is like in cubes have a time complexity so essentially what I did is so you get a row and a column of the mat and then you want to allocate a plus one because whenever you calculate today's right so it's just easier so now if you have a like here if you allocate a the resize password so for one because for every element that the prefix sum is calculated as you know is basically like this value plus this value minus this value and a plus itself so translating into code oh okay let me see I think I have it here yes so trust me they didn't to code it looks like this so the initialized part you have your left part the left part plus the right part miners the diagonal part and then you have to plus the value on its own so this is a basically you constructed the prefix some array and the ones you have because if you allocate a one extra right so all those are defaulted to like 2-0 you can just calculate everything 2-0 you can just calculate everything 2-0 you can just calculate everything just like a zone for example is the one is 0 plus 0 minus 0 by plus 1 that was still one right so yeah just calculate it this way you realize is a way easier and then you're basically doing this kind of like a put false way right so you just basically choose the minimum of the row and column and then for each of the row and column starting you know we want to start from the maximum to minimum so we're doing this like a triple four loop nested for loops and then here we essentially calculate in the sum I just explained it earlier and then if it's less or equal in a threshold you just return the results so this is the brute force way oh and Owen cube a method right there's other two optimization you can do actually if you follow the hint he asks you to use binary search so there's a binary search way you can do I link to the solution here not this one but I think this yeah it is this one so it's the same thing when you would constructed a song write the matrix and then you can essentially do a binary search because of what we're trying to do is we're trying to find this condition which is exactly like we coded before whether the square is this condition and then we want to find the maximum one so what happens if the maximum one is a like a super down in the left part which is really small so if you go in from the right all the way to the left and all efficient you can always cut in half there should've should I go left alright so if you need to go right you can just binary search way to do it right so that it will basically helps you in a log minimum of M times in solution there's actually a smarter way shoutout to drunk piano to solve this is whenever we constructed the sum right we can actually with the prefix sum we can actually along with this process we can actually also calculate out the less this is purely based on the assumption that on this problem if you have for example a square that is 5 by 5 that satisfy your need that means there's definitely a square of 4 by 4 can satisfy your need so which it also means basically that will definitely be a square of 3 times 3 2 times 2 and 1 times 1 right because all those it is the sum of all those values so that's why you sent to the water this most Ultimo algorithm is doing is whenever we construct this the array you're like ok let's just check if there's any square one can set if I'm I need if they're square one can satisfy my need I just increase my lens to be actually is here I just increased my lens by what so now I'm looking for is raining square of two that I can Center satisfy many so that's basically just keep increasing because if there's a square let's say the maximal solution is a 5 there has to be a maximal solution of 2 and then there has to be a maximum solution 3 so you in that case you actually won't miss anything by this scam so that book is basically give you the best solution it's kind of hard to think I would say in the real coding if you have the in Cuba solution you can code up correctly seems should be fine all right let me know if you have any questions leave any comments below if you liked the video please subscribe and I'll give it a like button click the like button until then I will see you guys next time bye
Maximum Side Length of a Square with Sum Less than or Equal to Threshold
immediate-food-delivery-ii
Given a `m x n` matrix `mat` and an integer `threshold`, return _the maximum side-length of a square with a sum less than or equal to_ `threshold` _or return_ `0` _if there is no such square_. **Example 1:** **Input:** mat = \[\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\]\], threshold = 4 **Output:** 2 **Explanation:** The maximum side length of square with sum less than 4 is 2 as shown. **Example 2:** **Input:** mat = \[\[2,2,2,2,2\],\[2,2,2,2,2\],\[2,2,2,2,2\],\[2,2,2,2,2\],\[2,2,2,2,2\]\], threshold = 1 **Output:** 0 **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 300` * `0 <= mat[i][j] <= 104` * `0 <= threshold <= 105`
null
Database
Medium
null
1,797
Show More Hello Everyone Today We Are Discussing Questions Many Questions Off List Ko Title Add Designer Partition Manager By Name Do You Understand Some Questions Related To World Design System Design In The System Will Receive New Updates Time To Day Do Subscribe Thank You Will Now Be Able To Edit And The Current Time To Live In Quentin What We Have To Women In Distress If Liquid Class Construct Authentication Manager And Saturn Placid Means Token Will Be On That Time To Life In Live As Much Time It will remain live for long period of time in which operations have to be performed, renewal has to be generated, one, generally this age is approximately 101 current time in quarantine, it will be updated at that time, reddy time, after time renewal, renal expire token, more means the Current Time 10 Top 50 Expected To Be Not Review Nor Do They Want To Give The Name Of Petrol Which Money's Memorandum Current Time 2014 Twitter The Number One Expected To Be Open Let's See It Will Keep Gold Activated Weight Generated At This Time 600 270 Circular Or Chapter Lewis 5 Second Day After Loot Start Amazing And Like This And Time Of 20 Renewed This Next To Be A Time Table And Will Again Elected For President From Shyam Okay 100 Is This Understanding Can We Use A Dictionary Can An Impatient Valediction Begins To Person In General And Colleges Using Local Time In New Delhi Articles By Your Name King Junior Matter What Generate This Frozen President This To Connect With The Talk With Just Provide In The Current Time Renew Subscribe From Time To keep it in order to keep it up character limit candidate renew the to commit friends quadruple increase tok token id just amazed current time and then i want to see the time of nation in the current time that is 9am donate year hotspot To Ajay that it should be a salute to con fi do not quitting and post method this town turning point options do and creative wearable limit decide how to change the unexpired open that if job attitude some limit better apps to connect with the time wishes Limit Should Be Punished By Penal Chart This Punished By Penal Chart This Punished By Penal Chart This A Grade This Is A Greater Than Limit Don Accuse Play And Even In Account Update The Value Of Account With One Increase The Value Of Account Weapon And Celebrate And Belief Com Contract Solution Of This Question Was Simply Amazed At How Do You Do The Time And Third Is A Running Court Stays By Proposing Formation By This Time Code And See What Is The Name Of The Co Justified Working For Editing And Design Question Statement Note Required And More Solution Stop dancing with this question ninth jumping to next question ok steve again in next question can be used on hua hai
Design Authentication Manager
goal-parser-interpretation
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. Implement the `AuthenticationManager` class: * `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. * `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. * `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. * `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. **Example 1:** **Input** \[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\] \[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\] **Output** \[null, null, null, 1, null, null, null, 0\] **Explanation** AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens. authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2. authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1. authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7. authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0. **Constraints:** * `1 <= timeToLive <= 108` * `1 <= currentTime <= 108` * `1 <= tokenId.length <= 5` * `tokenId` consists only of lowercase letters. * All calls to `generate` will contain unique values of `tokenId`. * The values of `currentTime` across all the function calls will be **strictly increasing**. * At most `2000` calls will be made to all functions combined.
You need to check at most 2 characters to determine which character comes next.
String
Easy
null
729
hi guys welcome to technique so today we are back with the daily link for challenge problem that's my calendar one uh that's unique good medium question lead code medium 729 uh basically this question belongs to uh fan questions if you have seen uh kind of uh merge interval questions uh it's similar to that so white asked if you know how to approach this Concepts and um a little bit of harder level if you talk about because it's not easy for everyone to get through what they are actually asking so before beginning I'd like to request you to please like share and subscribe to my channel go visit the health sheet that's hiring healthy for various companies which I have shared I'm working on other companies too we'll be sharing it very soon for the batch of 2022 and 2023 I have shared multiple openings for three to join that if possible connect on Telegram and Linkedin for further updates because many job openings are in there that could be posted as videos so I just share the link on my channel okay let's see what the question says you have to implement a program to use as your calendar now in a calendar what we do we can add an event okay so we can add an even but making sure that on adding that email okay there are no double bookings so double booking is what double booking happens when two events have non-empty intersection okay non-empty intersection okay non-empty intersection okay now we'll explain you what they mean that it can be represented as a pair of individuals that start and end so for any duration you need the starting point at the ending point that represents a booking and if you have a half open uh interval so you must have studied about the closed intervals and the also it's similar to match open intervals refers to that we don't consider the ending number okay so that's what they want to say so what all we have to implement my calendar class where my calendar initialized that's a Constructor initializes a calendar object and a function that returns true if the event can be added that means there are no double bookings or return points okay that's what we have to do we have been given some set of examples so let's consider the example given to us is this okay this is the example that's given to us now if uh we'll talk about directly what would be the possibilities that would make up okay so you can see for the first one as initially you don't have anything so if you don't have anything then obviously you can let's have this number like this initially you don't have anything that means from 10 to 20. sorry yeah from 10 to 20 you will not occupy so now you occupied yourself okay comes to the second part the second says 15 to 25 now 15 to 25 you can see that this part is already occupied so that means you are having a collision for double checking so this cannot be added this down here then coming to the third one 20 to 30 now you can see this 20 to 30 this get address so that's what we need to do we need to maintain vertical order so what we can do is we need to maintain a list of intervals okay and we have to check for any two intervals let's say we have a starting point and we have an ending point we have a starting point and equal for two events we have to check this should not conflict they should not conflict in what conditions that means they should not conflict if starting one is always we don't want any collisions so Collision won't happen if your ending point of forced okay is less than or equal to the starting point of the second Let's see we have one more 5 10. 15 20 Series so in this obviously no Collision would be there if you talk about these two so how is this possible the ending point that's E1 remains less than or equal to starting of 2. that's your basic concept or we can do the opposite Also let's say we have been given this first and this next then in that case we could also say if E2 is less than or equal to s that's what we need to check somewhere we can say that we need S1 to be less than E2 and S2 to be less than E1 if such things are there that means conflict will occur or double checking would double Loop so that's what would be the conditions but if we do it like rigorously we check to two so obviously for this case are complexity would go with order of n Square because we are comparing two sets again and again that's what could go on and a complexity of space complexity will also be order of n because we are compared comparing story so that's not an efficient way if you go up okay see the one which I explained is somewhere like this will create a song we'll create a list for this list we'll run this Loop and check for this particular element that for every element it's a of 0 and start and if this so this is a modified version that will go off with order of n because this time we are not running a loop inside you we are just taking for the maximum value of the start and the start available so the Collision that could be possible and here the ending voltage for the minimum and the end okay then comes the second and a quite good approach that's for the three marks you can see a tree Mark is always there so what we'll do we need to store these elements or you can say the duration in a data structure that key that will keep the element in sorted order the first thing and we'll have the past insertion so why we are using pre-map insertion so why we are using pre-map insertion so why we are using pre-map the reason is very first sorted elements and second is past insertion so somewhere a Time complexity would be improved that's what we have to do so we introduce a streamer for the same things now pre-map what we'll do we'll check for pre-map what we'll do we'll check for pre-map what we'll do we'll check for the Peaks okay starting of each interval that we have started in a wheelchair the previous whatever we are getting uh the start and end should be less and similarly for the next one it would be same so as you can see we are taking over the floor he and the floor entry and the ceiling right so what is the floor entry and a ceiling entry in a tree map that's what we need to know right now see what we are doing we are checking that the floor entry of the start slot equals To None So slower entry is actually giving us a key value mapping that is with the greatest this gives the greatest and this gives the smallest okay so the same way we would get uh we were trying to get the method dot Max using a loop for I equals to 0 to I equals to N2 I less than n the same thing instead of writing this Loop we can directly use this function so this will give us the greatest value that's greater than or equal to and if there are no such keys so it will return none so we'll check if it's not null and secondly if that value is greater than start and the same case the smallest value should be less than small sorry less than n so if these K Circle that means there are no Collision if no correlation that means it should be added to the free map and returned true so when we do this so when this particular condition is being followed up okay so what is the problem or uh what's the time complexity improved so as we said we have faster addition that's insertion right so for this case the time complexity goes up with order of n log instead of n Square we have improved that to order of n log n what is uh this l login goes up with the insertion as we said will take order of one time okay and for each new evil okay searching this part that goes up will go off with order of logging in insertions in order of one that's all dropped in this order of then the space Remains the Same so that's what the complexity would show up I hope the solution is clear even if uh there are any queries do let me know I'll be there to help you out a simple request to you always please share my Channel with my content with your friends colleagues and your Juniors it would be a great help and if there is anything you'd like to know about any recruitment process any interviews to let me know I'll be there to help you out till then keep falling thank you thanks
My Calendar I
my-calendar-i
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**. A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.). The event can be represented as a pair of integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`. Implement the `MyCalendar` class: * `MyCalendar()` Initializes the calendar object. * `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar. **Example 1:** **Input** \[ "MyCalendar ", "book ", "book ", "book "\] \[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\] **Output** \[null, true, false, true\] **Explanation** MyCalendar myCalendar = new MyCalendar(); myCalendar.book(10, 20); // return True myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event. myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20. **Constraints:** * `0 <= start < end <= 109` * At most `1000` calls will be made to `book`.
Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added.
Design,Segment Tree,Ordered Set
Medium
731,732
714
hello everyone our today's problem is a deep problem so the problem is uh is a famous one so this is a this is similar to best time to buy and sell stocks too so if you have solved that it is well and good if you have not uh we will see uh we will understand this problem in this video so let me tell you how we will uh go forward so first of all we will understand the problem then we will see a recursive solution and then we will try to convert that recursive into DP solution and in the last we will see the code so uh what the problem is saying you are given an array prices where prices of I is the price of a given stock on the I3 so for a particular stock prices are like this like it is going like it is one on the first day then it is going high three on the second day so like this the prices are fluctuating right and another uh fee variable is given that is nothing but a transaction fee uh what transaction means is like you if you have uh if you buy something and then you have sell something so that is called one transaction so for that you need to give this amount of money every time for every transaction so you have to find the maximum profit you can achieve so in this case uh I bought at a one like as in price one and then I am selling it in price eight so that is profit of seven and uh I have to do I have to give transaction fee so 7 minus two that is 5 that I can we I will be getting then I'm buying in four and selling in nine that is uh that is profit of five and but I have to give transaction fee so again 5 minus two so that is three so five plus three eight is the profit that we are getting so I am returning it so uh let's see how we can approach this problem so in the problem they are saying we have to uh return the maximum profit so uh I have told in the previous uh previous DP problem also when you are when uh whenever in the problem they are seeing or all the possible like they are seeing two explore all the possibilities like they are saying find like give uh all of the paths right if they're saying uh find maximum of something minimum of something so in these kind of problems you will like generally you use a recursion so this is a like kind of trick so uh how we will uh see the recursion let's see that so uh recursive is what you are see you are trying to focus on all the possible solutions or all the uh possibilities rather so uh for exploring all the possibilities and out of which you will give maximum so you need to first see or what are all the possibilities so uh in the problem itself they are saying you can either Buy or either you can sell something sell the stocks right so um buying is what like if I'm on this device either you can buy it either you can sell on a particular day let's say this is the time of buying like you are saying uh like if you are if I'm on this index so like to sell like before selling you need to buy something so if you are on zeroth index you cannot sell first note to buy so what are possibilities I can see here like this is the zeros index first day either I can buy it like if I want to buy and I can say or I can say I don't want to buy on this day I will buy on any other day so either you can buy or you can skip this day so these are the two possibilities at the time of buying so at the time of selling also the same thing like if I bought this on in price one and I come to this so you have buy now and now you have to sell so these are the states two states buy and sell so if you have not buy you will buy I will go to this and if I buy then you will go to sell so in cell uh you are like if I'm here so what two possibilities you can see like either I can sell it in price three so I will get profit of two like I have to give transaction fee but that is that it will that we will do later so uh either I can uh sell it here or uh either I can skip this like I can go and I will sell it here so again two possibilities I will sell or I will not attach up to me I will escape and sell on any other day so these four possibilities is what I am seeing so how this function will be looking this recursive function uh index we will pass and with this I will pass this by is what this buy will have like two values like if this is a time of buying I will indicate that with one if there is a time of selling I will indicate that with 0. because like at particular index you need to know already like what I need to do on this index because either you will buy it either you will be selling so you need to tell explicitly so if this is the like this is starting of the function so what I will pass from the main function zero syntax because uh you will start from first day so this is a day one you cannot sell because you have not bought any or any so you have to pass one by one is what you will be buying on day one right so this is what uh like this is how the recursive function will look like and what will the time complexity for this also the time complexity will be order of uh 2N by 2 power n because you are exploring two possibilities for every index and what we get is space complexity that will be order of n y out of n for uh a recursive stack space so this is a Time complexity for recursive one so let's see uh how we can convert this recursive solution to our memorization solution so uh before seeing that uh let's understand why uh memolization will work right so uh so I am telling you this uh this recursive solution uh like this will not get accepted because the time complexity is very high so I need to reduce this so let's see where I can reduce this in memorization so this is order of 2 power n y 2 power and power 2 power of n because every time like for every index you are asking I can buy or I cannot buy like I can buy or I can sell that is like these two possibilities here oh you want you are seeing every time like for every index like if this is the kind of buying then you are asking uh either by or not buy if this is selling either sell or not sell so these two possibilities like not by itself like this two one that I am talking about so uh this 2 power n is actually like you are like when you will be seeing uh like if you draw recursive tree so in that you will be seeing like you are actually solving the already problem solving again and again like for example if you don't buy here you will buy here like right and if you buy here let's suppose so you can uh pick what I mean is uh in this you are solving the already solid already solved problems again and again so that I that's why it is getting like High Time complexity so how you can solve it solve that we will use a deeper table so in repeatable what we will doing we will like uh whatever the size of TP table that is your states that are keep changing so that is nothing but your index and buy so index what is the limit for that is n like the size of index like index will index can go from 0 to n so N I will pass so n into what into two because by state can be zero or can be one so according to these two changing parameters I will make my DP table and when I will make multiple table so this will be like almost similar to recursive but before solving any sub problem I will ask if this problem is already solved so that I need not to solve it again so in that way I will decrease my time complexity so uh this will decrease to n cross at 2 y increased 2 because uh this DP of size that only like for this these many calls only I will be solving so uh like code I will be showing on do not get uh right so uh this is uh like next we will be seeing tabulation so tabulation is what uh like for this time complexity is okay for memorization but for space complexity this will be uh order of because you are using this uh repeatable and plus you will be uh using that respect space right so we can actually remove this stack space how uh if we use Evolution so in tabulation what you will be seeing like uh this is the top down approach and from tabulation we will use bottom up approach so in what you will be doing uh we will make the TP table first and in DP table um we will fill the values with already solved problem with base cases sorry so what will the what was the base case in recursive solution if you reach to the last index you cannot book any profit you cannot uh you cannot buy or sell something so what will be what we will do uh like we will make the repeatable for uh size n plus 1 cross it 2 by n plus 1 because the base case was if you are on last index you cannot buy or sell so the TP the size of debutable will be uh n plus 1 cross it two and uh with the base case with a base like uh first of all you will be filling the base cases and after that you will start the traversal from n minus 1 to 0. and the buy will be the same like zero to one right so let's like so in that uh the time complexity will be like same order of n cross it 2 but the space complexity uh that will be only n cross it two uh that uh like in this uh we are not using this that stag space again so that will be uh not that will be not in this case so we are getting the team benefit in this space complexity so I hope you have understood this let's see the code so this is your memorization solution let's see this so what I'm saying is uh like uh initially we'll pass uh this function with like this is a zeroth index then this is the binary State like because uh at the index 0 you can only buy so what I what you are doing is uh like if this is like this is the base case so if you are on the last index you cannot book any profit so return 0 and if you have solved already the problem just return that I don't need to solve it again and if this like if this is a time of buying or selling uh check that first if there's a time of buying either I can buy so minus price of index y minus price of index because at the time of buying you need to give the money so money will be a negative and then you are saying give to give a next index and I am passing 0 by 0 because uh you have buy now and now you will be selling so selling we are indicating with zero and buying with one so that's why I'm passing 0 here and uh this is when you buy or I have the another possibility I don't want to buy so in that case go to next index with the same one why one because you will be buying on next index also because you have not uh by this time another possibility is what this is the time of selling so either you can sell so I when I will be selling this so I will be getting this price summoned index in the uh positive and uh with this I will be subtracting the fee value because I'm uh done with the one transaction one by plus one cell so at the time of selling that will be your uh transaction a complete transaction so subtract this fee and like this is when you are selling and if you don't want to sell so in that case just go to uh next index with this same cell indication solution would look like so first of all make this BP table and I'm initializing the values with zero by with zero because uh in the base case we have seen uh when the index is the last one so at a time you cannot book any profit so that is zero so that's why 0. and I'm making it with I'm making this DP of size n plus one by n plus one because uh I need to fill the value with base case so that is uh n so for considering N I have to make it n Plus 1. so whatever we have done before like we are like uh we are uh we have to store the value for n right we have stored the value for n like this is the one this is zero we have stored the value for n and now I can check for Value values like I will go from right to left y right to left because if like this is your base case so with this I can solve this n minus 1 State how because at like every time like if you are at particular index you need index plus 1 like the next values so forget like if you are every time you are utilizing the next values so for that you have to go from right to left so if you have solved this like this is a this is filled with base case so when you are on this you can actually get help from next state and you can solve your problem that's that is how so just go from index n minus 1 to 0 and buys that again one to zero and do the same thing and in the last your answer will be stored at GPU DPF 0 comma one so zero is what like the first day like what you've done here like zero syntax and fun and one is what buy so that same thing we are doing here also so I hope you have understood uh this problem if you have understood please like this video and if you have any doubt you can ask that in comments and for those who are new to this so I make video solutions for DSA problems wherein I explain similar to this like intuition and approaches uh time cons time complicity space complexity and code as well uh I explain so you can subscribe if you like my explanations thank you foreign
Best Time to Buy and Sell Stock with Transaction Fee
best-time-to-buy-and-sell-stock-with-transaction-fee
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee. Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. **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,3,2,8,4,9\], fee = 2 **Output:** 8 **Explanation:** The maximum profit can be achieved by: - Buying at prices\[0\] = 1 - Selling at prices\[3\] = 8 - Buying at prices\[4\] = 4 - Selling at prices\[5\] = 9 The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. **Example 2:** **Input:** prices = \[1,3,7,5,10,3\], fee = 3 **Output:** 6 **Constraints:** * `1 <= prices.length <= 5 * 104` * `1 <= prices[i] < 5 * 104` * `0 <= fee < 5 * 104`
Consider the first K stock prices. At the end, the only legal states are that you don't own a share of stock, or that you do. Calculate the most profit you could have under each of these two cases.
Array,Dynamic Programming,Greedy
Medium
122
403
Ajay told that if in this video we will see the solution to the problem, a question says that we will get it in ascending order, friends, it is nourished, that means there is a receiver, there are some stones kept in it at some places and let us assume that those stones If there is a table, then the positions of those stones have been told in this city that in which positions one can get Arafat on, then it was said that to approach on Sunday with the walnut, we will have to fly off course on it, oh I now It is due to some condition that this post is above them, in the beginning the number is above zero and from there it is only an example that if it is good then why did someone stone it, then which jump will be looted from there, if there are three employed from there. When he jumped last, he would have 3 options that he can play my songs, when he can take them and K +, the current +, the current +, the current tone of the mind is fine, so if he is last then he reaches above them, he crossed the river in the other wise. If he is not able to bear it, then just tell him whether From can cross the river or not. Do you understand the place of your native village? Okay, look, the stones are made of small pieces, so I will show the stones in such a way that there are plans on which a first If you want to listen to someone on the second position, then here is the voter. Who is on the third spot and why is he on top of 5462? He is not on the top of the first place. A tunnel is tight related to money. Then you had to tell that if then he cleans it by doing it from here and then If he clears it with 200 questions then has he crossed it till the time of telling this it is good ok let's see so first of all that tone number is above zero and he has an option It happens that if you jump one, then it will immediately go from here and the same person will go, then why is the number closed, tips, reaching number one, introduction of how many people have joined, I should know when I reached by taking birth of one, taking birth, I reached by taking birth of one, now its There will be a pass option, the crowd of tattoos in the forest can make Zero shine, Zero is this note, the alien option is ok, now let's go back to this place from here, so we reached here by taking one step at a time, which is a plus 2 or 2 from here onwards. The tradition is right, if it had been attached completely then it would have gone into the water. If there was a jam of two in it, the cut that was made from here reaches till this photo. After washing it with the net, when I felt that it has come here, then I was at three. When he has reached this level, he should know, okay, what are the options available, then how many births will this plant have, or has it jammed two, will it apply to one step, what will be two steps and is giving birth to three? If I am then it is this - Banel's and Kepler's time, there are 3 options. this - Banel's and Kepler's time, there are 3 options. Now by placing the scientist's bowl directly from here, he will go into the water, then by jumping from this, he could go to the file, so by jumping from this, he can go to the roof. From both the options, I He will cheat you and go to the face by jumping and then it could be that 2.1 is here, if he and then it could be that 2.1 is here, if he and then it could be that 2.1 is here, if he goes to the teachers who have exams then he will have a lot of options, he will have one in his purse, I want one when I come over the pipe, tell me that from 5 Which is frozen, which job is alert from five, so from here I can go to the factory, friends, teacher, so if I go to the face late, then I am right backward, I am deciding that if I go to the face, then two While taking an oath, the water reaches the village and because if you apply two yards then the planets will be available nearby in the next options. To jump from 5, one, two and three, if the last jump was done, then Kepler is the same. They have three options, which option can they jump even from the number two husband, they give birth to a team of fear from Mehri, they can only go to the teachers when they reach, they can go till the pick, alleging 23, I will reach, just give you a jump of three. If I am reaching while putting, then officer fix will have the option of birth of two, birth of 3 and jump of four, how will it be tight that this jump has been put, that is the question of which - after becoming, these three options question of which - after becoming, these three options question of which - after becoming, these three options will remain tight for you. Choubey has 225 questions that now which job will he take one or will he take both the spirits and will have to do something else, it may be that the way from here is through fight and through whom will the way come, we will have to discover both the posts, it is tight. I come on top of the pipe and look from five to see what kind of crowd is there, increase it completely that today we have a problem alarm, so when I stand on the face, I should have this information, which of these people from here Jump Aloud is that if I get a six frozen on the track, then when I come on six, I should know the information which pimples have become due to this. Okay, for those who love you, I want an information brother and then who are their guests from there- Which jump is who are their guests from there- Which jump is who are their guests from there- Which jump is allowed, this information is required, preserve it in the information behind, see that it has been taken and only the songs are there, put the lions, put them, put CO, put the points 181 subscribe to, okay, now close it in front of zero. Diya became in front of the head meaning that brother, on the birth of one, what information and things are going to be done by me at this time, but this is stopped in front of the youth, I would like to know which one is simple than closed, okay, which job was in front of you. Life S A Which Nutmeg Powder Add So Let's Start We Have to Revolt and That Contact Ban Per Now I am on top of the forest Next I am on the top of the forest How much wealth is there from here So you should have updated earlier How do I update the tractor? First of all, I will get a zero phone. How much is the double roll from zero? From 120, if you jump one time, where will you reach? On top of one, reach how much of these phrases. You reached by jumping one. Where have you reached? If you reach at one point then it is good. If you take one step at one point then update one of your options. If the time is perfect then the update option is soft. So I said, brother, if you want to reach at one point, then option songs 2018 from here, so hey friends. I did not use to write in the option, I said that there will be two Jabalpur, then the mood is off, okay, next is on Taiwan, that is on them, now I have the information that from the off, there will be absolutely powder and two traditions in this dynasty, this I Took a step and I reached above two, so I don't get tagged. I would do nothing except go into a cup of water. If I took two, I would jump on the sovereignty of martyrs. Then I would reach above and unite the three layers. What time did it take to reach two? Kadam, you go and update the three questions. Come, I will give you. When you reached while applying, you will have these 3 options for 1213, then you will be able to jump by this much. Oh, a good team has come above xxxx3, this was the option placed in front of you, let's talk now. Questions are placed in front of Sakti, it simply means that I will reach number three, I am fine with you, then if I do all these options next 9, one by one, the jump of one should reach number four continuously, do you have any advantage? It won't happen when I reach 5 in a row. Take two steps forward. Hello friends, keep it on 5. Okay, please update its options. Okay, I got a job of 303. When I reach 6, I am giving birth to 3. I am looking forward to sleeping on the roof above 6. If it does, then update it and come, this is minus one and plus one Yogesh ji, now let's go, there are options in front of Next 525, which means it can be reached only till it discovers all the options, if we jump to one, then we would have reached. Above and does six digits, let's put Pancho exactly, then update the options for the bike, I will have options, just one, two yards of this gang, we jump here a story 018, so hey friends, if we do n't write it in advance It is written that add it to the loot check, it is written first, do it again, okay, next second option, A 25 to two steps, 512, when we reached along with above, there is water there, nothing else to do, 5 to three, when we reached. They put a camp of 3 on their lips by putting what time it is, now they reached here chanting options two-three, that ad will have reached here chanting options two-three, that ad will have reached here chanting options two-three, that ad will have option three, just immediately minus one and Kepler 153 option, I discovered all three. If you have a teacher's neck, then put four options in front of six. Do this. Six plus one is 72. There is water, nothing to do. Six plus 268 is stomach. Sanjeet adjusts at 8:00. is stomach. Sanjeet adjusts at 8:00. is stomach. Sanjeet adjusts at 8:00. She is looking amazing. If both of them work then there is this. Update the options and come back because when you put it in the right place, the key is verito - man's end and a put it in the right place, the key is verito - man's end and a put it in the right place, the key is verito - man's end and a plus is closed, how to present is already the president, so the bus has to be added, correct, you know what I am going to do in this chapter because here that To dobara add nahari dobara add new assembly for adventure fest apne sare hai shetty hai ki unique jumps to rahta hai let's see plus 399 do nothing will do village 60 also does that track training all options to and done next hua hai Hey it's an option, we have recharge you plus one does not reduce plus two 10 water or 11th water, you will get part plus 4 12th water, it is used by friends, it is felt in the house that you will have the power of four in the house from here, I will think about it again Hussain. All are updated and come back. If you take four steps and reach 345, you will have options, so the loot is ok, so I have taken this after breaking all the options. Now in my turn, I have taken the initiative. 26 2012 There are options in front, which means it was possible to reach them. 3rd's bus will reach 15th 4th's bus Saurabh Rochak 15th is water 16th is water If I had jumped from there to 5th, I would have reached there At seventeenth reached above seventeenth Return is rupam here Possible toe cross were reverse Reverse reached home last So above them it is possible, I will give an example in which if it is not possible, then it is for tomorrow, then it will be heavy 1234 807, these stones will remain, everywhere else there will be water and if you recognize 11:00 then recognize 11:00 then recognize 11:00 then you cross your life. If you haven't been able to do otherwise, then let's now, in the same way as before, I have taken the fat in front of the heroes and will do it in front of you in the same way, it will be set up in front of you, in front of C, in front of the heroes 1234, and in front of a lesson, that There will be more MP3 available in front of nine also, breaking this, today we started looting with 11:00, breaking this, today we started looting with 11:00, breaking this, today we started looting with 11:00, so now in front of 020, keep in mind that the first thing is that we are looted, okay, let's incarnate from zero. This kajal should be that ace when you come, where have you reached? Update one option above them. I am sequence that if there are two options above them, then apply the birth of one immediately. If you reach there, swear that you will reach above 3, apply two immediately. Reached and had two pack toe exits, friends, update it and come back and if you have asked where you will go on two sects three, then okay, then update the option for this and then edit it, then come while jamming, then ke - Kepler of the mind has come while jamming, then ke - Kepler of the mind has become an automatic option, I have seen both the options and now you too have two options in front of the planets, so if you put a cup on it, you used to reach this earth by taking one step in the gold which does. Which Jabalpur will be next to the right, it is 1.5, Which Jabalpur will be next to the right, it is 1.5, Which Jabalpur will be next to the right, it is 1.5, when it comes to one, then it is 0.22, when it comes to one, then it is 0.22, when it comes to one, then it is 0.22, we do not add one seal, but already overturned, we will not add again, there is another option, you made a jam of two and reached four, also on four. Taking two steps, I placed the stone in the front of 84 and said - 10 placed the stone in the front of 84 and said - 10 placed the stone in the front of 84 and said - 10 porn 10 back side of 110 is virgin, this was after that, what is the option? I have reached 1.4 in the jump of one, reached 1.4 in the jump of one, reached 1.4 in the jump of one, so I updated the option of four. If 1212 is already there, then take an oath, it reached near and on five, the vote unites, 13 were born, 3 can be made taller, those who were born, six will reach and only the fat respects, if the voter adjusts, then nothing has to be done. Next you have the option of one jump, wife will reach fifth, two steps, 6, chant of drinking water, reach there too, together, reach there too, water, okay, just give so many options, okay, finished, next, now the one in front of the school, settle size is zero. What can I find out at this time, we can reach for some time because if one could be reached, by any means, we would be reaching on the stomach, if we reach with a jump of so much, then we would have reached with a jump, then the birth of If it was there then there should have been some options here, meh that if I can reach here then by taking the birth of ki, then I get its options updated first oh ki planning, meaning I can't reach here, let's move ahead to Norgay or 11 -11-11 If you don't know then let's Norgay or 11 -11-11 If you don't know then let's Norgay or 11 -11-11 If you don't know then let's start the treatment. Let's smell it in the court. What do we have to keep in mind? The way you stand above them and see from there that we can reach the top of the stone, then we should know the options from here. If you want a double role of this much, then do all the options and you can reach this thank you. Go to them at this very time and get updated. How much can you bring and when you can reach to you, then you will have these options, so my stomach is hopeful. I am your boss, you try to break the lock to Leo and before doing this, mother asked me what would be the thing, do you need a help and in this I put it as this is the position of all the stones and myself toe in front of him. Will be the one who notes the options of jump from here is right in front 123 What are the options, he can take oath, have a meeting at 2 o'clock and tell him that let's start, this is the coast and I have this bike, time po 110 teacher vs like this You don't need repeat value, I am a scientist, so the first task is to go everywhere and come to the set room. The first task for a month is to add these stones, I will take Iceland stones, three plus one, put these stones in the map and Then I got a new cassette that the medical friends have set and placed a new one in front of it on the set. Well, now what will I have to do or a map dance to Shyam, what am I doing on map dot in fact map dot Ajay 2010 Whenever we would have cried, write again that from here it is exactly powder. Okay, from here you have got the set and added to it, but what is it made in front of zero, what is set in front of zero. Have put one in it and now we start our work, brother, look at the stones, look at the torch, total length is you plus, you take out the current turn on them is 105. Okay, okay, I thought now in which positions from this stone. If the current can be reached above, then the hair lying in front of them will have to be removed or okay, someone takes out that like this to go in tears that the options are a map dot net, the current turns on, okay, I took out the set. Now what should I do, put a loop on it that I should discover all the options which will be the president inside the set, I should discover all the questions and enter is the enter option, there will be a pimple, I will remember when is it okay, then in these facts. If it should be written like this, then it is optional, I jump, I am, and with this, we have taken out the paint chops one by one. Here, let us see that if I jump by this much, then which stone will it reach on top of the current stone. From I have made a jump and reached then the value of their reach is going to be broken that the position above which you reached should be nourished and maintained and got it done. Now if above that position then it exists that this map did not contain content. If the Council is maintaining that position, that is, if the stone is kept there, then go and update its options and come back, then see the map posted, my friend, or again please get a map to know how the position is. To add that till date you have added jump when the crime of minus one is to loot on penderm plus that it is just vote on the phone, keep in mind that jump - 100 has been added to that jump - 100 has been added to that jump - 100 has been added to 275, take care, it is good, okay and before that I would have applied a little oil. If I am then you are taking out the portion, if it is the last position, if the position is the last position, the scientific position is the last question, then you have reached above your destination and the return from is okay force, if you have reached the plus portion co, then from here. You will do it through otherwise after checking everything, in the end I have paused the tension, take a look at what all the devices do, it is time and light, I have added all the stones to it, I have come in front of the hare, I have set it. And in the set in front of 1000, I have got one added to it. Okay, so people will rotate it over the stones, take them out one by one, and from there we will see how much the brother is worth. They will do porn with him. So I took out that asset as simple as that and ignored that and then jump that much and see which portion you are reaching, if that position is the destination then returns through. If there is a stone placed on that portion then go. After updating their options, come back tight. If there is no stone placed there, then there is nothing to be done. If A is flying, then it is tight. Let's try one more round. Before doing so, I will preserve the code once. There is some mistake in the torrent from the account, we got the answer wrong, let's see that we got it from the side everywhere, I started it from the sunlight, when these people wanted to make us run from the houses, that building will come from every answer poll, Loot Navle Tried to submit now Now let me try to explain to you once again what I have done, this is the reason why this pick is above the gold, you will see the options written there that from here I am so much of this color is red, so when I emphasize all those I do this and if people jump from there, then I am reaching over someone else. By jumping how many, this trick was immediately planted. The option was written on the topic above which I was reaching. While standing on this phone, from here I suddenly It was thought that for that - there will be an option to ask more questions of the mind for that - there will be an option to ask more questions of the mind and while doing this, if you reach the top of A Krishna then you have to return tow. If you are not able to reach the offices by doing this, then you post the last minute Who was correct? Si kali meri karta hoon aapko samaj mein aa ko to samaj mein ko, do come once, do watch. Thank you so much for watching this video. Please subscribe our YouTube channel. Thank you Jhaal.
Frog Jump
frog-jump
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of `stones`' positions (in units) in sorted **ascending order**, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit. If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction. **Example 1:** **Input:** stones = \[0,1,3,5,6,8,12,17\] **Output:** true **Explanation:** The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. **Example 2:** **Input:** stones = \[0,1,2,3,4,8,9,11\] **Output:** false **Explanation:** There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. **Constraints:** * `2 <= stones.length <= 2000` * `0 <= stones[i] <= 231 - 1` * `stones[0] == 0` * `stones` is sorted in a strictly increasing order.
null
Array,Dynamic Programming
Hard
1952,2262
573
hello hi guys welcome back to the new problem squel simulation firstly sub chazi I hope that you guys are doing good uh so basically it has been asked by square and not pretty much but it's actually a good problem like it can give you Devolution of something else but it's something else let's see uh what it is saying that it's saying that we are having a two integer height and width representing the garden of size height cross width so we have a garden as you can see we have a garden of size height cross width we have a Gard cool now next thing it says is uh we have an aray tree where it just says that it contains the coordinate of that tree and we have a squirel which contains the coordinate of that squirel the right side uh and we have an array of nuts where we have let's say n nuts and basically it's a vector of vector where each Vector will contain okay what for that specific nut what is its coordinates now what we have to do is the squirrel can only take at most one knot at one time and can move into four directions and do something else they have to return again remember the squirrel can take at most one nut now return the minium distance for the squirrel to collect all nuts again squirrel have to collect all nuts and put them under the tree if the squirrel have has to connect all nuts and that squirrel can take only one nut at a time so for sure he will have to connect that like collect that nut put that nut on the tree and then go back and go on to the next nut then C that nut and then put it back to a tree so when the squirrel can only pick one nut at a time so he will go to the nut collect that nut go back to the tree put that nut here then squirrel will be at the tree so he will go to other nut collect that nut come back put that to a tree and then again go through some other nut collect that nut come back and put that tree so you will see that how it will look like for sure initially if I have a squirrel I have a tree I know that the squirrel has to go to some nut it has to go to some nut in the beginning for sure he will go to some n in the beginning let's say it is a nut one it's a nut two it's a nut three so either it can go to nut one nut two or nut three it has to go to one nut and for the and as soon as he goes to nut one so for sure uh he will collect that nut which means Aran so when we are saying that we have to go from the squirrel to the nut so are we saying that we will find the shortest path between squirrel and the nut it you might say that you are fining shortest path but you will see it's just a simple grid and the distance is just the simple distance of like simple difference of their coordinates there is no obstacles as such so you don't need to use BFS to find the shortest path you can just simply do okay if its coordinates are X1 y1 its coordinate are s SX comma s y so the distance between a square and a nut will be nothing but SX - X1 which is will be nothing but SX - X1 which is will be nothing but SX - X1 which is absolute value for sure and also absolute value of Sy Yus y1 so that will be the distance so we don't need BFS or stuff just to find the distance so because we don't have any obstacles this tree also is not an obstacle for us I can go past the tree to actually reach any of the nuts so for sure this distance thing find out it we can do without VFS without any graph usage you might think okay for shortest distance I want the shortest distance from a nut to a squirrel or from squirrel to a tree from nut to a tree so maybe I'm just using a BFS no because it's a simple distance I can just simply do a sub like find the distance by simply doing a coordinate subtraction now let's say when we have found the distance so one thing we for sure know that from the square I can choose any nut as the beginning nut and I can go to N1 maybe I choose to go to N2 maybe I choose to go to N3 let's for now I choose to go to N1 then from if I go from squirel to N1 then from N1 I have to go to a tree so that's one thing for all other nuts for sure I will be starting from the tree itself going to a nut and collect that nut coming back to a tree so for all other nuts the distance will be actually basically you have to travel this distance so it will be nothing but from nut to a tree to a nut which is two into distance between nut and a tree distance between nut and tree it will be for nut two and the same will be for and the same two into distance of nut three comma three same will be for nut three for this nut one the only thing will be actually happening is that I will have distance from this nut one to squel and then also the distance from this nut one to threee this is the only thing rather than 2 into the distance between nut and tree I just use a distance between nut and squirrel because first time squirrel can be at any positions it's not specific that it will be at the nut itself okay so ultimately my final answer would look something like okay it will be nothing but 2 into or I can just easily write this thing which is D into N1 s which means from nut one to squel or basically you can say Square n one everything is same distance between nut 1 and three and then two into distance between nut I can say distance between nut 2 and three plus same 2 into distance between nut 3 and three now for sure uh here I just wrote nut one but as a told earlier also I have to try for every first thing which means I have to try for nut one I have to try for I have try the same thing for nut two same thing for nut three so in this uh if you have not known then there is one thing called as summation and subtraction which means let's say if I want to find a b c d if let's say I want to find the answer as 2 a 2 into a + b + C plus d but a 2 into a + b + C plus d but a 2 into a + b + C plus d but let's say I don't want to include one specific B and instead I want to include let's say some X instead of B and I have try to replace everyone let's say I will try to replace a I'll try to replace B I'll try to replace C so one way is take its summation one like I'm just showing you one way one of the ways which we use actually in programming in compettive programming one way is just to take the sum which is this a plus b plus C plus d and then you know that you have to find like ultimately my task is to find replace every like Take 2 into a plus b + x + 2 into C + 2 into D plus b + x + 2 into C + 2 into D plus b + x + 2 into C + 2 into D ultimately my task is this so I'm at the I index I know that I have to replace this up so one way is that you just go and try to find for everyone which means go and find the sum entire sum replace this which is O of n sare but we like we don't want it so other ways that you know it sum entire sum which is two in like entire sum which is which like you can pre-compute so I know it is 2 into a can pre-compute so I know it is 2 into a can pre-compute so I know it is 2 into a plus b plus C plus d which is actually nothing but 2 into a + 2 into b + 2 into nothing but 2 into a + 2 into b + 2 into nothing but 2 into a + 2 into b + 2 into C + 2 into D I know I'm at the I index C + 2 into D I know I'm at the I index C + 2 into D I know I'm at the I index so what I will do is I'll just subtract the value of the I index which is V of I because I know it's actually a b and then I know for that corresponding vfi I just have to add IX so I can move on to every I and I can just I know it's fixed I can just keep subtracting this value V of I and I can just find on Computing what is the distance because I want this value and this value needs to be minimum so I can just compute okay at which index I this thing is minimum so it is one way the same way to represent this is the same way exactly same way to just represent this is no it is exactly it is very fine and usually we use this only but you will see that you have to WR like you have to first take the sum and then on the entire index and stuff rather you can just use and do it in one pass because now the interview might ask you okay you have reduced the time to O of n itself which means o of number of nuts but you will see that it's a two PA algorithm which means first you will go and find the sum and then again you will go and find for every I what is the value which is the result which we saw which is 2 into that entire sum minus V of I plus X you'll go and find for every I so it's a two pass like one pass for some other pass for actually finding that minimum value rather if you want to do it in one pass what we can do is we know the this is a sum right we can write the same stuff as 2 into D of 2 into same 2 into D of n1a t plus d of N2 comma t plus d of N3 comma T now you will see what has been counted N1 comma T has been counted again so I have to subtract this N1 comma T now AR in what is N1 like you have to use N2 N3 also meanwhile hold on and then for sure uh I will have to add this N1 comma S Plus D of N1 comma s now if I have this one equation and it is kind of same equation which we saw earlier also if I this one equation I know that this is nothing but the total obviously you can say 2 into total but you will have to simulate this so rather writing like this because I want to just apply one operation on this so I just write the same stuff as minus D into n1a T minus D into N1 s now I know this is fixed I want the entire thing to be as minimum as possible so rather maximize because you know that it is N1 I know it is fixed rather maximize this right stuff which is distance between N1 and T which means I can just while I'm iterating and finding this total sum itself I just keep track on side by side what is this maximum difference can be now this maximum difference is just this difference what it can be which means distance from that nut to tree and then that specific nut to squirrel ultimately in the end I will have this particular maximum difference I will have this total I'll just say okay my 2 into total minus my maximum difference is actually my minimum result and that will be my answer in just one pass algorithm is still o ofn and last time was it was also o ofn it's just that earlier it was two pass now it is actually one pass and that's how you can simply get this solved cool let's quickly see the code itself it's pretty same as what we saw so firstly um as you saw that we need to have a distance so I can just take and say uh just go and find the distance between two vectors because ultimately for us uh our entire thing is just finding those Manhattan distance so I'll just say that abs of a 0 minus B 0 and the same thing for y coordinate which is ABS of a 1 uh minus B1 now I have found the Manhattan distance I can just go and find my answer I know I want the minimum answer so I just initialize with int Max I know I have to go and find the maximum difference I'll go and initialize that with int Min and then ultimately I also want a total so as I showed you I want a total also I just initialize with that now I have to go on to all my nuts because that is for every nut I have to go and find the distance I know that my total will actually nothing but the distance from that nut to a tree because I just ultimately know that ultimately in my final answer what I will do is I will just multiply do a two into total and then subtract my maximum diff I just need to do this so I just know that my maximum diff will actually become the maximum of so far what whats is the maximum diff and also just go and see that specific for that from that nut to tree minus the distance from that n to square SQ u i r e l so that will be our distance and this should be our answer let's quickly see and run uh this has Ty so that thank byebye
Squirrel Simulation
squirrel-simulation
You are given two integers `height` and `width` representing a garden of size `height x width`. You are also given: * an array `tree` where `tree = [treer, treec]` is the position of the tree in the garden, * an array `squirrel` where `squirrel = [squirrelr, squirrelc]` is the position of the squirrel in the garden, * and an array `nuts` where `nuts[i] = [nutir, nutic]` is the position of the `ith` nut in the garden. The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell. Return _the **minimal distance** for the squirrel to collect all the nuts and put them under the tree one by one_. The **distance** is the number of moves. **Example 1:** **Input:** height = 5, width = 7, tree = \[2,2\], squirrel = \[4,4\], nuts = \[\[3,0\], \[2,5\]\] **Output:** 12 **Explanation:** The squirrel should go to the nut at \[2, 5\] first to achieve a minimal distance. **Example 2:** **Input:** height = 1, width = 3, tree = \[0,1\], squirrel = \[0,0\], nuts = \[\[0,2\]\] **Output:** 3 **Constraints:** * `1 <= height, width <= 100` * `tree.length == 2` * `squirrel.length == 2` * `1 <= nuts.length <= 5000` * `nuts[i].length == 2` * `0 <= treer, squirrelr, nutir <= height` * `0 <= treec, squirrelc, nutic <= width`
Will Brute force solution works here? What will be its complexity? Brute force definitely won't work here. Think of some simple solution. Take some example and make some observations. Will order of nuts traversed by squirrel is important or only first nut traversed by squirrel is important? Are there some paths which squirrel have to cover in any case? If yes, what are they? Did you notice only first nut traversed by squirrel matters? Obviously squirrel will choose first nut which will result in minimum distance.
Array,Math
Medium
null
122
hey guys today we're going to be solving a code question 122 but it's time to buy and sell stock - this is the second and sell stock - this is the second and sell stock - this is the second question in the stock prices problem series the first problem was the same except the only difference between this question and the first question is that in the first question we can only do one transaction at most one transaction meaning we also there's a possibility we don't know any transaction at all if the prices are sorted in a descending order in this problem we can do as many transactions as we like so this is a classic peaks and valleys question meaning we are trying to this search for local minima and local maxima and just some of the differences between them what I mean by that is suppose you have something like this let's say there's 8 here there is 10 here something like this so what we the first local minima that we find is 1 because the prices keep dropping and suppose this was 9 so the first local minima we find is at 1 so what is the for when would we want to sell this it would be at 8 right so that is a local Maxima that is just before the next price drop so this difference will contribute to the max profit now then we will search other less next local minimum which is 3 and then we will sell it at 10 so basically I was just searching for valleys and Peaks this is a valley this is a peak again a valley usually our value has to immediately press follow a peak right and then this is a peak so these differences will contribute to the maximum profit cool with that I think we are ready to code I'll keep this because the because first I will present a solution that is based on this valleys and Peaks concept because that comes naturally to me but one very good observation will lead us to where one very short early elegant solution so I'm going to just keep this around to explain that because that is a much more elegant solution just that it didn't come naturally to me at first I won't know right what came naturally to me first good so let's say if Sogard is basically just an if to see I'm just trying to ensure that the prices array is not empty for people not familiar with Swift this is simply that nothing known as fancy as it looks cool so I'm just really going to be searching of valleys and Peaks because this makes more sense to me that short and shorter solutions will give a max profit variable Nikki and I were able to traverse the price of the rear so while we haven't reached the end of the prices are a let me just insert the return statement so let's search for the like let's search for a value first so we'll don't worry like this looks like we have nested while loop so I basically just going to be iterating the prices array once so it will still be an order n solution so keep traversing it until the prices don't drop so basically we will exit this loop when we find the first price drop and that will give us our new Valley or new local minima now that we have the local minima we will start searching for the local Maxima that will be accomplished so we'll keep the we'll keep searching traversing the array until we see a price I mean we'll keep searching until there is a price drop under the first price drop meaning the next Valley so just before the next valley if we stop that will give us the peak now that we have found our peak and Valley we simply added to the max profit please note that this there is a possibility we have zero profit which would refer to the situation where all the stock prices are given and our descending order of values meaning the stock price never rose so we make and make no profit so we will just return zero max profit in that case yeah so basically we still have to increment this I right okay let's see if it works yay works cool so this is an acceptable solution this looks scary with so many values but what I insure you since we are will only be iterating the prices are a once will only inspect any every value once so it is still an order in solution I promise you have more elegant solution this arises from the fact that if you look at the problem you're only just adding up the positive segments only the segment's where the price is going from a lower value to a larger value literally throughout the array ignore that these are stock prices whatever you're only just adding a positive segments for this solution so what I mean by that is if you look at this array that I gave you initially what a positive segments meaning 1 2 5 is a positive segment we can add that Phi to it is a positive segment we can add 3 to 6 meaning whether in a first value is a low value in the second value is a larger value that is a positive segment 6 to 10 is a positive second we won't add 10 to 4 that is basically what we are doing and if you look at the problem that way it gives us a very easy very clean and neat solution just that it didn't come to me naturally the first time so I didn't present it right away but I'm going to it's such a small solution and such a beautiful solution that I'm just gonna hold it for you once again so if prices dot I is greater than prices i minus one basically if this is a positive for our to initialize match profit if this is a positive segment this definitely goes adds to the maximum profit and yeah that's it guys looks great doesn't it works awesome cool guys this is again an order n solution adding up all positive segments cool good luck guys thanks for watching bye
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,608
hi everyone um welcome back to jk work well actually this is first video i'm trying to making it as kind of nervous uh today we are gonna solve the problem the liquid 16 8 special array with x elements greater than or equal x let's look into the problem is very simple so um you are given an array numbers of non-negative integers non-negative integers non-negative integers numbers is considered special if there exists a number x such that there are exactly x numbers in numbers already that are greater than or equal to x and notice that x does not have to be on elements in numbers all right so uh if it's not a special return minus one if it is special return the value x so here is the example so they mentioned the x doesn't have to be an element in numbers array so here is the example that the x is 2 since the length of the array is 2 and then 2 is less than the elements in numbers so yeah they just pretty much explain it what i just said and here's the second yeah you could understand and then third there are three values is greater than that's why true there's three values that are greater than or equal to three so three and two four are three equal or greater than three so the x yeah must be three how are we gonna solve this problem well we since um the x doesn't have to be an element in numbers um we can kind of define the range of x so let's say uh the mean value could be the main number is true so uh here is his like easier to solve this problem it's better to sort the ra first and then you know the maximum we supposed to look into the value it could be the length of the array or the maximum number of the elements in the numbers so um here's number and the maximum value if we sort the array here so minimum could be number gel the first like let's say um if you start it the first one let me use the example three if we thought it and then uh through it the array would become like already become like this and uh minimum we should start and a candidate of that x value should be the zero but i mean zero you can't inescapable actually because unless the length of the numbers is zero which is constraints you look into the minimum number of the length of numbers is one so um number is not the case and the max we don't have to check all of the mags so next could be the either maximum element of maximum element in the numbers or the length of the numbers so um here is the example like let's say like whatever value you have the length is five so then what is the maximum value to be the x is five obviously right so um we define the mean and a max value that indicates the range of x so here's the x we start with the mean and then we needed some index cursor i would say idx this is index point and simply we wild so the x is less or equal to the max then we'll move and if the x is the length of array minus the index it means we find the x so we turn the x and uh otherwise uh we have to skip like the same like number like what if um there's a good they say zero this is minimum so we already look into this two so um the first the mean is the x we check this and then we get ready we get rid of the zero from the ra then less though our age three four and four so um we move the index point to the three so index should be less than the length of array and the numbers and x is equal or less than x then we increase the index so the first index is zero and move to the one and a move again so now here so let's say whatever next x is 2 and then we have like this so we can calculate here using the index so we match it if not case we increase the x let's check another one so we couldn't find the x simply return the minus one so here is code and we can run the code there we go yay here's the solution for this uh problem and um it's a faster um but this is so random so you don't have to really worry about here and i want to just mention about the time complexity since um we don't really use any extra space so um space complexity is bigger one but um time complexity uh you can look into here the maximum is you know we look into n to max and here is the length of the array so um so either one i don't mean it means like uh the smaller value from here or the n and the max is numbers n minus one which is the max number of array or the length of the array so here is time complex that is o n but um we use a third method to sort the array first so um the average we could say the n log n time complexity plus n so it could be the analog and time complexity if you have any question about this um please leave the comment down below and i will answer and see you next time
Special Array With X Elements Greater Than or Equal X
calculate-salaries
You are given an array `nums` of non-negative integers. `nums` is considered **special** if there exists a number `x` such that there are **exactly** `x` numbers in `nums` that are **greater than or equal to** `x`. Notice that `x` **does not** have to be an element in `nums`. Return `x` _if the array is **special**, otherwise, return_ `-1`. It can be proven that if `nums` is special, the value for `x` is **unique**. **Example 1:** **Input:** nums = \[3,5\] **Output:** 2 **Explanation:** There are 2 values (3 and 5) that are greater than or equal to 2. **Example 2:** **Input:** nums = \[0,0\] **Output:** -1 **Explanation:** No numbers fit the criteria for x. If x = 0, there should be 0 numbers >= x, but there are 2. If x = 1, there should be 1 number >= x, but there are 0. If x = 2, there should be 2 numbers >= x, but there are 0. x cannot be greater since there are only 2 numbers in nums. **Example 3:** **Input:** nums = \[0,4,3,0,4\] **Output:** 3 **Explanation:** There are 3 values that are greater than or equal to 3. **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 1000`
null
Database
Medium
null
808
Hello gas welcome back to my channel and today's hit and challenge soup servings so what to do in this question basically I have given you two words A and B ok and I have given you N M L of soup in both and what you You can basically do one by one operation from A, if you keep giving operations then what can you do one operation, from here you took out 100 and from here you took out zero and what can you do another operation, you took out 75 from here. From 25 I had written, what can I do in the third operation, you can take out 50 from here and what can you do in the fourth operation, take out 25 from here, take out 75 from here, okay, so I have to keep going, if I want to keep going, then every You can perform the operation every time by doing it. It is okay. Suppose if you perform this third operation then it is 5050, then this 25 is taken out from here, 75 is taken out from here. What can I do? Is it okay to perform this operation? 75 is taken out from here, 25 is taken out from here, then this is What happened from here, zero became zero? Okay, so you have to do the operation like this and you have to tell what is the probability of getting an empty if BMC is not done. Okay, you have to tell this plus what you have to tell plus you have to tell that both. What are the chances of the probability of being empty together? Okay, half of the chances together. Okay, so this is a bit of conjuring, so if you remove half of it means that here, if you have to remove this, then I Okay, this is what is meant in this question, I will explain the factor to you. Okay, so the question is written like this, brother, you have A and B are okay and you remove either hundred from A and some from B. Don't take out either 75 from M, take out 25 from B, take out 50 from B, take out 25 from M, take out 75 from B, now you will keep doing this, okay and one by one. If the probability of reaching zero is zero, how will you do it? And you have to reach it. Okay, and both of them can take both. The probability of both is half- can take both. The probability of both is half- half. So you have to tell me what is the probability of you reaching six. Okay, so what will you do? What will you do? In this question, you leave the supposition probability first find out the number and what will be its answer, till now the total of both is equal, what is there in probability, only one thing will come, if from here I know what is the probability, then it is half. I will cut it in half and here my life is half so I will cut it in half ok and when I reach here what will I return 1.0 1.0 1.0 and there is another story too when I reach here what will I return then zero ok so this is mine The probability will be okay, so this is the thing we have to do in this, sorry, so what it is saying is basically half of it, what are the half of its chances, what are the half of the chances of this happening, so what does it mean, I suppose I am telling you that N = I am telling you that N = I am telling you that N = What are the chances of reaching 6. N = What are the chances of reaching 6. N = What are the chances of reaching 6. N = How many bases are there to reach 6. Find out. Okay, so what you do is send the total and come out. Okay, after sending the total, how far do they come out. You identify here the chances of reaching here and here. But you would have got total base to reach here, ok till then our tomorrow would have been relieved and by recognizing this here and here also we did not open it and if you would have got total base to reach here, then due to our delay you could have reached here. If we could reach at here and at this point c and n = and equal then the probability of reaching at 6 would be because what would we have done here whenever as soon as we were reaching at n = 6 whenever as soon as we were reaching at n = 6 whenever as soon as we were reaching at n = 6 we would have returned one then this would have been 8/20 is calculated like this, we would have returned one then this would have been 8/20 is calculated like this, we would have returned one then this would have been 8/20 is calculated like this, now let's assume, this is also to say that N = 7, how much is it? this is also to say that N = 7, how much is it? this is also to say that N = 7, how much is it? Okay, so what you do is add another base condition here and what was the total, what will you do, give 14 times. I want him to say like this that if I don't understand here then we will return zero because we do n't want this thing to happen to us, if we want to count it then we will make it point five, okay and we have done it okay and This is if you run it, okay, what will happen, basically okay, what will it convert into if you say it, then it will convert itself, its answer will come, this is okay, something like this will come, you will be in the forest, okay I have understood below and this nonsense has been done, it is ok, we will go till 48.
Soup Servings
number-of-matching-subsequences
There are two types of soup: **type A** and **type B**. Initially, we have `n` ml of each type of soup. There are four kinds of operations: 1. Serve `100` ml of **soup A** and `0` ml of **soup B**, 2. Serve `75` ml of **soup A** and `25` ml of **soup B**, 3. Serve `50` ml of **soup A** and `50` ml of **soup B**, and 4. Serve `25` ml of **soup A** and `75` ml of **soup B**. When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability `0.25`. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup. **Note** that we do not have an operation where all `100` ml's of **soup B** are used first. Return _the probability that **soup A** will be empty first, plus half the probability that **A** and **B** become empty at the same time_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** n = 50 **Output:** 0.62500 **Explanation:** If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 \* (1 + 1 + 0.5 + 0) = 0.625. **Example 2:** **Input:** n = 100 **Output:** 0.71875 **Constraints:** * `0 <= n <= 109`
null
Hash Table,String,Trie,Sorting
Medium
392,1051,2186
1,816
uh let's talk about truncate sentence the trunk sentence is a list of words that are separated by a single space with no leading or trading space and each of the words consists of only upper and lower english data so there's a constraint you can only have k words so the first k words you are going to return the first k word so for example uh k with the four you uh return the first full strings instead of the last one com so you don't want contestant so what you actually need to do is you can actually have a string builder and i can say count space equal to zero and then when i convert the string to char array if i see the space which means there is a word for sure right and if c equal to k and i just break and what should i do now i should i can just append a pin what open c right and then if i see a space i can append a space others y uh okay so i already append a space if i see the space and if i see a character i just append it and just return screen right just return string okay i made a mistake when i talk about the space but let's find oh where uh this should become space instead sorry making mistake so count space if a conspirator is equal to k i just return i mean return the string i have if not then uh sorry i should see okay pause so what i actually do is i convert the string to char array and then i do three so traverse through the string array and it's to see if i see a space which means there's a character right and if the space count is equal to the k so when you see one two three four right when you see the count space is equal to four right you break the loop and then you return the string and understand that you just keep adding the space adding a character sorry and for the time and space is and for the worst case alderman you add every single word into the into a string for this uh for example this and every single character into a list for the time you are traversing every single character in the list so it's all over as well so total time open and that will be your solution and peace
Truncate Sentence
lowest-common-ancestor-of-a-binary-tree-iv
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a sentence `s`​​​​​​ and an integer `k`​​​​​​. You want to **truncate** `s`​​​​​​ such that it contains only the **first** `k`​​​​​​ words. Return `s`​​​​_​​ after **truncating** it._ **Example 1:** **Input:** s = "Hello how are you Contestant ", k = 4 **Output:** "Hello how are you " **Explanation:** The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\]. The first 4 words are \[ "Hello ", "how ", "are ", "you "\]. Hence, you should return "Hello how are you ". **Example 2:** **Input:** s = "What is the solution to this problem ", k = 4 **Output:** "What is the solution " **Explanation:** The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\]. The first 4 words are \[ "What ", "is ", "the ", "solution "\]. Hence, you should return "What is the solution ". **Example 3:** **Input:** s = "chopper is not a tanuki ", k = 5 **Output:** "chopper is not a tanuki " **Constraints:** * `1 <= s.length <= 500` * `k` is in the range `[1, the number of words in s]`. * `s` consist of only lowercase and uppercase English letters and spaces. * The words in `s` are separated by a single space. * There are no leading or trailing spaces.
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
Tree,Depth-First Search,Binary Tree
Medium
235,236,1218,1780,1790,1816
102
leak code question 102 binary tree level order traversal given the root of a binary tree return the level order traversal of its node's values from the left to right level by level so in the example here we have a binary tree so our output needs to include the node's values level by level so we've got three here which is the first level we've got 9 and 20 here which is the second level we've got 15 and 7 which is the third level and as you can see the output is an array contained in three different levels first second and third level so let's discuss how we'd solve this so level order traversal we'll be using a breakfast search approach so breakfast search utilizes a queue data structure our q data structure just restricts the processing order of an array to first in first out basis so we're going to initialize this q with the root so we're going to pass in three we're going to have current this is just going to resemble the current node that we're on that we're checking to see if it has children and then we are going to also need a level array which is going to store the levels and up here will be the result array so let's walk through this example so we've got root within the queue we need to check its children left and right so we shift from q so three goes into current we check its children so there's nine and twenty three has been seen so we can add that into level and because we've finished this level and there's no other node at this level we can push three into results and then we move on so everything is reset apart from the queue which contains nine and twenty we shift from the queue so 9 goes into current we look at current does it have a left child does it have a right child no 9 has now been seen so we can add it into levels and then we move over and check the next value within the queue so 9 has been seen 20 shift from add it into current check if it has children we have 15 and 7 these can be added into the queue 20 has now been seen so we can add it into the level now there are no more nodes at this level so we can add this array within two results and then reset level and current so now we shift from q 15 add that into current check 15 if it has children it doesn't so 15 has been seen to and it can be added into level now we move along in queue we check seven can be shifted can be added into current check to see whether seven is children it doesn't so we can add this into level now there are no more nodes at this level so we can push that level into results finally because everything has been seen too in q so q at this moment in time will be empty i mean nothing current and level will also be empty because we pushed into results now that q is empty we can pop out of that while loop and then we can just return results time and space complexity time complexity is o n because we need to visit each individual node and space complexity is o of n as well because we need to allocate space for the queue so firstly we need to carry out sanity check so if root is equal to null then we can return an array let res equal an empty array let q equal an empty array and we're going to pass in root so let's create that while loop so as long as there is something in q carry this out we need to initialize level and level size we'll call this q dot length and then we need to create the next loop so while level size is true carry this out so we need to grab the current value which is going to be shifted from q we need to check whether count has a left and right child and then push that into q so if current dot left is available q dot push current dot left do the same with right now that current has been seen we can add that into our level array and we need to add in the value and then we need to decrement level size so we can escape this while the res dot push double array so once we exit this while loop we have finished the level so we need to push into res the array that we have created and then lastly we can return res let's run this code okay let's submit it there you have it
Binary Tree Level Order Traversal
binary-tree-level-order-traversal
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[9,20\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
103,107,111,314,637,764,1035
63
okay lead code number 63 and unique paths two so this is the brother of the previous task right here unique paths one in this test it's the same description the guys on the left corner on the top left the destination is on the bottom right and there are only ways to move down or right and the question is how many different paths exist that lead to the destination except this time we have obstacles so it's pretty much the same assumption as before you can check the previous video for more detailed explanation but again using dynamic programming with the same principle for each row we can move forward and for each column supposing that our input will have only one row or one column we can move forward until the first obstacle that we can calculate by hand and then afterwards for each cell we can arrive to that cell only from the top cell or from the left cell if neither one of those is an obstacle so that's pretty much it let's jump to the implementation again pretty simple but dynamic programming tasks are always cool and i will call this a that's because such a very long name okay so this time i will use dp variable vector int okay so it's going to have as many rows as the other guy and hint and this many columns and we'll assign all of them to zero and we'll only modify the values which are not an obstacle so if it is still zero then it is an obstacle so like for example on this cell there are it will be as many ways as from the top because if we arrive at the top we can go down and also from the left you can go right but we'll mark all of them at zero so that won't mess up the answer all right so let's first of all make the first one as one there's one way to move from zero to zero and then let's feel first the columns a zero that size plus i and it will look something like this so if the doesn't equal to one our answer is the previous one so our dpi no zero i is dp zero i minus one this basically means that if this is not an obstacle then the way to reach coordinate zero i is exactly the same as reaching the coordinate zero i minus one so this will pretty much have all the prefixes filled to one until there is an obstacle and after that all of them will be zeros okay so the same thing we want to do for the columns not for the row the first row sorry so it will be so zero the first column of the rows and the same goes like this so i minus one zero okay so and for the entire formula it's uh starting from one which is size plus i j would be again from one and the same formula applies so if it is not an obstacle use the same formula so dpij equals dp i minus 1 j plus dpi j minus 1 and return dp a that's size -1 a that's size -1 a that's size -1 dp a zero that size minus one okay let's see ah wrong answer unfortunately okay what was the problem zero one zero oh it's this test case okay not the complicated one okay where is the footprint this is the first zero i it's not the one then feel it the way it should be filled i think this is correct for the most part and the second loop correct for the most part again and here we have oh yeah my minor footprint here just equal to one that was all it was supposed to be okay this is by far the most ridiculous case i have seen so we have how is this even possible the input says we have only one cell and the guy is there and there is an obstacle on top of the head of the guy okay i need to do maybe the same check here so if a 0 is an okay cell then do this it doesn't make any sense really yep and we're done
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
1,846
hello and welcome to another video in this problem we're going to be working on maximum element after decreasing and rearranging and in here you're given an array of positive numbers and you want to perform some operations possibly none on the array such that it follows the following conditions the value of the first element must be one and the absolute difference between any two adjacent elements must be less than or equal to one there are two types of operations you can make you can decrease the value of any element to a smaller positive or you can rearrange these return the maximum possible value after performing the operations so in these examples they have 221 21 and the maximum value is two and in the second example they have one 100 1,000 the maximum value is three one 100 1,000 the maximum value is three one 100 1,000 the maximum value is three because you can just make it one 2 three and the third example we have 1 2 3 or five and already satisfies the conditions so from these examples you can notice that like the best possible outcome you can have if your array is length n let's say the best like the best maximum you can have is n because the first element has to be one and then the best possible thing also you they can only be one apart so the best possible thing let's say you have five elements it has to be one and then increase by one right so the best possible answer you can have for length n like if n is five here it would be five if n's 100 it would be one up to 100 and so on so that's the first thing you can recognize so let's just say we have a bunch of numbers I'm going to kind of walk through two ways of doing this and I'm going to actually code up both ways because they're both well at least the first one is way super short second one's a little bit trickier and funnily enough as uh a problem I did a few days ago the optimal solution in uh or maybe not optimal but the better solution in bigo actually runs slower on Le code so it's just like test dependent but I'll go over with one so let's say we have a bunch of numbers like 10 8 15 16 1 7 right and how do we actually do this so the first the like the easy way or more intuitive way is you first sort the array because you're going to want to have this like increasing sequence of 1 to n if possible so we're going to sort it and we're say okay so we have one then we have seven then we have eight then we have 10 then we have 15 then we have 16 so once we sort it then like I said ideally if this is at ARA length six you want to just have 1 2 3 4 5 six so basically what you have to do is you have to keep track of like a result and then keep track of like since really all you can do is you can bring numbers down if your numbers are too small you can't like increase them right so for example if all our numbers were ones and twos and we wanted 1 2 3 4 5 six that wouldn't be possible but let's see if it's possible in this case so what we would do is we'd start with like a result of zero and then basically we're just going to go through all our numbers and see is per number greater than result if yes then result equals result + one because then result equals result + one because then result equals result + one because remember result can only increase by one at every single stage and if not right because this is already sorted if not then result stays the same and so let's kind of walk through this and let's do like two examples here so this sorted we're GNA go to the first number and we're going to say is the current number greater than the result yes it is so then the result has to be one and notice uh one of the requirements is the first number in the result has to be one so here the result will be one now we go to the next number because remember our ideal situation is 1 2 3 4 5 six so we check is this number greater than the result if it is then the result is two now and we can just keep we can always like make if it's bigger we can always make it smaller that it fits our criteria right so this will be one if this is bigger we can always make it smaller so we can always make this a two that's one of the operations so this is bigger so we'll turn result to two now remember result only increases by one every time now is this number bigger than the result yes it is so we can make result equal to three and our operation would just be change this to a three right just keep decreasing until it's a three is this bigger than our result yes it is so then our result will be four is this bigger than the result yes it is so then our result would be five break make this smaller again and is finally is this smaller is this bigger yes it is right so because in any two operations you can either rearrange so we are allowed to sort and we can decrease we're basically sorting to rearrange because we are allowed to rearrange and we're just saying like if it's possible to make this 1 two 3 4 5 six let's go with that so that's one way now let's have another set of numbers and I'm just going to write them out in sorted order because we're just going to sort to begin with any so let's say we have something like um so we have 1 2 two 3 4 58 let's say so ideally once again we want to have 1 2 3 4 5 six 7 you know and so on so let's walk through this example and let's see what would happen so let's change the color here we're just going to write the number that gets transformed into above it maybe so our result will be zero again so we're going to say here is this bigger than the result yes it is so we are going to update our result to one and this is already one is this bigger than the result yes it is so we're going to update our result to two this is the number we want is this bigger than the result no it's not and we can't really do anything about it right I mean we can like put in a bigger number now but then we're going to have this two so ideally you want to have it in sorted increasing order where you have it like this so if this is not bigger than the result stays at two and is this bigger yes it is so now our result goes to three is this bigger no it's not so our result stays at three is this bigger yes it is so our result is at four is this bigger no it's not so our result stays at four is this bigger yes it is so our result is five and is this bigger yes it is and our result is six and we would just change this value to a six right so we still have that property where every value is one apart so we still have that property and uh the biggest value here is six that's kind of like the first way of doing it where you just sort and you just literally check is this number big enough where I can just increase my result by one if yes let's do that if not let's keep the result the same and the only way basically it's not going to be big enough is if you have two numbers that are the same okay so that's one way of doing it um and this is going to be an nlog N solution right because we're doing a sort so there's another way of doing it's going to be kind of similar so let's walk through well it's going to be kind of similar we're not going to be sorting we're kind of going to be doing that bucket thing that we were uh doing in the last few problems we're just going to get Buckets and the number of numbers for every bucket so the idea is let's say we have so this is 1 2 3 four 5 six seven 8 nine so if we have nine numbers what's the biggest number we can have nine right so if we have nine numbers we can only have this at in our final like outcome so 1 3 five six 78 nine this is in our final outcome so any number bigger than nine is going to be basically the same as nine because we can't really get to any number bigger than nine even if we increase at every stage so any number bigger than nine what we're going to do is we're just going to say it's nine so if we have like a 100 a th000 and all those things we're going to turn those all into nines because they will end up getting reduced to a nine or less right so basically anything bigger than nine or nine is the same because it can fit anywhere like it's always going to be bigger than the result so they're equivalent so what we're going to do is we're going to bucket every single uh every single index that we want and a count so let's say we have a bunch of numbers let's just have nine numbers again so let's say we have like some random numbers like 10 15 2 3 8 100 how many is it six uh three again and let's say we have a bunch of Threes something like this so that's uh 1 2 3 four five six seven eight nine okay so we have nine numbers now instead of sorting we're going to use this bucket technique where we know like okay the biggest number we can have is nine so we're going to have a variable for like Max num we'll call that like Max or something obviously we're not going to use max but you know uh so we're going to have something like this and essentially what we're going to do is for every number we're just going to say if it's bigger than nine we're just going to add one to the count of nines that we have and then we're gonna have a dictionary of counts so let's call this counts and let's go through this so 10 is bigger than nine so we will have nine with a count of one and let's maybe try to have this like a little bit in order so let's put the nine like down here with a count of one 15 is also bigger than nine so we will change it to a nine with a count of two so we have two with a count of one we have four threes so three with a count of four we have an eight with a count of one and then we have this 100 with a count of one and so this 100 turns into a nine okay so we have uh nine numbers total and the idea now is instead of sorting we're going to go through every single number that we could have had in here and because we reduced everything to a to one through nine we're just going to go through one through nine and we're going to see how many of those do we have right and the idea is for Anytime our result is Big anytime our number is bigger than our result we're just going to say okay how many of these numbers do we have and then how many can we use and let's kind of walk through the logic with that so once again we're going to have a starting result of zero okay so remember ideally we want to have one through nine in our output array because that's the biggest sequence you can have so let's walk through this so first we're going to go to index one and we're going to say is there a one no there is not then we're going to go to index two and we're going to say is there a two yes there is with count of one so because two has a count of one there's only one in here right so that means our result we can only increase it once because our result is zero because we only have one number here we can only increase the result once and the maximum number we can increase the result two is only two so let's say two cut a count of 100 and our result is zero well we can't increase our result past two because we can't increase two we can only decrease two so we basically have to take the minimum of the count right we have to take the minimum of the count and the difference so let's say our result is zero and our number is two the most we can ever get that number up to is two so it's going to be the difference of result minus count and the other value We Care is the actual count right so we can only increase it count amount of times and the reason we want to do this in uh we don't want to like while loop through we don't want to while loop through every single one of these we want to just calculate it on the spot and so if we can only increase the result up to two the most we can increase it is result minus count but we can only increase it by one every time we actually we need to have a count right so let's say we can increase the result by two the only way we could increase the result by two is if we actually have two twos so this going to be the minimum of these two and that's the operation for every single count so let's calculate this so we have or it's going to be actually the opposite not it's not going to be um result minus count it's going to be uh it's going to be count minus the result so it's going to be or well not count it's going to be like the value right the value or this key okay so key minus result so let's kind of walk through uh why that is okay so our key is two right we are trying to get our result up to two so key minus result is two the most we can get our result to is two but we only have one two so if our result is zero we can change changes two to a one right and then our result would become one but we don't have two twos so we can only get our result up one so this result now transforms to one and then we check again we check one we check two now we check three so three has a count of four and I'm actually going to write this out in our output array just to demonstrate it easier so in the beginning we have a two so we got our result up to one because the our operation was basically take our two and change it down to a one right because we need it 1 through n okay now for the three uh so our key minus results so we have 3us one is two so the most we can increase our result is by two and how many threes do we have four threes so because we have four threes we can only increase our result by two and then to increase it by one you need one number so the minimum here is two so what you're going to have is you're if you're going to have four threes you could do something like there's a bunch of different ways you could do this but one of the ways would be like one two three so you in you decrease two threes to two and three and then or you decrease one three to three sorry and then the rest of the threes you would just write out like this so this is one way of doing it I think yeah there's other ways right you could do like one two 3 three and so on but essentially something like this so that kind of represents why it's the minimum of these two right even though we have a lot of Threes we can't get our result to be above a three because we can't increase our three so then we go to four we don't have any fours we go to Five we don't have any five no sixes no sevens now we go to eight with a count of one and our result is currently actually three so if our result is three eight has a count of one once again we do this key minus result so the most we can increase the result is by five numbers right we can go like f we can go four five six seven eight but we need five we need a count of five to do that we only have one so if we only have one we can only increase our result by one because we only have one number and we have to increase by one we can't increase it by more than that so our result here would now turn into four and basically we take our eight and turn it into a four okay now we go to nine it has a count of three so nine with a count of three our result is currently four so what's the most we can increase our result by it's going to be 9 minus 4 which is five but we only have a count of three so we can only increase our result by three so this result would turn into a seven and one of the possible operations would be take the first nine turn into a five take second nine turned into a six take the third nine turned into a seven I think it's the only way to do that but that's kind of like what these are so essentially if I write these numbers on the top this would be we took uh here's our numbers right so we took our two we turned it into a one these all used to be three so three and then we had the eight and then we have 999 so the blue is what the numbers used to be and then the green is what we turned them into right we're essentially figuring out like okay every time the number is bigger than the result let's just add one more number than the result and by using this equation we're able to if we have a bunch of one number we're able to figure out how much can we increase the result by in one instead of looping through the number a bunch of times because that would be efficient right let's say you have nine or let's say you have like a number like 100 with a count of like 50 you don't want to like Loop through it you just want to quickly calculate like okay what's the most I can increase it all right so that's going to be pretty much it this one's a little bit more confusing sorting is a little bit more straightforward for I'll codee up both because it is relatively short so let's uh start with the Sorting so we can sort the array and we're going to have our result start at zero and we're basically going to say for number in Array if number is greater than the result that means we can increase our result by one right we can just chop down our number to be result plus one so if this is the case our result plus one and we can return result and we can submit that and funnily enough this one is actually uh quite efficient even though it's worse time complexity so we could talk about this one real quick so this one is going to be o of uh n log n because we are sorting and o one space right because we don't have any kind of extra variables that's the first one so now let's go through the second one which is a more complicated one so we're going to have a default dict you could also use an array so we're going to have nums equals default dict int and the max number we can have remember so for an array of length n the max number we can have is length n right if we have nine numbers we can have one through nine Max number is going to be length of the array and then essentially we're kind of doing the same thing so we are going through for number in R let's nums if the number is bigger than Max num let's reduce it to Max num right so we'll reduce it to minimum of num and Max num so if it's smaller than Max num let's keep it the weight is otherwise it's reduce it to maximum so if we had like a 100 here this would reduce it down to nine if our array was length n okay now we have the same thing so result equals zero and essentially we're going to Loop through every single index in the array so we'll say 4 I in range so what are our numbers so our numbers if array is length nine it's going to be 1 through nine so it's going to be 1 to Max num + one right so max num here to Max num + one right so max num here to Max num + one right so max num here would be nine so one to 1 to 10 but it does include 10 so be 1 to N9 essentially we're going to say result plus equals that equation that we had the minimum of the count of I and how much can I actually increase this result right which is I minus result so if our I is like nine and our result is five the most we can increase the result is by four so we have to figure out do we have enough if we have enough we can increase it by four if we have too many we can still only increase it by four and if we don't have enough then we can only increase it by the count and return the result and funnily enough like I said this one actually runs slower but in theory it should be better so this just kind of depends on Le Cod cases so this one is actually of n because we are traversing um we're traversing the array here right so we're traversing the array here and then we are basically traversing the length of the array here and this is an over one operation so theoretically it's still oven and this is this one does take space so this is oven space because for every single index we are keeping a count so both Solutions just wanted to show those this one's pretty quick so I decided to do both so hopefully you like this one I think this is like the second or third problem actually where like the optimal solution actually uh did worse on Le code cases but that's whatever um but yeah I think that's going to be all for this one so hopefully you like this one and if you did please like the video and subscribe to the channel I'll see you in the next one thanks for watching
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`. There are 2 types of operations that you can perform any number of times: * **Decrease** the value of any element of `arr` to a **smaller positive integer**. * **Rearrange** the elements of `arr` to be in any order. Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_. **Example 1:** **Input:** arr = \[2,2,1,2,1\] **Output:** 2 **Explanation:** We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`. The largest element in `arr` is 2. **Example 2:** **Input:** arr = \[100,1,1000\] **Output:** 3 **Explanation:** One possible way to satisfy the conditions is by doing the following: 1. Rearrange `arr` so it becomes `[1,100,1000]`. 2. Decrease the value of the second element to 2. 3. Decrease the value of the third element to 3. Now `arr = [1,2,3], which` satisfies the conditions. The largest element in `arr is 3.` **Example 3:** **Input:** arr = \[1,2,3,4,5\] **Output:** 5 **Explanation:** The array already satisfies the conditions, and the largest element is 5. **Constraints:** * `1 <= arr.length <= 105` * `1 <= arr[i] <= 109`
null
null
Medium
null