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 |
---|---|---|---|---|---|---|---|---|
929 |
hello and welcome today we're doing a question from lee code it's called unique email addresses it's an easy um let's get started so every email consists of a local name and a domain name separated by the at sign for example in alice is sign for example in alice is sign for example in alice is the local name and is the local name and is the local name and is the domain name besides lowercase letters these emails may contain periods or pluses if you add periods between some characters in the local name males will be sent to the same address without dots in the name so dots are basically meaningless for example at alice. and alicia at alice. and alicia at alice. and alicia are the same email this does not apply to the domain name however so after the at sign it does not apply if you add a plus in the local name everything after the plus sign will be ignored this allows certain emails to be filtered for example m.y plus name for example m.y plus name for example m.y plus name will be forwarded to my will be forwarded to my will be forwarded to my okay and again this rule does not apply to domain name so here we just got rid of the name um and it's possible to use both of these rules at the same time as we saw here both the period and the plus were used given a list of emails we send one email to each address in the list how many different addresses actually receive emails so here we have test email so just test email ignore this at here again this is test email ignore the periods um ignore the periods um ignore the periods um and of course everything after the plus to be ignored um and then test email at so here it's l-e-e-t- l-e-e-t- l-e-e-t- so that is different and which is why we have two different outputs so this is a fairly simple easy problem i think it's just good for string manipulations making sure we know whatever language we're coding in pretty well how to use string operations so we're going to have a set this is going to store all of our unique email addresses and we just keep adding to the set after we get rid of the periods remove everything after the plus and return the length of the set at the very end so for each email and emails we want to first split into the local and domain name so the first part and the second part so first um let's call it last equals email dot split on the app so what dot split does is it finds every instance of whatever character you have in this quotation mark here it's an at so every at that occurs it's going to make a list and remove the ad so for example over here if i have alice at it's here if i have alice at it's here if i have alice at it's going to return a list where the first index store is alice z the second store is if the second store is if the second store is if there were more ads it would just make more additions to the list every everything that comes between the ads so here it would be this they said there's another ad after this and more text after that text would be in another index so now that we have split on this at right here we want to get rid of all of these pluses so everything after the plus we don't care about so if plus in that first part um we remove the plus and everything after so first now equals first so colon means we're including everything up until so first dot index of that plus index of this character is going to return its first occurrence in this string so the index of that will now not be included in first we've rewritten first to not include plus and after and of course we want to replace everything with the periods we just want to get rid of them and add it to our set so a dot add first dot replace we're gonna replace all the periods with nothing so this is just an empty string right here it takes all the periods and replaces it with this pretty self-explanatory um and pretty self-explanatory um and pretty self-explanatory um and then we want to put the string back together both the domain name and local name so we're adding the at symbol adding last nothing really had changed for last we didn't really manipulate it in any way and now we want to return the length of a so it's going to have all the unique email addresses that's what the set will do for us so return len of a let's run this code accept it and submit and it's accepted as well so quickly talking about space and time complexities space it's going to store whatever the set stores right so it could be o of m if m is the number of unique emails this comes out to and for time complexity it's going to be oven because we're iterating through every single email in the emails when we do this split again we go through the entire email find all the ads split make a list when we're finding this it's another linear scan replacing is another linear scan so all of these are basically linear and end up being o of n if you have any questions at all let me know down below otherwise i'll see you next time
|
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 |
133 |
Hello hello guys welcome back to tech to join this video will see the common problem which is program successful hot list code number 133 so let's not look at problems statement in this problem and goli to create a lot of given one day problem in graph interacted With Nothing But and subscribe to the Channel 900 This is the Richest Man in the Question Number One to Off Representative List subscribe and subscribe the Channel Behaving the Information about the 09 2012 That No Latest Look at the Observations So Dakshin Raat Has All Notes New Notes And Don't have no difference to give in original sources basically creating and dept subscribe The Channel Please subscribe and subscribe this Video Subscribe Important Observation Note subscribe and values which will be Observation Note subscribe and values which will be Observation Note subscribe and values which will be representing the valid notes will be keeping track of all subscribed notes that minute will be stored In the internet or in notes wife in this distinctive word not money to use in order to solve this problem they need to traverse all the original and they will make your dear father for this problem solve they otherwise this channel subscribe button simple difficult latest lutab school Subscribe for latest videos from Will Not Know What Do We Call The Will Not Do That Boat This Will Be Appointed To This Not To So Will Be Making This Not To Okay So Before Going To Not To You Can Actually Make No Difference 9089 To 9 News For All Elements From This Point To 9 News Already Made Simple You Will Be Making And Which Will Give You Can Not Make Award This Problem No Problem You Can Withdraw pre-2005 Notes Problem You Can Withdraw pre-2005 Notes Problem You Can Withdraw pre-2005 Notes Will Take Away All Subscribe Now To They Will Be Converted To Improve This To You Will See What You Want To Give One Has Already Been Made Some Places To Visit In Point To Point Problem Remember No Veer The Same To The Same Present And Share It Is Not Chapter No. 8 Notes Fennel Withdrawal Bullion This Is Not Possible So You Will Have To Use A Different If You Find Hidden You Want To Know What You Need To Know From Where Did n't Know What Will Be The Way You Can Give Way To give 999 9999 for number one to you can also take care the yogas to not one in stop this channel no valid for the value overall you will go to the not to 9 0 no to you will make you know that you will not and make A Call To The Call Subscribe Button Subscribe Now To 9 Will Not One Will Dare I Will Be Id 2nd Id Element 5 This No Call Okay So They Can Be Updated On Jhal Desh Will Be Updated And 110th Love Story Note Do Not One Should E Us This Not To Know Where Did Not Know You Can See You Later This Is Not Solved Will Give You Need To Know You All The Original Sources Tell Me To 9992012 But You Will See The Difference Between Avatars And You Will Not Three Love You All The Best Song Girish Shades This Note 3 Will Also Be Passed Members Notice From Original Graph And Destroyed Is Not From The Region Of This Newly Made Food Research And Development Can Only Be Safe From The Original Graph Notes Noida Will Be Made Here And You Will Get Updated With Story Note 3 Not Adjust And Elements Of Not Free To Be Liberated From The Mode On Original Name Is The Number Of But It's Already Created From This And Will Not Created Strus You For Watching This Is Not No When you all the best to make a note near that know what is the next step well in the next time when you later this note 4 9 4 and will start getting all the elements of WWE wrestlers which will try to avoid you will not the Subscribe Back to the Already No Hero Who Has Already Been Created Evil Apni Poonch Country Note End Wars Than Ever Before Starting Point Have Traveled Yar Urin Tarzan This Is This Question Very Simple But Not as simple to implement what is the time complexity subscribe The Channel ki veer is the number of this is the what are doing this you will not be seen after making sure will just do the great for all the best and Notes from original software with starting point will be in the original and withdraw all notes will always know the original and not have knowledge about all subscribe aur bell point to point is this channel ko subscribe our Channel this is the current node mehndi Siddharth visitor map and visited there no s soon s they make the united vs new node in the call s well s original from the original on newly made hair oil add this original Video then subscribe to the Page if you liked The Video then subscribe to subscribe Satire
|
Clone Graph
|
clone-graph
|
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node.
| null |
Hash Table,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
138,1624,1634
|
316 |
Hello everyone welcome to my channel codestorywithMIK, so today you are going to do video number 20 of the strings playlist Leetcode number is 360 medium marked but I will tell you the story in a simple way you will be able to code it on your on ok the name of the question There are many similar questions like this Remove Duplicate Letter and most of them are by Microsoft, it is okay but this question has a good tweet in it and it is a nice brother Google OK, I am wrong here. Given it was bin asked by Google ok so yaar let's see the question kya hai jeevan hai string s remove duplicate letters so tha every letter appears and only one let's ok one strings given all the duplicate letters you have to remove true date every character Come only once but take care of one thing, I think this is the most important part of this question, the result is fine, like see here BCABCABC So which are these duplicates I am seeing one wicket. So B is there twice, A is there, C is also there, A is there twice, then which one will you delete? If you delete this B and this one, then what will be your answer? BCA, but if you had deleted this B and this one, VCABC, delete this. If you had done this then your answer would have come to you, ABC is Lassi, who is the smallest, ABC is right, look, the answer is ABC, look here also, here it is C B A C D C B C and you will listen to a love story with this code finish. It will be done ok hello ok the result has to be made lion as of now it is empty ok as of now there is nothing in the result and lion ok so here I will do the indexing 01234 ok now see first of all it must have come to your mind that friend How do you know that a character is present multiple times? Like mother, look at B here, A has gone once more, that means how can you know its meaning, friend, keep a map for that, or keep a set, or Then in the question, it is given only from this lower English letter, so it is 26, keep it, okay, and if any character has been visited, that is, if any character has come twice, then you can find out from there, so what will I do here, okay? If it is there, then minify it like this, if A goes to zero, A will represent it, okay B - A, if 1 comes, okay, then this B, you will already know this, C is given and so on, okay, you will know this, I have told you earlier also All these things are fine, so why did I write this, you should know that like let's say mother, if there is B here, then B has been seen by me, so I will mark B as true here, again when B is seen again in the future, I will check, okay, here it is true, that means B is duplicate, okay, so it is retirement, that is why I took a map here, right, here I write it, if it is not of Tech, then the scene can be named anything, Tech Care means already taken. Okay, we have got it, from here we will find out the duplicate. Okay , starting is okay, now look, pay attention, the index is here, it is here, I have just come here, I have seen it, okay, the result is empty. Now the result is empty so don't do anything directly put B here B we have taken S B so marked B as true ok now I am coming next ok here now look pay attention but it will come. C is bigger than B. You see, A is in the lexicographical order. C comes after B, so C is going to the right place. So what did I do, I put C here, right . Now I have come here, okay, A has come here, A has seen, oh brother, there is C here, but this comes first, after that, C has come, okay, then this order is wrong, right, so A will say, brother. C tell me one thing can you do later A I mean where is it right now so is there anyone in the index after you C is A he is asking if there is then you are now who is later A is it okay to go then it is not Asked A whether you have come later also, C would say yes, I have come later, after you, meaning after you in English number, I have come after you, look, I have come at index number four, friend, I came at index number 4, so A said it is okay. So you then A go, now you are there, why because I am younger than you, I should be first, then C will say, ok, I am going, so as soon as I removed C, then C will bring me here, when C was taken, then true mark. If C has done it , I will have to put a watermark here that it has been reduced, we have not taken anyone from our result, it is okay, as soon as C moved away, now A asked B, brother B. You are elder to me, so I should be before you, then again he asks B, will you come after me, I will come after your index in the future, that is, what is an index? Okay, and B is going to come in the future. Na, let me come now you are there, because I am the youngest, so BB is gone. Now here the result is empty, so we have given one more pulse. Okay, and we had removed B, so B will have to be marked first because BF. No, it is not there in the result and A is now A. We have taken A, so one is taken, one has been marked as true. Okay, now A has come here, so C should come here, so C will go to A because C is bigger. It will go smoothly A Here you will come in the future or else the sign told me that in the future I will come in one of the indexes, he is right after you, how will we know that, we will have to store the story instead of B, which is later. It will come in some index, okay, so that too, we will store it on the story, so what will I do for that, I will take another one of size 26, what is the last index, where you will come, okay, look, I will be driving again last means after. When will you come in I, when will you come later? Index, its name is ok, you take the last induction, what does it mean while coding, so I went to B and wrote zero here, brother, you who is zero if it ever comes later also, then most I have to write the last index here, I am fine, now look here, C came on, but I went to C and wrote Kar, it is clear till here, now see, I will drink again, okay water so on, okay. Now look here, A was there, B is there, and the result is still empty, so when the result is empty, then put B. Here A is C is there, so it is right, only after B, C comes, then C. Also quietly here A went to the result, we are fine, now look, A is here, A is gone, okay, this A has gone, A has seen, C is good, I, this is bigger than me, so A has to be told to move away, but look, pay attention. Here A asked C to C, will you come later? C said, wait, I will check on my last index, so I went to C, it will be taxable and now whatever is on the second index, it will be taxable. Meaning in the future I am going to get one more. Okay, that's why I can remove this one now, so I removed C. Then I also asked B, brother B, when is your last index, will you come in the future? B said yes, I am the index number . I will come on three, now on three means you will come in the future, which means again now, which is also B is gone, poor guy, okay, so here why did he go to A because now both of them were done, from our result, now I came here. Okay, here B saw that the last character in the result, A, is small to me, so B can easily go to B, A is also C. The red character in the result, B, is small to me, so C can be easily answered, this will be our answer, it is clear till now, okay, so I will show you directly by one more example, okay, but before that, pay attention to one thing, many people say this and it is also correct, what is the reason, I have C is popped, the question of start is actually monotonic start in which you are following any order or it is increasing order or it is decreasing order, lexicographically increasing the string itself, this is a kind of string of my result, string Now you can do this also, if you go to my Github code, I have written the code from string also, I have written the code from stock also, there is no problem, you can see that also, but I have solved it from string only, ok. But I am trying to tell you that this is also a question of stock. The question of monotonic start is clear till now. Okay, let us take another small example. Okay, which is important to understand. Let us take mother from the point of view. Our example is B C A B is a small example, so first of all fill the last index to know when will you come last, after that the one taken is ok. The English letter is C. It is 2525 but A is there, so I went to B and filed zero here. But look, I have done a little concentration because what I am writing here is when can someone come later, so I have updated that, okay, great, I have done it, now let's start, my address is empty, the result is empty. so i can relax i am ok you me You are small, sorry, you are big, so you will have to remove me, but C is saying that friend, I will not come later, why won't I come, see what is the index of C, then you are in the future, index means after A, C has never been A. If it is there then I can't remove C. This time I won't be able to remove C. It 's clear till now this thing was important to understand. It's okay if I can't remove C then it doesn't matter. I'll add A. It's okay here. Now let's move ahead. Now look, B is okay, so B comes after A, but why wouldn't I do it to B because B is already used? Right, see, here I did not mark true, I forgot to mark it has already happened to B too. When has it happened to him? Okay, you will insert a character when it is not him. Big B, once he has happened, if you want to bring it multiple times, then we will not use B, but okay, so we will take care of the duplicate also. Should have been given every time, when will I include any character in the result, when it is not used, not taken, like it was here, right now, B has come to me, then why did I not include B, when B is bigger than A? B should have come here, but B is already used, hence we cannot write B again because we cannot do anything with duplicate letters. Every character has to have a big Aana. Sir, it is clear till now, it is a very simple solution, Mr. Now you have understood completely, now you can code very simply, so when you are going to code now, you will do exactly what is told line by line, first file the last index, then make a mistake in which all the falls will be there, then start filing the result. In this, it will start from i0 by hitting rate, okay, it is clear till now, try to understand its time complexity, what will be its time complexity, it is very simple that you are not visiting any character more than once, on pain. Loop is fine, you will not visit any character more than once, you can do it directly, you are not visiting a character more than once, okay, that is why its time compatibility is off N, but now when I will code, neither see the code. By looking at the for loop, you will definitely feel that it is quadratic but it is not quadratic, okay, but if there is another for loop inside the loop, then it does not mean that either there is a will loop inside the for loop, whatever. Whatever the look, it does not mean that it will be quadratic every time, it will be fan square every time, it is not necessary that you have to see how many times you are visiting the elements, so pay attention here. Dog Na, you just think even once, its time is going to be compressed of n and what will be the face completeness, we have taken the last index of 26 size and Taken, this is also of 26 size, so its 26, what will it be then ? Take only one mother and keep it constant. If you see this, then let's code quickly and do the code exactly like the story as explained. Okay, let's start the court like this. Look, there is an exact similar question. Liquid number 1081 is given here. You will copy and paste the code from it. So it will be submitted. Okay, first of all, what did I do? I took out the s dot land. Okay, I took out the land of my string. Let's also take the sting result. Okay, now I had said that two vectors are made of vector of words. Okay, what was this? Are you lying or not? Does it have a character? It will be of 26 seeds and I have marked it first now because I have not taken any character and it is 26 because all the lowercase English letters have been given in the question. Vector of eight has been taken. Will it store the last index or not? How will I be able to know with its help whether any of your characters will appear in the future or not? If that character will appear, when will it appear and at which index will it appear? Last four and I = < is ok. Which character is care of ch=sofi Okay, now the last index has to be filed, it is of the character okay, so which index will be corresponding to that character, in the last index one, it will be done by doing C, Ha, Min, A, I had taught you this is equal to constant. I came to _ The idea was that we will go to all the characters one by one and which character is it? This is how the indexes used to come out. The character is fine, see what I said that if I have already taken a character, take care of the idea, it is equal, it is true, that means, if you cannot take it again, then continue, okay, and if you are going to take it, then we should What will have to be seen is that if first of all, brother, whatever character is there in result.back is correct , that is, I have solved it in K, then it is wrong, we will have to remove it, but when will it be removed and whose last index is it? The result.back will come later, how will you get the last one? By doing this it is ok, this is the character, so why did you do the result by month so that the index can be taken out, then the last index has been found, if that is ok then give the greater i, what is the meaning of this index. Even if it comes in the future, it is safe, you remove it, if it is safe, you pocket is fine, then it is fine, let's pop it, result dot pop it back, fine, the character that was in the back of the result is fine, if it is big, it will have to be removed, but When will you remove it, when will we meet in the future, did it ever come after the index, okay, now that it has been removed, okay, what will I mark before removing it, I will water mark it, okay, I got the index from result dot back minus A. I have marked the water mark, it is clear till now but take a check here brother, the result should not be there, the result length should be greater than zero, only then you will be able to do all this if the result online is not greater than zero, that is. If it is zero then everything in the result.bag will fail. Ok, it will be clear till now, whatever story you tell is exactly the same. Understand well that if the character behind the result is bigger than the current character, then you will have to pop it, but pop it. When will you do it, when will I get it in the future, look after the eye index, its last index, it must have come in Greater Dane, only then, okay, I popped it and marked it first, we have not taken it yet, okay, great, now. I can put the current index in my result dot push underscore back sure ok so what index of K will it be K - A which I had started with, marked it true till now it is clear, now what do we do? In the end, return the result, you will also get the Java code in my get up link. Okay, so look here, first let's see whether it is getting submitted or not, let 's see after submitting, but before that, see one inside the loop. And this does not mean that it is quadratic time complexity, okay we are visiting each character only once.
|
Remove Duplicate Letters
|
remove-duplicate-letters
|
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
|
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
|
String,Stack,Greedy,Monotonic Stack
|
Medium
|
2157
|
974 |
Hello everyone, today we will be discussing question number 974 of lead code which is sabri sam divisible by request. You are watching the videos of these two questions sub are equals and continuous sub are equals because these are questions in prefix hum pattern. This is also a question of Prefix Hum Pattern, isn't it and in both these videos I have discussed the method of Prefix in great detail, how to tackle this question and the question that is this and in this I have explained it in great detail. I will also explain to you, there is no issue but if you watch these two videos then you will understand the discussion more easily and you will be confused about what are the problems here, one will be this, okay one will be this 510 All positive So there are 7 here, now how will we do this question is very easy, if you know how to tackle the prefix us, through these two questions then you will do it immediately, just a little bit with this question. Okay, as we saw in the last two questions, I will not refer them very often, I will try not to refer, but in that only we discussed, I took one, this is what we made a prefix, okay, now here in the prefix n1. So what will happen to it, the elements before it are sound and zero, the elements before it are called sam n1, the name of the element before it is n1 + M2, okay that thing as you will see if it has A plus B Our in that What we do is we find the same mines again and again, I don't want to go into detail about it, so what we have here is this is equal to A plus B, this is B Now what do I have to do here? What is this Sam, if I take its mode then should it be zero? Otherwise a condition will be satisfied. I have given the cake and how I got Sam that with this model, zero is coming along with it. My condition will be satisfied, it means if I have got one morning then I have got Jodhpur, if I do it with the models then I get zero, then I have got all of them, then my condition has been satisfied. Model OK J Ka Kek K By adding modules, we get one number and that too should be N. If this happens, then this is everything between I and J. This will be divisible by K. How to see this, then you can skip this example. If you have seen it in the previous question, if you have not seen it, if you have not understood then you can understand it again. So like I did 23 Model of Five, then what did I get? Sorry So what will I get, even then the file is You will get neither I am what did I get? Sorry So what will I get, even then the file is You will get neither I am what did I get? Sorry So what will I get, even then the file is You will get neither I am seeing now nor I am doing multiple sets of sex and modules N is repeating why because in 12 models 620 that is why the meaning of this question is that the model being is repeating is this equal of PK models. P Model Okay when did this happen when the Sam was divisible by them This is the condition that has to be satisfied Now let us see this in the example also It is given in the example Let's start We can extend the models also Yes, why is that, let's go here instead of four, it is okay, it is available, yes, so I was in the answer variable was zero. Earlier [ variable was zero. Earlier [ variable was zero. Earlier which one is this and before going ahead, there is a frequency van of four, so what to do with it. Two, now I will move forward to four How to do the mode of mines, I will take a little bit of wear, then what will happen, but let's assume that I have an example, what did I do, my 11 model will come out with five, I will show how to do it if I in this What should I do 11 plus 10 done model of five because it is from 10 model of five it is zero study number need big number There is difference in this question and in continuous question there is nothing else There you had to specify the frequency, but here you can put a separate value for the frequency and there is no difference, now here what will I do for -1, I will van the -1 first, what will I do for -1, I will van the -1 first, what will I do for -1, I will van the -1 first, I will get it It's It's It's done to me, I have moved forward 4 Have you seen only mine, have n't you shown me? Yes, this is the first one you have seen, so the first one you have seen is this, meaning this is the whole thing from here till here, right from the beginning. Okay So here I will start my phone and stock size Now here I will add my prefix us to come out of the name and that becomes negative By doing positive Given, now how will I divide it, now I will take its ceiling function, understand? Now I will take its ceiling function, and how will I multiply it, I saw what I did, I am doing what I said, understand so so so that he can move forward It will go, I will just find out whether I am getting it, this is not equal to you and if so, then answer plus turn off the MP, the frequency is and after all this is over, update its frequency, that is the thing here in my mind which is That's what we had to see, if there is no star then it is a multiplication sign, then it should be accepted, now okay, if it is accepted, then this pattern is very important, you have to understand it, you will get many prefixes, our questions will be solved, okay.
|
Subarray Sums Divisible by K
|
reorder-data-in-log-files
|
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104`
| null |
Array,String,Sorting
|
Easy
| null |
1,695 |
credit program is the sixth 1695 the maximum erasure energy value their you're given an array of positive integers nouns and one two days want to make a unicorn want to make a subway containing nucleometer and this sub array with the unique element we need to find the maximum score of subway so we need to consider this kind of two examples let's see the first one pull 2.56 okay put four five six four two four five six and this is sneaker unique but in this case though there are already four heads appeared in the strings in this case this is incredible this is unique subway so some of these bags are 17. so drop the first example return 17 and the second case five two one two five in this case but only two up here so you click and you can consider there are four kind of next y axis in the example 2 so the but older some of the subway are a same as a so we can call it the courtesy so simply like this now we need to solve this problem with 30 pointer algorithm and so we need to dig away left point and white point and we need to create a little variable value and in order to store the previous index that there is already axis appeared in the given subway we have to prepare the dictionary that's folder that's true the index of turbulence quite badly the problem is already played this yeah right and now is the other wrapped pointer because third value with the rest index that then the left side of foiler then we need to use we do not have to consider value like this and update the left side of the folder and update right side of the pointer of this okay right side the folder is this one and the augmented place the index and enter value and calculate your max operator maximum is video were as high so i could discuss okay
|
Maximum Erasure Value
|
maximum-sum-obtained-of-any-permutation
|
You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements.
Return _the **maximum score** you can get by erasing **exactly one** subarray._
An array `b` is called to be a subarray of `a` if it forms a contiguous subsequence of `a`, that is, if it is equal to `a[l],a[l+1],...,a[r]` for some `(l,r)`.
**Example 1:**
**Input:** nums = \[4,2,4,5,6\]
**Output:** 17
**Explanation:** The optimal subarray here is \[2,4,5,6\].
**Example 2:**
**Input:** nums = \[5,2,1,2,5,2,1,2,5\]
**Output:** 8
**Explanation:** The optimal subarray here is \[5,2,1\] or \[1,2,5\].
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
|
Indexes with higher frequencies should be bound with larger values
|
Array,Greedy,Sorting,Prefix Sum
|
Medium
| null |
1,680 |
hi dear folks today's lead code challenge is concatenation of consecutive binary numbers here we are given input in the form of n so there are few steps which we need to do to get into the output firstly we have two I trade from the value 1 till the value n so for example if the input is 3 we have to firstly have the values from 1 till N means three one two three will be three values then we have to find the binary representation of one will be one for two it will be 1 0 4 3 it will be 1. then we have to concatenate all these values all these binary representation starting from 1 then it will be 1 0 and at last it will be 1. now we have to convert this binary representation into a decimal form back into a decimal form how we can do this 1 into 2 raised per 0 plus 1 into 2 raised power 1 plus 0 into 2 raised power 2 plus 1 into 2 raised to power 0 1 2 3 plus 1 into 2 raised to power 4. so 2 raised power 4 is 16 plus 1 into 2 raised to the power 3 is 8 plus 0 into 2 raised to the power 2 is 4 plus 1 into 2 raised to the power 1 is 2 plus 1 into 2 raised by 0 is 1 it will be sixteen plus eight plus zero Plus 2 plus 1 which is equals to 27 and that's the output also in the lead code problem it's given that we have to return the result as modulus of 10 raised per 9 plus 7. so it will be 27 modulus of 10 raised power 9 which will be 8 zeros plus seven so this will be the output here so here the output will be 27. so I have done this in a way uh the time complexity is o n where n represents the input value and the space complexity is o1 so we are not using any extra space let's quickly move to the solution part this is a very simple approach quite easy and the time complexity is also oh and space complexity is open as we are not using any extra space here I have taken one into a resultant variable then I am iterating from 2 till the value of n then as a first step I am calculating the number of digits in a binary representation of I for example at some point the value of I is 8 its binary representation will be I a one zero and one zero is having how many digits 3. now we will shift res to the right by how many digits till L why we require this because we need to append the I at the end let's do dry run so for example we are having a value of n is equals to 3 for first and res will be having value 1 we are iterating from 2 till 3 for first iteration value of I will be 2 its binary representation will be 1 0 and value of L will be 2. now res existing value is 1 and we need to shift right shift res by how many values 2 so it will be 1 0 plus we need to append to at the end as well so it will be binary representation of 2 is 1 0 it will be more like this one zero and three so like this it will work and for the second iteration the value of I will be 3 its binary representation will be one value of L will be 2 now we need to shift this res by 2. so that we can make space for this one at the end so we are shifting this by two plus one or it will be one zero plus one and it will be 1 0 1 and 1. so that will be the value of res and its binary representation will be 27. so I have submitted this code as well so it's accepted that's it for this part thank you so much for watching this video
|
Concatenation of Consecutive Binary Numbers
|
count-all-possible-routes
|
Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation: ** "1 " in binary corresponds to the decimal value 1.
**Example 2:**
**Input:** n = 3
**Output:** 27
**Explanation:** In binary, 1, 2, and 3 corresponds to "1 ", "10 ", and "11 ".
After concatenating them, we have "11011 ", which corresponds to the decimal value 27.
**Example 3:**
**Input:** n = 12
**Output:** 505379714
**Explanation**: The concatenation results in "1101110010111011110001001101010111100 ".
The decimal value of that is 118505380540.
After modulo 109 + 7, the result is 505379714.
**Constraints:**
* `1 <= n <= 105`
|
Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles.
|
Array,Dynamic Programming,Memoization
|
Hard
| null |
643 |
hey everyone welcome back and today we will be doing another lead code problem six four three maximum average sub array one this is an easy one you are given an integer array nums consisting of n elements and an integer k find a contiguous sub array where length is equal to K and has the maximum average value and return this value any answer with the calculation error less than 10 raised to the power minus 5 will be accepted so if we have an array like this we are given K so let me just write it down here to and understand it more clearly then we are going to return the maximum uh sum first of all find the maximum sum only then we are going to uh find the maximum average so the maximum sum is going to be provided by these four elements 12 minus 5 minus 6 and 50 and these two negatives ones are going to just add them add up because they are two negatives and it will be like uh 11 their sum will be 11 so if we have it like this then thus their sum is going to be 12.7 thus their sum is going to be 12.7 thus their sum is going to be 12.7 average their sum is going to be 11 12 34 and 51 basically and now uh we have their average 12.75 so K is important if K was 2 then 12.75 so K is important if K was 2 then 12.75 so K is important if K was 2 then we would have just written 50 and alongside three yes alongside three because this is just going to return the maximum one and if we just take the average it is going to become 26.5 or something which is I think is 26.5 or something which is I think is 26.5 or something which is I think is the maximum between any two any other sub array uh having two k as 2 but we'll be taking the example he has to because we cannot find much more sub arrays in our nums because if it is for then obviously we are going to say like this is the maximum and if it is k then we are going to do some calculations and for now first of all we will making a current variable and for I in range till the length of K so taking the first K elements only and adding them up in current so for nums at I and then making a maximum which will be current and now for I in range so for I range starting from K till the length of nums then the current will be added by other ones and nums at I and remove the last one so I minus k and update our maximum will be like current uh just the maximum of current and the Maxi itself and after doing that we can just return the maximum but by also taking the average which is in this case is going to be K and that's it type end is not have length K uh yes North length K but K itself so that's it this should work now current yes okay so what is happening here if we have this array and suppose K is 2 just for an example then we are going to take the sum of the first two so the current will be like 13 and the maximum is obviously current at that point certain point then it is going to be 13 itself okay now we have you can say a slide here we just took the sum of first two then we are going to start with k so the K is 2 at K at 2 we are going to have 5 and now we will be taking the sum of these two so the sum of these two is just let me write it down so it is going to be like something like this subtract it by 1 this is going to just return 11 minus 5 and -1 -1 -1 uh six minus six and seven this is this should have returned a 7 but let me see yes taking the current value and 13 because this is you can see let me just write it down because I got confused for a second myself there so it is just like current plus okay so this is our current this is our uh nums add five which is just minor nums at I which is minus 5 and k i minus K which is 2 minus 2 which is going to be the first one and we are going to in current we are going to have 7 then we are going to take the maximum current is not you can say the greater than maximum so will not be update updating it and moving the bar again by just going forward in our for Loop including 6 and excluding 12 at this point so the current is going to be 7 and now we have 6 at I and I minus K which is going to return 1 we have this and now we have minus 18 and 7 so we will be having minus 11 in our current and this is less than maximum so will not be updating it and now we will just move the pointer not the point of the bar or you can say moving forward is not for Loop and now 50 is our at I we have 50 and sum is minus 11 so minus 11 50 and we have minus 5 which is itself is minus so we'll be just adding it so it will come like adding five adding 5 55 subtracting around it is going to become 44. and now it is greater than maximum will be updated to 44 and now just move the bar again like this so we'll be adding 3 and subtracting 6 so let me just remove 44 and on the next iteration we are going to have three so let's just add three here and subtracting 6 which is itself is negative so we'll be just adding them at basically so it is like 47 plus 6 is going to return us 53 and as we can see the sub array we can find will give us the maximum is going to be 53 which is just 50 plus 3 as like you see and we can tell things and now if we take its average by K which is just going to be 26.5 or something and that's it this is 26.5 or something and that's it this is 26.5 or something and that's it this is how things work and that's it
|
Maximum Average Subarray I
|
maximum-average-subarray-i
|
You are given an integer array `nums` consisting of `n` elements, and an integer `k`.
Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted.
**Example 1:**
**Input:** nums = \[1,12,-5,-6,50,3\], k = 4
**Output:** 12.75000
**Explanation:** Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
**Example 2:**
**Input:** nums = \[5\], k = 1
**Output:** 5.00000
**Constraints:**
* `n == nums.length`
* `1 <= k <= n <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Sliding Window
|
Easy
|
644,2211
|
24 |
welcome back today we are going to understand to delete your question and today we have given this question uh swipe two notes in the pairs right so this is the question based on the link list and we have to swap every two nodes to adjacent nodes you can say and we have to return its head as you can see we have to swipe every uh two nodes right and we have to return its head so you must solve the problem using you can say without modifying the lists right and you have to solve using uh logical things how to do that right so uh to do that there is ah many approaches right we can you can follow that right in which we will see the first approach we are going to see here is recursive approach and then we will going to see the another approach that is iterative approach okay so you can try by your own right so you can pause this video and you can try by your own and then we can go ahead right so before that let's understand the uh you can say example what example is saying so example first is saying that we have given these nodes right so we have to every two adjacent node we have to take right so the for this one the adjacent node is 2 right so this will go here and this will go here like this so as you can see in the resulting one two is coming first right and then one is coming again and there is another one that is we have this node and this node so this should go here and this should go where here and it is coming like this right as you can see so this is the resulting ah you can say link list we have in which we have to return its nodes and you will see the output like this 2 1 4 3 and previously it was one two three four right like this and if you coming if you want to see the another part let me go down yeah another example you can say so if there is null we don't have anything we will return a null but if you have any element into that so there is no adjacent so we will return one only right so these are the examples we have given right and uh to implement that let's go to the coding section here and we'll try to do the coding here okay so before understanding uh let me tell you one thing okay so uh we have this question right and to do solve that right the problem doesn't ask us to uh you can say for the entire reversal of the linked list right as you can see this is the first part for this one this is the second part you can say so after each node right we have to what we have to Traverse its uh adjacent node uh we have to save the adjacent node only not the hall or you can say entire reversal we have to do right that doesn't ask the problem right so it rather asking us to save every two uh adjacent notes of the linked list starting at the very first node as you can see here as one and then two it is moving like that so what we have let's suppose we have given a this note right and we have to do the swiping like this right so what we can do here right so now the basic thing what we can do is uh to reach the end of the linked list in the step using 2D cursor right so the first recursion what we can do let's suppose I am going to write here let's suppose we have given uh that is the first node we have given and there is another is a point right so we know that each node contains its data and its pointer right so this is if this is your data and this is a pointer right so this pointer connects to another node that is we can say like there is a two Azure data and we have another as a point right and it will connect to another like three we have and there is another is a pointer so this going to connect like this means it will look like this only right so now the next element is nothing but what this comes to null next pointer we don't have so this is null right as you can see let's suppose this original one right and if you want to do the swapping thing right so let's suppose uh we are starting from here so this is nothing but our head right so ah let me change the color so you will understand a little bit very good so your you have here the head you are starting with here and after the swapping right what we have to do actually so what we are going to do we have to take a jump from here to here okay like this just for understanding okay and then uh you can take a jump from here to here like that means two jump you can do or either we can take one jump from here to here and then another jump we have to take from uh the any element that we have means from here to the next one like this right so this is the better like we can take like this from here and then we can go to the next one right oh yeah this is the best thing because we have to escape one we have to skip one okay yeah it's better so what we can do like uh we will try to uh reach the end of the link list in the step of using two recursion right so in the first recursion we'll go from here to here and then we will go to here right while the back tracking the nodes can be swept like how we'll do that so if initially what we have one have and we have two nodes right like this so this is connected with another one this one and this is connected with like this we have connected with another one okay now we have three and four right so what I will do I have swept this one like this okay and this is going to uh with now three and this is nothing but connecting with the null we have null here right so what we are doing here we are swapping here right this part we have swept to here from here to we have swept to here right like this means here we are doing a backtrack what we are doing back tracking we are doing here okay and here what we are doing recursive recourse Audi cost you can say because okay so we are here we are doing recursing rights means to reach at the end of the linked list what we will do first we will do uh two recursion and then we will do backtracking to do the uh to do the swapping right the backtracking the notes that can be swept right so two steps we will do so in every function we call write and we take out two nodes which would be the Swap and the remaining nodes are passed to the next recursive call right so the reason we are adopting a recursive approach here is because uh we have a sub list of original list right and that would be uh still be a linked list and hence it would be we adapt to our recursive strategy right so assuming that the recursion would uh return the swap remaining element list of the nodes and we just swap the current two nodes and we will attach the remaining list we will get the recursion of the two pairs it means what I am trying to say here let's suppose uh I am going to write here okay so first of all let's suppose we have two nodes right so I'll take one node here like this and this is connected with another node that we have data to and we have this pointer and this is nothing but what it is connected with there is a remaining I'm just telling out this your remaining list so this is a list where we have our list remaining right so we will connect with this one or either if will be marked like this so it will look like this is the remaining list that we are going to connect this one okay now so this is your original list right what is you have this is your original list okay now what we will do the original list we are going to swap right so every call is responsible for swapping the two nodes the remaining swept list comes from the next recursion right so how we'll do that means we will after swiping this one this will come here and the pointer is here it will point to here and this is the pointer like this will become and it will look like this one I am trying to say this one okay and this is connecting with this one right now this is the part we are talking about so this uh this is the original list we are going to uh Swap and this will connect with the what remaining swept list like this right it is pointing to here like this or I can point like this okay like this so this is your remaining thing that we have already seen and this is the pointing thing we have right so here what we are doing actually so for every call right what we are doing we are swapping two nodes right and the remaining swept list that is coming from uh the next recursion this will come from the next recursion right and that way we are going to connect it right so ah like this we will do our uh you can say swiping with the two current nodes and we will attach the remaining list and we will get from the recursion of the two swap appears each time right so what we will do we will start from the recursion of the head let's suppose we are going to the code section and then we will try to do I'll write the code then you will understand little bit so as you know this is the linked list we have linked this is the node we have node class and you know each node class will contain value and its next as a pointer it will call and the rest of the it you can say as a Constructor over here so let me hide this one ok so from here what we will do we are going to see the code and then we will do the implementation so we'll understand okay so first of all here what we will do we will start the recursion from the head of the node of the original linked list and to do that what we should do give me one second we should start uh first of all let's check first right first we will check what uh if the list has no node right and Order uh of the node has ah one node left there is only one node as you can see right let's suppose we have the head that we are passing and if it is null just for understanding if this is null then what we will do will uh one more thing we can do or we can say if head is equal to null and head dot next so that next time we are not going to call head.next right and this should call head.next right and this should call head.next right and this should also null in both case what we will do will return here nothing but our head you are not going to do anything right so this is your first call means we will start recording with the head of the original load node and then we will do the swapping right to find the swapping what we have to do we have to find two nodes right that node two is web right to two swept two step two nodes right we what we have to do we have to find the ah this is the node right so we can get the node from here so let's suppose I am going to say this is our node one right and this will come from what a head sorry this is nothing but I will start from the head okay another I will take what the second node I'll put here and this is our node 2 and that will come from what head Dot next right if we'll do head.next so we next right if we'll do head.next so we next right if we'll do head.next so we two node we have right and if head or head dot next is now we will returning head we are not doing anything we will not come to here right now what we should do now so once our two nodes are there we have to swap right and to swap that what we have to do we have to swap the node right to swap that what we have to do we will do node one just for understanding node one dot uh we'll do next node dot node one dot next equal to nothing whatever we already have this function so we are doing a recursive call so we have to call this one and this is nothing but what I will pass the first will pass the node two here node two will start from here head dot next we are calling right so if we have not the second node.next we'll store where the second node.next we'll store where the second node.next we'll store where the we can we are iterating so while I trading we have to take two one we have to skip and to do that node two dot next we will do and we'll store the node one dot next correct and on the Node two dot next what we will do like this what we will do we'll add what our node one like this so we have a skip one right now sorry we have to save one right that is that we have done already now the head is the second node right so now the head is the second node right like this we can say and to do that what we have to do we have to return what node two that's done so let's try and run this program let's submit so this is working right now the in this way give me one second and to do that you can see here right we are going each time all the nodes if we have given a list of n nodes just for understanding this is a node right so if there are nodes connected with n nodes right just for understanding if there is node means we are traversing all these nodes right we are going with all nodes and that's why the time complexity become o of n in this case right and here we are taking two nodes right here right so each time what we are doing we are traversing each time right all the nodes okay so once you have all these nodes right so the utilization as you can see here right we are going with all the nodes we are storing here right so in the recursive stack we will create one stack right so first will come uh the node one and it will become a stack right so this stack will take what how many nodes and nodes it will come over no dot next total node whatever we have that will come each time here all the nodes on this stack and that's why a space complexity also become of n okay so this is the thing we have to do the uh you can say uh in the recursive way we will find our time complexity and space complexity okay and we will do the Hands-On okay so if you we will do the Hands-On okay so if you we will do the Hands-On okay so if you want the iterative way please ping me in the comment box so I will create one uh iterative way approach and I will uh go through all the codes okay thank you guys thank you for watching this if you like this video please hit subscribe this channel so that you will get more notification uh for upcoming videos thank you guys thank you for watching
|
Swap Nodes in Pairs
|
swap-nodes-in-pairs
|
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[2,1,4,3\]
**Example 2:**
**Input:** head = \[\]
**Output:** \[\]
**Example 3:**
**Input:** head = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 100]`.
* `0 <= Node.val <= 100`
| null |
Linked List,Recursion
|
Medium
|
25,528
|
419 |
okay we are starting with Lee code number 419 or battleships on a board given an end times n Matrix board where each cell is a battleship X or empty period return the number of battleships on the board Battleship can only be placed horizontally or vertically on the board in other words they could be made up of the shape one times K one row K columns or k times 1 K row is one column where K can be of any size at least one horizontal or vertical cell separates between the two battleships so basically this whole paragraph the second paragraph is saying that we could only have battleships that are horizontal like this or vertical like this what it's also saying is that we can't have two battleships adjacent to each other there will always be a column or a row which separates them so in this case we'll never have a battleship like this right so there won't be two battleships that's next to each other like this will always be one Battleship so our main goal is to scan through this whole entire Matrix and find every single Battleship on the board count them up and return it in the end okay so this is my Java approach and this approach I use DFS or depth first search instead of BFS you can use bro both bread first search and that first search but I feel like Dev first search is much easier for this problem especially if your first learning DFS this is an easy problem to attack just to help introduce the basic concepts of DFS so what we do first is that we declare an intervariable shapes which keeps track of the amount of ships we are going to return in the end which so that's our main variable that we need to keep track of and my Approach is a o of MN m is the number of rows and N is the number of columns approach which means we always go through the Matrix only once using DFS so these two for Loops here just go through each index of the array right so we start from the first zero so starting from the first we are here right we're at zero so starting from 0 we see that the character in that index is an X and since it is at X we go through the function DFS we pass in the zero we pass in another zero or the row in the column and then the board the main board which was passed into us and then we increment the number of ships but we'll see why after DFS we do that so once we're in DFS we get the row we get the column and we get the board remember in Java matrixes are passed by reference so anything we do to board and this function will change it in this function up here the first thing we're going to do is go through this if statement and we check the edge cases of the row and column so if row is greater than or equal to zero if column is greater than or equal to zero if rho is less than the board length if column is less than the board length and if the character at that particular index is a battleship and if it is a battleship then we go through what is under the if statement so unusual DFS approaches we use a visited Boolean Matrix of the same size but in this case we could change the ships in this Matrix to show that we already visited it right so since we know that this right here is an X right now and we only visit here and here if it is a battleship or if it is an X we could just change it to a period to know that we already visited it so after we change this to a period or let's say an open c we check above one we go below one we go to the right one and we go to the left one so basically we're seeing all around the x that we found to see if there's any more x's and if there are then we change that to a period also so again we go above one but since that's out of bounds we don't do anything we go below one that is in balance and that is less than the board length but this is not a battleship as it says here since this is a period so we don't go into if statement we go to the right one and that's the same thing every Edge case is satisfied except that it's a battleship so we don't go in the if statement and then next we go to the left one but as you could see it's off the board which means it is in the C so in this case we only have one Battleship right and the battleship is only of length one there was nothing to the right below it above it or to the left right and we keep doing that for every single X on the board so now we're back to this for Loop up here and we're going to increment each index remember so now we are here in this part of the sea but this isn't an X right so we keep going we're now in this part of the C this isn't an X but now we go to the right one and that is an X and basically our DFS approach will make every part of that ship a c right so in our DFS approach we start here we check every direction from it so up to the right down and to the left so since to the left is to the C we don't do anything above and to the right or off the board we don't do anything below is an X so it satisfies every Edge case in our if statement so we do take this out and we put it as a period instead of an X now we do the same thing here we go down one we go to the right one and we go to the left one and as we could see there's only one way we could get to then X and that's down and we take that out also and that is where we stop because there's no more X's anywhere around it and remember once we're at this x we can't go up again right because once we go up through DFS row plus one this x right here is actually we change it to a period remember so we can't go up one and it will not satisfy this part of the if statement board row column equals x because it's not a battleship anymore since we already know there was a part of the ship there and we change it to the C so now going through the for Loop we are now at this Index right here which is one zero now we are one two since these are all part of the C now we are one three right but remember this is passed by reference so whatever we did to board right here it will change the board for the whole entire class so now this is actually not an X it is the C so we will just pass by it like it's any other part of the C we go here and now as you can see same deal with this x right here this is part of the C now right since we already visited it so now we go through each index and we are finally at the end and our ships incremented twice right because we found two x's we found this x right here and that is our two shapes which we return at the end
|
Battleships in a Board
|
battleships-in-a-board
|
Given an `m x n` matrix `board` where each cell is a battleship `'X'` or empty `'.'`, return _the number of the **battleships** on_ `board`.
**Battleships** can only be placed horizontally or vertically on `board`. In other words, they can only be made of the shape `1 x k` (`1` row, `k` columns) or `k x 1` (`k` rows, `1` column), where `k` can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).
**Example 1:**
**Input:** board = \[\[ "X ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\]\]
**Output:** 2
**Example 2:**
**Input:** board = \[\[ ". "\]\]
**Output:** 0
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is either `'.'` or `'X'`.
**Follow up:** Could you do it in one-pass, using only `O(1)` extra memory and without modifying the values `board`?
| null |
Array,Depth-First Search,Matrix
|
Medium
| null |
112 |
okay so leak code question 112 path sum given the root of a binary tree and an integer target sum return true if the tree is a root to leaf path such that adding up all the values along the path equals target sum a leaf is a node with no children so we have an example here of a tree and they've highlighted the root or the path from root to leaf node that adds up to give the target sum so i wouldn't say this is an easy question in the code this is probably more of a medium but the whole idea behind it is pretty straightforward so we just need to find a path in this tree that equals to the target sum that they have provided so we're given the root and we're given the target sum and we need to work out a path that adds up to target sum so let's look at a potential solution as soon as we've got a tree here and we need to go from root to leaf it would either be dfs or bfs so in this case we're going to choose the recursive dfs solution so we're going to be using recursion and with recursion we have base cases and we also have a recurrence relation now the base case is what pops yourself out the recursive function because otherwise we'll enter into an infinite loop and then the recurrence relation is what takes you one step closer to the base case through each iteration so in this just imagine like as a sanity check the tree is null or there is no value within the tree what are we going to be returning well in the question it asks you to return a boolean so we're going to be returning false so if root is equal to null or return false so that is one base case sorted now let's think about say the recurrence relation so within this tree what do we need to pass down so at this level what do we need to pass down to this level and this level to this level in order to work out whether the sum is equal to the target well we need to pass down the current sum right so let's create a variable called current sum we'll start off at zero and at each stage each node will grab the value from the node and we'll add it to current sum so at this level current sum is going to be five we'll go down the left tree at this level it's going to be 9 at this level it's going to be 20 and at this level it's going to be 27 at this point we've reached the end we have a left child and a right child they're both equal to null so now we can see that we're at a leaf node and we can create some logic or recurrence relation to decide whether we've reached our target so at this point if the left child is null and the right child is null we can check to see whether current sum at this point is 27 is equal to target and if it is we just return true and if it isn't we return false so what's going to happen here is 27 does not equal 22 so we're going to return back up false and then we're going to check down the right side of the path because 11 has a right child we haven't checked yet and at this point current sum is going to equal 22 so we can update 22 here we can see that it's a leaf node because it's pointing to both nulls for left and right child so we check is current some equal to target yes it is so we can return up true now here's the tricky part we have to decide at this point what to return false or true well we're just looking to see if there's one potential solution right so we can just return false or true so this is going to return true because one of them is true right so at this point what we're going to do is we're going to say if left or right is equal to true then return true we have left which is false we have right which is true so this is ultimately going to return true and then it's going to return trip here and then we're going to check down the right side so 5 at this point 13 plus 13 is 26 so 26 here we've reached the leaf node because the left and right child are pointing to null we can see that 26 is greater than 22 so we're going to be returning back false then we can check the right side so 13 plus 4 17 plus 1 is 18. we've reached the end of this we found the leaf node 18 is not equal to 22 so we can return false here we check at this point if the left tree or the right subtree are passing back true they are not so we're going to return false and lastly we need to check up here is the left tree or the right tree returning true yes it is so we can return true so that is how you'd solve this solution in terms of time and space complexity time complexity is o n because we need to traverse the entire tree so we need to go to each and every node so space is also equal to o of n and the reason for this is say we have a really say we have a completely unbalanced tree so the tree looks something like this each node has only one child node so the recursion call would occur n times so basically the height of the tree and therefore space is of n so let's create our recursive function we're going to pass in root and current sum i'm going to call it at the end passing 0 as the current sum because we're going to start off at 0. carry out sanity check so if root is equal to null term false update current sum so current sum is equal to current sum plus root.val plus root.val plus root.val simple way to do this is to just put plus equal then we need to do the check to see if it's a leaf node so if root dot left is null and root.right is also dot left is null and root.right is also dot left is null and root.right is also null and we need to return where current sum equal to target sum so here this is going to return true when current sum is equal to target sum and here we need to pass back up the tree whether the left side or the right side is true and this is where the recursion will occur so return recurs we're going to recurse on the left side current sum and it's going to check whether that is going to pass back true and we also need to recurse on the right side and check whether that returns true okay and then we can check to see if this is correct it's been accepted submit it and there you have it
|
Path Sum
|
path-sum
|
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22
**Output:** true
**Explanation:** The root-to-leaf path with the target sum is shown.
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** false
**Explanation:** There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
**Example 3:**
**Input:** root = \[\], targetSum = 0
**Output:** false
**Explanation:** Since the tree is empty, there are no root-to-leaf paths.
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
113,124,129,437,666
|
232 |
hi everyone welcome back to the channel and today we solve e code daily challenge problem number 232 Implement Q using Stacks so outside it's one of the classic problems and uh it you know it this question is asked many of times in very famous company interviews and uh we're going to look into it today so first we'll check out the problem statement then we'll check out the approach which you're going to use and towards the end we'll see the code as well so starting with the problem statement it is uh very straight up uh so we have to basically Implement a queue using Stacks okay so uh Implement a first in first out que using only two stacks so basically uh in Q we use fif strategy fif stands for first in first out and on the other hand in stack we use Leo strategy last in first out okay so we have to implement these four methods push Peak pop and empty and they have given the uh the definition for each of the methods with push we will be pushing a new element to the back of the queue with pop we will remove the element from the front of the queue and return it with Peak we will just uh see what is the element at the front of the queue and empty will basically check if we have a empty Q or not okay you must only use standard operation okay I think uh these are basic notes and they have also given example which we'll be using in our case as well so let's go to the approach which we're going to use okay so starting with the example so this is the exact same uh example which they have taken uh in the question itself so first uh we'll have to know this Q follows first in first out strategy okay on the other hand Stacks follow last in first out okay so what do first in first out means for example in this case if one is pushed first when we'll try to you know uh do the pop on it will give one first okay let's just consider this one in fact so we have one and two and n q and one was inserted first or before two so when we'll pop the element one will be popped okay but in Stacks if this was exact same condition uh and we do the pop it will pop two okay not one it will pop two so in stack the element entered the stack later will be uh eliminated first in Q is the other way around okay so that is exactly what we're going to use and uh you know it's just a classic problem in and uh the idea behind solving in this is you need to have two stacks okay to implement a queue using Stacks you need to have two stacks okay let's name them S1 and S2 so for push what we will do we will first uh transfer all the elements from S1 to S2 okay all the elements from top to bottom and then we will add our element on top of S1 okay after adding the element we will again take back all the elements from S2 to S1 okay so this is how we uh do pushing uh push operation so for push let me write down here shift okay uh I should H so for push we will shift all elements from S1 to S2 add element in S1 then shift all elements from S2 to S1 okay these will be the three steps for a push operation so in this case what it will be for example we have S1 and S2 and uh like your S1 will be treated as a q okay so whenever you'll have to uh say uh which stack is your Q or is acting as a q it will be S1 so we didn't have any uh element in S1 at the moment so we don't have to transfer anything on S2 and we can simply add one in it okay now comes push two again okay and this is the situation at the moment we have one in S1 S2 is empty okay then what we will do we will first transfer all elements from S1 to S2 okay now we will add the new element on S1 this is our S2 and at the end we will transfer the element from S2 to S1 again okay now comes Peak uh with Peak we basically just had to check what the element at the front of Q so to do that what you can do you can just simply check for Peak check element at index minus1 minus one basically represents the last element in the array okay and pop for pop uh we just have to Simply do the pop operation and uh we will simply use the do pop method to do so and when you'll do pop sorry I should do this H when we peaked everything remained same okay now comes the pop operation pop will basically remove your element from the top and it will give you the element okay and the only element remain is two now and empty will basically tell if uh our Q is empty or not so as you can see we have a element in S1 so we will say no false okay for popping we will simply use pop method now let's check out the uh code for the same so if you see here what I have done I have defined or initialized two stacks stack one stack two okay now at the time of push operation what we are doing we are basically transferring all the elements to stack two from stack one okay so pop will basically pick uh elements from stack one and will uh you know add in stack two then we added the new element in stack one and we again transferred all the elements from stack two to stack one next comes Pop as I said like we'll simply use the pop method to do so next is Peak with Peak we wanted to check the last element added in the stack so we can have minus1 uh for the last index and that's what we are doing over here and for empty we are just checking if the length of Stack one is zero or not if it is we will return true otherwise we'll return false so let's check out the test cases so as you can see the test case got clear let's for further evaluation now and the solution also got accepted and yeah this was the solution guys thanks again for watching all the video stay tuned with uping ones don't forget to like the video and subscribe to the channel thank you
|
Implement Queue using Stacks
|
implement-queue-using-stacks
|
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).
Implement the `MyQueue` class:
* `void push(int x)` Pushes element x to the back of the queue.
* `int pop()` Removes the element from the front of the queue and returns it.
* `int peek()` Returns the element at the front of the queue.
* `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.
* Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
**Example 1:**
**Input**
\[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 1, 1, false\]
**Explanation**
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: \[1\]
myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is \[2\]
myQueue.empty(); // return false
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`.
* All the calls to `pop` and `peek` are valid.
**Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
| null |
Stack,Design,Queue
|
Easy
|
225
|
138 |
Ajay Ko Hands Free Mode Dynasty Site From Falling End Inside today's video we will solve this problem, I have filled it earlier this year, what will we do inside this problem, we will copy the link list, we have to TRP but it is within the end appointed s. So you will have some life points left, from that you have to copy the lace. Okay, so this is the solution I told earlier, which was Khurram at this time, I used the helmet on it, so I was using some extra space. To solve this problem, today I am solving this problem twice, but this time I will not switch to any actress, that means I will make some notification in the same link playlist and when I solve it, then see what is the problem. The problem is that you will get a single English with additional random point between some point to any mode Hindi list and tap means someone point that channel also and anyone else and written update scorpio play list for more details watch video ok so here you There is a next point, a, there is a random point, a reminder, this is a cup of Chinese tea, let's come here, let's get to the point, then direct, you add yourself a little, if everything looks right, then there is one, that's why the list is sprinkled, now that's why I remain immersed inside as if Vansh's next point is appointing you but its random pointer is also appointing you, your next point is appointing free but its random point. At one point means anyone to anyone randomly. Point do 320 points Kara for direct 76.4 This is 2016 66 This for direct 76.4 This is 2016 66 This for direct 76.4 This is 2016 66 This point I used to appoint points 126 Here point This point I used to appoint points 126 Here Jeevan This point of random eight is appointing someone 1014 is appointing And toe Agyeya ne appointed this Anyone randomly appoints someone and I don't want to take out its D copy and then I don't bother to edit the copy. Look, if I talk about the copy given in someone's name, then I do n't want to find someone else who looks like me. There should be two meanings of list last and the second list should be from disease. Basically this is the photo copy type. You have the original content and you also have its photo copy. I want another list which looks exactly like this but their addresses should be different. Like its address is of cases but UK, it is of some kind, it is of one, it means any MS Word, it has RAM, it has 24k, then it accepts it as per its stomach, here I accepted it as level, here it is accepted as toll, here it is accepted as husband's owner. This list is the address, it will become a pair of notes, it is tied somewhere, nor I, it must also have some address, so the address is accepted, now the gender list is the head of the ambulance, life, now I have to do something so that it becomes a deep copy of it. Okay, then let's do something, so what I am going to do here inside this lead is that first of all I am going to traverse the length Vishwakarma travels toe and add a node in the middle of it, meaning a node in the middle of these English, see those who do JS. What is going to happen with that, then they themselves, first of all, what will I do, this is mine, so I put my one here, point it named C, on the counter named C, this is hunter named forward, okay so that I get the backup. My upcoming back cover is what I should have. Now I made another note that looks like this. There may be another address at another address, like a gram. For the moment, I made one that looks like this here in a different color. Along with this, create another note and let's assume its address is 41k, put one in it. Okay, so how do I improve the numbers here I have put one and then what to do, put this new note next to the current one and add this new note. Attached forward next to the note and where did the current go? Direct forward, now this current of mine came here, share mine here, forward will come here, then do the same thing again. What to do first of all, create a new note, give name. Attached it from its next, attached it from its next and again bring the current forward, in case any other address will be created, you can add any, it is important, it means like I said its address is 41k, it is 31k on the floor like this. There is some address, so I made a note here with the name 'Free', ' I made a note here with the name 'Free', ' I made a note here with the name 'Free', ' Tripartite' it in 'Whose Next', ' Tripartite' it in 'Whose Next', ' Tripartite' it in 'Whose Next', ' Attached' it in 'His Next' and kept doing it in the work, 'It brought the current Attached' it in 'His Next' and kept doing it in the work, 'It brought the current Attached' it in 'His Next' and kept doing it in the work, 'It brought the current weather, brought the forward to home, brought it home, then like this, it will point to this. I will appoint here, I will create the name ignore here, I will create the name of note here and the current forward will go forward, now this thing will go to ₹ 15, so this will forward, now this thing will go to ₹ 15, so this will forward, now this thing will go to ₹ 15, so this will prepare my entire list, so I will quickly prepare it first and do this whole front by running the same procedure. It will take a little time, so you have to do the password, come here but on time, I have stretched it, attached it to this and then current forward, then taken it forward, then again the same work, we will make another note here and tap here. And we will put it, we will set it, we will test it and the current will be opened, forward here, then here I will make a note of 2016 on this, set a school on it and touch it with tap, that's it, everyone has address seats of 80's but it is broken. Gaya 1's is also done with a pipe of 123's 27k A's of nine and there is President for's reproduction somewhere and it arrived so what did I do in this way nothing will create notes so this is my new note created here Now the new notes have been made here, so now they are useful here. Now look, I have got the notes have come normal, so why did I have to create the result inside the length belt, that was the mode, I did inside it. After setting these lists, my work is done, now my next work is to set their random points inside this, so see how I am going to set the random points, now see Vanshraj Random, whatever it is, appoint it to. If you are doing this, then this one broken random which I have made with blue color will also be appointed to two blue colored ones. If you are appointing another one, then this blue colored broken random will also be appointed to two blue colored ones. The right thing to do is to stay away from the right one, a lot of factories are running and if this has happened inside the green colored one, then there must be a Bluetooth center too, then one is randomly pointing you, then one will randomly point the blue colored one. Blue color 2 is absolutely correct, how do I extract it in this thing? First of all, let's make this thing, it is so much that I have not done it. Please, if you want to use it, then first do it, note it down, then in the next step, set the randoms. Will do OK, now let's go, so let's see how many pieces I cover at one time, then write here static boiled public static that is going to be and here we will copy the list, I am copying the list, okay I am loot, you will get a list node, one head, then I will have to make a current deposit on the upper side, I will have to run the coils for how long till my current does not become equal to null and as soon as I come, what is the first thing I have to do? You should make a friend who will be the current one's next. The next task was to create a new note, what data should you put in it. Dot bell, after that you had to work, you had to do no report in the current's next node's next. I had to attach the forward and after doing this work, the current had to be freed. When the work is completed near the forward, then my list will fall in love. Is it the main stop? Now who did this? Got the list completely copied. The thing I have written here is Simreli Scorpio, that is, this strat has come inside which I had created it will also be suggested, it has become state, now I will do it here, I am creating another loop, the name of which is public static became oil, a puppy random point of Madam, what will the pointers do inside this, here now the next 300 codes are going to be there in which I am going to break this random pontifical here at 3020, how to break the pizza beach, first of all thought of taking notes on the topic and then think what to do by making profit. Lia, now just copy the end and want to copy, if you notice one thing, as we talk about time in Britain, the tender which is a random point is appointing four. These people see it as appointing a random point of time. I am fine ok so this one tank will point there and 1000 fab ok no let's run it lightly only this point will point Parmesan thing how to do here I can reach my random point yes very easily got the current trend scare me point And will I get my trend part from random? If I want to get my random point then I can get it from whom should I dot whatever its name is I am random yes I got it I got the front point ok if I have got the doctor yesterday then my next one Nine current's next9 is that tell my copy model Look carefully every time my copy is note Every time it is so it means my current's next karma Who will be chronic's next reason Dum current's next meaning 1010's random That tennis star is going to be random If the tank is random Thakur, then my friend's next random person will become the next random one, but my next number will also be a copy note, it means what should I write to you that the one I had selected as my random pointer is going to be next in these two lines. Assembly group Bashar is one, then it should not happen that the money goes out, if it is not there after 9 and water, then put that check, till now I have told you this first, then we will put the check here, if fashion and random do not return, then sit here, if you don't want to do this. Let's run this, let's go, then I write here that if it is random, then one friend remedies to correct, then next one will be random, the next sound of my random will be check to be absolutely correct with the delivators, you write here in red color. Understand that this has been discussed, okay, if you break, one is random, then two's next is due to come to connect, meaning the blue one is the one with the tool, two is the one with Damru, the next one is random, according to me, I mean, I am talking about the green color. I am doing my random connect i.e. one is ok then I random connect i.e. one is ok then I random connect i.e. one is ok then I went to three, I reached free, how am I on free foot, what to do by coming here and works of neurons, Sal Karan and Mad Max, if you pick up this phone here on Zucker and WhatsApp, then in this way Travels from free came ok free ka random hai tu prithvi ke next program kaun banega and vent on random ka next ko pura pokaran mein 17641 more correct so for ke next i.e. blue wale former ke next i.e. blue wale former ke next i.e. blue wale former program kaun banega drop and ka current less Here see seven six more current metro train numbers i.e. metro train numbers i.e. metro train numbers i.e. who will be the random one for the blue colored four randomly connect me 76.69 blue colored front piece, get this 76.69 blue colored front piece, get this 76.69 blue colored front piece, get this billed 786 i.e. it will point that billed 786 i.e. it will point that billed 786 i.e. it will point that A76 is ok, a stranger eighth random handle So we have to do something, we will tag it as tap, this too tap is 110 random, 110 is the reason for four it means the next current in the tank will be reduced, the random one whom I have to dip will go to the next point of my phone, somehow this one will point fat. This point will do 1 See all our alarms are set then what to do to set them randomly Ignorance Film Story The story always remains there and never changes, you just need to dry land on your printer properly if you have done it properly Jointed, then everything goes, they are not equal to nothing. Now what will you do here, first of all I should measure, take out random points, list mode, take out your friend, then that will be my friend out, a friend is perfect that if a israndom, that is not equal. It is two taps, if it is such a thing then why not I? If my friend does remedies then it means if he does handmade sheets then do dot net current collection then my copy and who will become his random one, if the random one of the money is taken out then he will become the next one in his next. A perfect front of shopping and study of random will run on the next of equal to current and sugar this is my copy also has been passed random now see here I have passed my roll number 10th so my friend border should be open here Now what do I have to think here? Now I have to think here that my friends should copy those points and how should I express my original minister in it. If I somehow extract the original list, then my work will be done. It will be done and it will be correct, then thinking about how to do this, the first point of this work has been copied, the reminder has been copied, it straightens me in it, I have a big head, if I do this, that too in one go and make that last 15 minutes. Let's make it, maybe it will be like you are giving me drink like Aslam - will be like you are giving me drink like Aslam - will be like you are giving me drink like Aslam - etc. So make this Dominor, here's my previous one. Okay, so did I Sharma put a side connect in the next one of the previous one. Please put a helping hand in the next one for current account. Okay, absolutely correct. And in the next to the current, the network of the next to the current became the current collector and next to it, so basically what should I do here, you broke this link, I connected this link back to it and then I smiled further to the current. In the same way, I picked up the previous one and freed it further. From now on, what were the things done by the corporation, connect the current in the next part of the previous one, attach the current connect in the next part of the previous one and started well, what to do now, in the next part of the current one. Attach the map of the current and take the perfect current forward as well. Take the previous one forward. It seemed to me that I attached the current connect in the next to the previous one. Well, the balance was broken that it became true and in the next to the current one, the current was connected. By doing next, 250 is placed on the tile and current then forward and previous again my predestination and then connect the current then this one is point A and it is pointing and if we attach the next to the current to the next of the current then this one point. But it is pointing to it and then forwarded both of them to the end here to the previous here then again to the current next. What we will do first of all is we will test some lines. Type in the following characteristics in it. Okay, we will do that in the next. If you are not able to do the next method then the limit will go, try thinking that I will do the next in the friend's next and destroyed it, then I have connected the street and now I have written that we can attach in the previous's next, I did not do that. Do me line thinking salami hai before what will happen in the next of the front in the next and 230 in the next of the current were in the next of the current correct opposite they are ahead and then again show the setting that it will point to the next of the current and it will point to That the next note of Karan will go from this tree to do these things and like this my current will be curved and here the previous here and then what will it do then this note will move from here and will appoint this and then again the current will be curved We will go create here and from here, what will happen is that eventually this one will point from this and this one will fight with the percentage and as soon as my current person reaches there, that means the previous one will come here and the current one will come here. If it is on normal like igneous then it means that the release company has been tagged so complex that both of them were able to point out that it is very easy, it has turned out to be too much, so what was my work to do after the copy, I have to do it public here. Steak boil week returning otherwise list node stretched atattoo base dippy past copy saved does 16 edit topics ready on i made list note by doing my add 40 and as soon as come i created list node and i am naming it You named academic tummy and created new list node minus one I list is not previous because appoint karega dum hai ko quilon chalay hai aur kab tak chale brother guys until my karan is not equal to null okay then here one Make current only, this is the point, the biggest task to be done was to match the current next to the previous one, the next task after that was to attach the next to the current to the next to the previous one. Removed the next and termed the current as the poems of the current. What does he do? Finally made in English. And a tractor, where will I get my tab? By the way, where will I get my deed? From Redmi's act and this is here, Straight Deepti gives me my If we can get it, then what will you feed us first? First of all, play your list. The first thing you should do as soon as you get the phone is to copy the list. It is okay, the list is copied, I have to copy it, random pointers, seats are copied, random points, next. After this work is done, there is an alarm, get your heart copy returned from here, that my friend, please correct it that after doing it from here, deposit on my topic will be returned from here, run it once and see the word, ok, then list. Node node that can't find is 99. Write the word phone here in the check list. It's okay that your other person's year is a picture of a word thing, Jaunpur, it is coming right, submit it and see, it was okay, it is being submitted. Now just make one of these, it checks whether the time and space clipping is done, so I am only talking about whom, this list came in front of me, look at one thing carefully, how much expressbys have I done here, I ask for something special. I will wait a little, here I have taken the space complexity, I have listened to it on one click access because I had asked for the same to happen, that is why it has taken so much time, I have completed all their tension ma Darpan, here again I have taken the space one time How much space was taken here, how much overtime was taken, how much time was spent on the net, how much cow time was spent in free and wet, which is equal to one, so this is my time and space for lips, pin number, then the previous question. Space was taken inside, you did not take it here without the fact that we solved this problem. I hope you liked this video. If you liked the video, then please like this video as much as possible to your friends. If you have come to the channel for the first time then subscribe, you will get the song in the next video, Ajay.
|
Copy List with Random Pointer
|
copy-list-with-random-pointer
|
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.
Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.
For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.
Return _the head of the copied linked list_.
The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:
* `val`: an integer representing `Node.val`
* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.
Your code will **only** be given the `head` of the original linked list.
**Example 1:**
**Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Example 2:**
**Input:** head = \[\[1,1\],\[2,1\]\]
**Output:** \[\[1,1\],\[2,1\]\]
**Example 3:**
**Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\]
**Output:** \[\[3,null\],\[3,0\],\[3,null\]\]
**Constraints:**
* `0 <= n <= 1000`
* `-104 <= Node.val <= 104`
* `Node.random` is `null` or is pointing to some node in the linked list.
|
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list.
For e.g.
Old List: A --> B --> C --> D
InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
|
Hash Table,Linked List
|
Medium
|
133,1624,1634
|
1,463 |
Jhal Hello guys welcome to kar di david koche face pe ek paath subscribe do subscribe and subscribe the Channel Please subscribe and subscribe the Channel Jhal will leave and give these problems on Tuesday subscribe rural web designing channel health and subscribe The Amazing The Robot 2.0 The Robot 2.0 The Robot 2.0 The Caller Meetu Phir Di DJ Roadways Problem Loot Subscribe Must Subscribe He Will Reject The Calling Number Three Day Visit To Boys Will Have Only One To The Robot 2.0 Will Give Video subscribe Video Subscribe Robot 2.0 Will Give Video subscribe Video Subscribe Robot 2.0 Will Give Video subscribe Video Subscribe Must Subscribe me 110 number four this one time incident bodh robot 2.2 and values and subscribe our channel if you are subscribed then this special tum jio ka mobile will be rich tours and 102 Thursday subscribe Indian result main to facebook discover with me to Bhavana More Vitamin A Great You Will Get Seervi * * * * Scientist Dr Se Bihar A Piya Ravinder Boat Spelling Divya - 1898 Ajay Ko Ki Nine Inch Ali Vinod The Value of the Column V0 End Column - Loot Through 2014 V0 End Column - Loot Through 2014 V0 End Column - Loot Through 2014 APlus Your Column Tub Kal Morning Hai Value For The Phone Vitamin E That Know I Will Discuss Strategy To Have Maximum Value And Vid U Ajay Devgan Se Path Meri Sleep Chot Raid Over ISRO Row Starting With One Previous Song English It's Rope The Dominant Exercise Logic Packing You Come position side se ek phone to sudhar will be an introduction to will take divya no problem share and subscribe must subscribe to a love police jis previous pimples 2012 and operation Video plz subscribe Channel and subscribe the Video then subscribe to the detention ki nominated and all the combination andhak wanted film institute in this will define ki izzat nahi 28 dis sexual * current column ki izzat nahi 28 dis sexual * current column ki izzat nahi 28 dis sexual * current column values will get number 90 vighna na ko end and desh ko the value of ki redmi 252 got column two without B D To Back To You My Problem One Column And Also Per Call To That Hindu Values Are In This Range Bill That Hindu Values Are In This Range Bill That Hindu Values Are In This Range Bill And One Column Udayan In Middle Age Man Through Current President 's Position Column 1 Column 2 And 's Position Column 1 Column 2 And 's Position Column 1 Column 2 And To More Will be previous love not the calling one column to airtel d2h that validates presentation is roll number one and all this is the phone column to all minute updater maximum this app will give you that grain discuss minute to determine the cause death no about the human 332 Appointed Limit Value 0a The Limit Is Computer Code Electrolyte That Patent Ductus Pinpointed As Well Was Trained Successfully Tested For All Pimples Before Submitting This Form You Remind Siddha Yantra On This Day And Night Result 100 Gram Paneer And Have Alarm Set Samet Early diagnosis of this approach could help him into square roots. Subscribe to Indian Squash.
|
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 |
977 |
what is going on everyone so today we are looking at lead code number 977 it's a question called squares of assorted array and here we're going to be given an integer array num sorted in non-decreasing order non-decreasing order non-decreasing order we're going to return the array of the squares of each number in non-decreasing order so we have nums in non-decreasing order so we have nums in non-decreasing order so we have nums minus 4 minus 1 0 3 10 and we're going to square all those numbers and then return the sorted version of that okay uh and then we have some constraints here we have a follow-up constraints here we have a follow-up constraints here we have a follow-up squaring each element and sorting the new array is very trivial could you find the way to do this in o of n solution using a different approach all right so what do we have to do here so yeah there is one way we could do this the trivial approach which would be very quickly we'll just go ahead we could just map through this array square every single number and then just run a n log n sort and then we would have the result sorted and yes that is a way we could do it the only thing is our time complexity using that would be n log n okay so can we do this in linear time that's the challenge here and the answer is yes we can do this with a two-pointer approach this with a two-pointer approach this with a two-pointer approach okay so what we want to do is we want to create a result array an auxiliary result array that's the same length of our input array so here at the bottom i will have our result okay and it's going to be the same size as our input array so i'll just go ahead and label these indices here 0 1 2 3 and 4 and 0 1 2 3 and 4. okay and so now what we want to do is we want to use two pointers we want to have this array here our input array and we're going to have a left pointer and we're going to have a right pointer okay we're also going to have a variable which is going to be result index and we'll set that to the last index of our result array so it's going to be set at four okay and so now all we want to do is we want to compare if the squared value of 10 or the squared value of left or right so for of -4 left or right so for of -4 left or right so for of -4 which is going to be 16 which is greater okay so obviously 10 is greater so what we're going to do is we're going to go ahead and move this right value into our result index which is going to be 100 and then what we're going to do is we're going to decrement the right okay and now we're going to repeat the same process we're going to check what value is greater is 4 squared greater or is three squared greater well minus four is my any two minuses that are squared are going to be a positive so 16 is going to be our next value so we're going to go ahead and put 16 also we're going to decrement this three so now our pointer for result index is at 3 we're going to check which one is larger between the left and the right the left is so that's going to come here that's going to be 16 and this left is going to increment okay and then we'll go ahead and decrement our result index we're going to do the same process we're going to check which value is greater between left and right when you square them it's going to be the right so that's going to be 9 okay and we're going to decrement our right pointer and we'll decrement our right index okay do the same thing we're going to check which one is greater it's going to be our left pointer so this is going to be 1. and we're going to go ahead and decrement this to zero we're going to increment the left to the right and then whichever one is greater they're both the same so it's just going to go ahead and put in that final value okay and so now we have a result here that is correct and then we just go ahead and resol return that result so now what is our time and space complexity with this problem well we are creating a brand new result array here so our space is going to be o of n it's going to be relative to the size of the input so our space complexity here is going to be o of n because of that result array and our time complexity how many times are we iterating over each element dependent on the size of the input array only once we're only hitting each element once we're not going over it more than once so it's relative so our time complexity is going to be linear o of n all right and so let's go ahead and jump into the code okay so what we're going to do here is we are going to first go ahead and instantiate our result array our auxiliary array so we can say const result is going to be new array we're going to set it to the nums.length we're going to set it to the nums.length we're going to set it to the nums.length and then we can just fill it with zero so we have some initial value in the array what do we want to do next we want to set up our variables well we have a left pointer we have a right pointer and we have a result index so we have three variables that we need to set up okay so we can say let left equals zero let right equals nums dot length minus one and let result idx equal nums dot length minus one okay and so now what do we want to do well we want to check while left is less than or equal to right what do we have to see which one is bigger okay which value is bigger when we go ahead and square it so what we can do here is we can say leftval is going to equal math.pal is going to equal math.pal is going to equal math.pal nums at left index to the second power we can do the same thing for the right okay so now we have our left vowel and we have our right vowel and what do we want to do now we want to check if the left vowel is less than the right vowel then what do we have to do well then that means our right val is going to go into our result because we want to get the bigger one out of the two so we can say result at result index is going to equal right vowel and then we are going to decrement our right index we're going to also decrement our result index okay else what do we want to do well then we want to go ahead and set our result at result index to the left val and we want to increment our left what we could do here is just remove this so we don't have a duplicate and then set this here we can say our result decrements okay and now we just go ahead and return our result let's go ahead and run that and we're good okay so that is lead code 977 squares of a sorted array we want to use a two-pointer approach we want to use a two-pointer approach we want to use a two-pointer approach on solving this it's not that bad if we just make clear very clear what our variables are our left our right and how we're stepping through all of this okay so that is squares of assorted array i hope you enjoyed it and i will see you guys on the next one
|
Squares of a Sorted Array
|
distinct-subsequences-ii
|
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_.
**Example 1:**
**Input:** nums = \[-4,-1,0,3,10\]
**Output:** \[0,1,9,16,100\]
**Explanation:** After squaring, the array becomes \[16,1,0,9,100\].
After sorting, it becomes \[0,1,9,16,100\].
**Example 2:**
**Input:** nums = \[-7,-3,2,3,11\]
**Output:** \[4,9,9,49,121\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in **non-decreasing** order.
**Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
| null |
String,Dynamic Programming
|
Hard
|
2115
|
1,521 |
hey what's up guys uh chung here again today i want to talk about another lead code problem here uh 1521. find the value of mysterious function closest to target so this is the last problem in the last week's weekly contest it's a hard problem and uh i wanna try to explain this uh this i the concept for this problem to you guys here so let's take a look basically you're given like a function here let's uh let's ignore the content of this function for now and uh assuming you have this function here and you are given like array here and the target and you need to find out how can you get so based from this array and this function what's the closest number you can get comparing to the target here basically you're given this function and you have you can pass in this array plus another two left and the right parameters and then you have to find somewhat somehow find the minimum distance from the possible result you can get out of the function with this target value right and yeah basically that's the problem here right and let's take a then let's take a look at what's what does this function do basically this function what it does is you're given like an array here and you pass a start and an end point so for the start and end point what it does is it does a bit wise end for all the numbers from a start and end basically you have an array here right you have many numbers on this array basically you can pick any range left or right and this function will gives you the uh it gives you all the uh the bitwise end for everything inside this range right and then it asks you to uh it asks you to find out find the minimum values sorry to find out a way to uh to get the proper uh proper ranged end result bitwise end result for this range that has the closest the target the distance to the target so how can we approach this the solution here right so with the end here and the uh under a an array here what does this end can tell us basically one thing you guys need to know first is by the more array the more numbers you are doing the end the less value it will become for example if there's a three whatever three right um not three let's say there's like a number of nine eighty 500 400 300 okay and so on so forth right it doesn't really matter it could be uh it could be one 150 um it doesn't have to be sorted but the thing is for the so this like this bitwise end starts with 980 right basically the more next time it's when it's to a bit end with the uh this is 850 the end result will definitely smaller than 980 why because the bit end means the means it will only have this one value if both of the bit value is one right so this one will give us one anything with zero one will give us zero right so it doesn't really matter because for 980 the biggest value for end with n this is 980 is itself because that's how we can get the one the most once right because we have to be have the same let's say there's another one if the uh one zero how about this is eight right uh this by the way this is eight and let's see there's another huge number here right has so many ones here but it doesn't really matter how big the next number is right because only these ones only the ones will give us the end result ones for the all the others as long as this number as long as there's a zero number of value on this on the other positions will always get zero no matter how big the second number is that's why every time when we have like a bit end with the current values it will the maximum one is itself so that's the sum will always like be smaller equal or smaller than the current value the more we are doing the end the smaller it will become so that's the fact we need to keep in mind and with that fact we can simply start our searching and we can end our searching when it reaches certain conditions right so our goal is to try to search all the possible ranges right basically what we're doing is we're going to have we're going to start this l from every possible positions in this range right and then we're going to try to uh do an end from the left all the way to the end right but we don't have to uh do an end for other elements right let's say for example we uh we start this uh our search at this position right and then we just keep doing this end by the time our current value by the time the current answer is smaller less or smaller than the target not the target than the yeah then the target right then we can simply break right why because we know the more we will do end with the current answer the smaller the value will it will become so by the time it's already gets smaller than the target so if we keep searching it the smart the answer will become smaller and the distance from between the answer and the target will become bigger and bigger so that's why there's no need to keep searching it right and that's when we stop right so that's the first stop right this is easy to understand and the second stop is do we need to search all the uh do we need to search all else here from start to the end right that's the second question and the way to stop trying the new position for the l is let's assuming let's assume you from l from the current l to n after doing all the bit wide end we get a result uh has here right let's say if the current result from l to n if the s is still is bigger than target it's greater than target if that is still greater than target then it means we don't need to move keep moving the l to the right side why remember so the uh the more we uh we do the bit end the smaller the value we get so what's the opposite statement for that the less end we do the bigger number it will get right so that's why on the stop to stop the l loop here the outer loop here because we already uh we already do a bit wide end from l to n for everything right and the target is still greater than the result is still greater than the target then it means let's move this l assuming let's move this l a little bit to l plus one right then it means the bit end will basically it means it will do less bit end which means the s can only be greater than the target okay sorry the s will be the s uh one will be greater than s right because we are doing the uh the last bit end which means this s1 will be further away we'll have like longer distance between this target and if we move this l1 to l plus 2 here right and then from this l plus 2 to n we'll have another s2 here and this s2 will be even greater than s1 and of course greater than s and also greater than the target basically the more we're keeping keep moving out to the right that the bigger s will get and the further away it will become comparing to the target right so that's when we can stop the outer loop by checking if the final answer of the current loop is greater than target then we know okay we have already seen the best options yet already no need to keep searching okay i think that's pretty much the basic idea here and let's try to code these things up okay and so the first thing is of course we need that n here and array and the answer is the system maximum since we're going to get the minimum value right so we uh initialize it with the uh the biggest the maximum value and then we have l for range n that's our left right that's our left and the right how about the right is the same right we start from l and we end with n and then we have the uh the beat result so for beat result we're gonna start with the uh the array l and for each of the right positions right we just do a bit result we do end with the current right we do this until because every time right when we do another end we're getting a smaller number and that's why we will be updating this answer right every time we have a new result here gonna be a bit answer that absolute value between the beat result and the target right and we stop when the answer it's smaller so when the beat side beat result it's smaller or equal to the target break we can do a smaller because if the answer is zero right then we simply return zero at this moment the bit result will be equal to the target right that's our ideal solution here that's early stop and like i said and if the speed result is smaller than target then there's no need to keep doing this beat wise end because the speed wires will only uh will only get smaller and smaller right and so that's the inner loop how about the outer loop right so let's say the bit if the bit results it's greater than the target right like i said we can simply do a break here right because in the inner loop we will do a will break right will break and when this bit result is smaller than the target and if it didn't break or by looping through everything to the end right basically if the speed bit results target is greater than b3 bit result is greater than the target here it means that we must have already looped through to the last element right because if it stops somewhere in between it might it must be the only reason that you can stop in writing b20 is the uh the beta result is smaller than the target right so basically if it reaches here it means that it didn't stop right in between it means that we already looked through everything to the end right and if from the current l to the last element if the result is greater than target then we know there's no need to continue because like what we discussed the next bit result by moving the l to the right will only become even bigger right and which means it will never it won't give us a better solution better answer here and then so in the end here we simply return the answer since we're just keep up we already keep updating the answers along the way so yeah i think this should just work let's in range okay so this test case passed let's try to submit it yeah so it didn't time out at least it passed yeah cool so basically and the time complexity for this problem i believe in the worst case is the is n square right because we have a an acid for loop here and for if it's the worst case our it will time out but it didn't it's because we have this kind of two bricks here to uh to give us the uh to help us terminate stop the loop earlier that's why i didn't it didn't end up with the worst case scenario right and yeah there's two for the recap so the key idea here is that the more we do a bit wise end the less value this bit result will become with that in mind first we'll stop breaking will stop the for loop when the current range is smaller getting is becoming smaller than target then there is no need to continue the inner loop and for the outer loop right since the bit result from the starting point to the end is already greater than the target with there's no need to try another starting point because it's a with a greater l starting point the speed result will only be great greater than the uh than the previous one okay cool guys i think that's it for this problem yeah thank you so much for watching the videos and stay tuned i'll be seeing you guys soon bye
|
Find a Value of a Mysterious Function Closest to Target
|
find-a-value-of-a-mysterious-function-closest-to-target
|
Winston was given the above mysterious function `func`. He has an integer array `arr` and an integer `target` and he wants to find the values `l` and `r` that make the value `|func(arr, l, r) - target|` minimum possible.
Return _the minimum possible value_ of `|func(arr, l, r) - target|`.
Notice that `func` should be called with the values `l` and `r` where `0 <= l, r < arr.length`.
**Example 1:**
**Input:** arr = \[9,12,3,7,15\], target = 5
**Output:** 2
**Explanation:** Calling func with all the pairs of \[l,r\] = \[\[0,0\],\[1,1\],\[2,2\],\[3,3\],\[4,4\],\[0,1\],\[1,2\],\[2,3\],\[3,4\],\[0,2\],\[1,3\],\[2,4\],\[0,3\],\[1,4\],\[0,4\]\], Winston got the following results \[9,12,3,7,15,8,0,3,7,0,0,3,0,0,0\]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.
**Example 2:**
**Input:** arr = \[1000000,1000000,1000000\], target = 1
**Output:** 999999
**Explanation:** Winston called the func with all possible values of \[l,r\] and he always got 1000000, thus the min difference is 999999.
**Example 3:**
**Input:** arr = \[1,2,4,8,16\], target = 0
**Output:** 0
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 106`
* `0 <= target <= 107`
| null | null |
Hard
| null |
87 |
If Ajay is there, now let us discuss its tabulation message, so we brought the solution from here, in it I had three are you made, but now they were piled up, Singh and spring 2016, so and lag, so these three two alarm set, you spring loan. I am taking for example great strength dos it would be a and we try to make from the farmer will add it will need a dip which will handle a definition like this a demo will handle 623 stock index of start induction spring one side reaction spring 21 and the third definition length, I am using it to show the question village based mission and the love of love can eat purification, how to teach freedom, love just tries to show, which cut here, we will do princess cut, one team on thing. back and p.m. Will remain a victim till now think about what is the meaning of the person who gets the DP done, let's maximize it 2012 2140 phone was scammed Jhalawar Rajasthan set the alarm that if there is even a little bit then they will be sent to the website Loot in this love side examination on Saturday at a slow pace in the second and third round so here we will do this here then we will do this to England in the final here is the jhal chikit side you have to understand very well otherwise you will get lost in the middle So what kind of people do you talk about melting, then lunch one, if there are any girls, what will happen in villages and villages, 108, there is going to be a phone, a string, 207, play the action sequence, here you will be asked about phone or bring to front, which Part options officers and spring banta who are keeping part plus is its bramble meaning scored note is the blight that people talk about late support over any support add have fun and lunch man ki baat kar af that this trick descendant Will you do a leg rintu starting with 'i', there is a girl with the moon, a leg rintu starting with 'i', there is a girl with the moon, okay, that means I have asked this question, friends, to ki dot spring ticket, where from where to where is it justified, question one tap me vighn, subscribe ho, subscribe to hua tha, okay, I Length to back portion will come from this Students Substring A to Z Plus You Pizza Scramble of S One Door Samsung J6 Price Laker Question Meaning If I talk to any like share then it will ask, isn't it happening, it will be like Laker Z Plus Bank Please subscribe and subscribe this Light a So, let's think about the effect of this, I have given it here, so let's start, we have already scrambled, there is no ji's number, there is no his number, and the development is on the order, ji will be ji's number. If you talk about one thing, then you all will be both characters, then I will start working on the machine to make arrangements for scrubbing and notes, it is a symbol of love, yes, it is not a ramble, it is a primitive scramble, which cannot be done on your own, okay. Well, where both the characters are coin, there is true opposite sports that rest of the places can think, A pre-planned to back to, I will definitely A pre-planned to back to, I will definitely A pre-planned to back to, I will definitely share the answer once, Dolat Singh, who started from such areas and Dolan gr8 of 15 crore villages. Be subscribed, sorry, have returned it is definitely an ambrology charge, a string toe starting from 0, two garlic, if your body and mind are encouraged, then likes are definitely very happy, teaser, scramble, employment and not a prayer of course, ki patti khajiyaar That's not a scramble, that's the post here, how do we understand that this is the pick that we are talking about the force of heart and the length of you, after that, thanks to the Soviet land, the present time is the same index of both of them. You told that after starting from zero, two lakh unemployed people should wash it, so now I have cut it, either one line above can be taken, but if you wash it, then you will have cooked it. Now I am asking you, by making such a cut on both the beans, its life. Its left is back pimple i.e. tight friend lamhe ali method from left to i.e. tight friend lamhe ali method from left to i.e. tight friend lamhe ali method from left to right with and ride it with its left is the chapter of jhale ka yeh to main bola to ko trim 102 year 2002 arrangement hogi like and ko aap in sanskrit that ticket which cut ki Talk to me, there is a cut here in both the lions, then the left side of both of them gives the jhal, okay, and you will have to look at the right side of both of them, then the string will start 13252 and the length is time or else I have hugged both of them till now. If the side line is from here, then if the balance is not there, then what will you have to see, the trick will be made, you will have to do the left leg and * left leg and * left leg and * with the carat, A was siropa and one rank one A friend was there that plant right A on your friend * left blank one If you on your friend * left blank one If you on your friend * left blank one If you need an answer to this, if you have a complaint, then try to make it out of the trouble. It is okay to see it in the frame of 2008 language. Now, it is okay to hate your mind by becoming a mother to Besan. If the force reaches both the places and above, then the force is now considered by these people. Priyanka's left toe is crying and her right left toe is playing, it was correct, there was trouble, but you have to understand that it will cause loss. 0101 If you have read this post here also, then why should you write a spring here once and send it to people through mediums 60 Look Husband If you are doing a single job with Jiyaur Koma 80s track, then here you are asking questions that yes, this program is a scramble of speed. If you ask a question here, then there is a scramble of your husband and that with this, you will be able to solve the problems according to Saurabh. Whether there is encroachment or not and if I want to ask a question from here, it is a scramble to share a text phone to ask this question, it is not a scramble of torch light, cannons, it is not a symbol of love, if you get it here then it is zero here. If the gums are burdened with the size of 151, then finally the price is possible, where I will explain it here. Now let's go once with such a feeling, then go through a place and subject. Well, what's the point in sending a message here that RTE's TRP is scrambled or No, it will not be decided, there is no sample, there is no air caste, there is no scramble, now you come to the aerobics village, what is the RG course, the result is that talk about Shiromani, the phone is needed, thank you loot one put length on them and then you will ask So 2013 main length banta give the answer then left and s main forest is famous main length bansal hai joint or are or else what will we do village left him to arrive at length one jhal achha ok a spring call right no leaves I am feeling that our hatred will come in full and will serve as a service to their love. * All you have to do is take a look at what questions Saul was going to ask. I have to write it in one go. If I get space somewhere, I will write it. Good morning, only question. He asks what else ji Jiara has been serviced no ok so the first murder has happened and here if it seems like AG will be scared that is why you are in this then what ji and will you think about solar energy first and ji is. Or if you want, its left and its right are in the districts of GN. Like this, you have got its left since March and now you will get two from here. There is a scrub of G and there is a scrub of G. If you kiss it from both the sides, then this becomes what you want. This is what I am showing you, the machine length is 102 and two, now see here, now Bigg Boss one is pardoned and voting and these 2G are closed completely, I am at the entrance, now let's check in this Sirohi second Manzil cancer and extension into being widowed and on top of that tell a Pappu ji's side and Amish Singh Rintu and that too a Ajay to me so anyway what should I find out Priyanka from last point 2.5 nipples ad Priyanka from last point 2.5 nipples ad Priyanka from last point 2.5 nipples ad temples of each other and like this This train to call is left spring after becoming right, this middle is sorted carefully, here is S2. Yes, okay, what will you do again? There is a need to use it. From here, make two lengths and wash it while starting. If you don't like Singh, then this is You can take the meaning but I leave the message that here meaning of that you will not be able to update the status here jhal alarm set free the pimples quickly will be asked here active this category Scramble of York located on this side and North It is here that this series bramble of RS and not through coming doctors is at maximum this festival etc special order rhythm of course you acid this serum here two friends like I did a pan here try to understand it here But the professor was about to come, so immediately write 1.2 lakh, you are also professor was about to come, so immediately write 1.2 lakh, you are also professor was about to come, so immediately write 1.2 lakh, you are also talking, then how will you cut each one, if one is engaged, then one wants to live with each other, 98 I am the right of the first, left of the second. It happened 376, see what happened on the machines on 12212, but the frame of one rank one is tight, on 1212 the machine is Pawan Kumar Two but the polls come tomorrow Bake Two comes towards this, they decide the second place, their machine is Pawan Kumar Uppal. Entry Ghuma to go, a seal commando has said that you are there is a small mistake, it is a mistake that we collect the season partner more, it is possible to do right, tukur chakra is up there, I am on permission, so you are Kumar Bittu, so here Since your final is Tubelight, it will be good and you maintain it well then there is not much inside next 8081 bramble, there is extra force, CR is not on one side and will win, there is no scramble, I just now 80 scramble, Goa Delhi encroachment will not happen RGT Don't scramble, I am just going to get length free leg like this and it is going to be more interesting. Hello friends, I am of no use to support my skin. It is for this village only because 3 inches will be increased while the cold starts, so you will not be able to consider it. Note it while subscribing. The first question that the printer will ask when he starts is the daughter frowning, is it scrambled or is there no number to go to, the number is very important, a specific one has come, a strict one, so now let's understand it, how to make this 0210, the villagers are very focused, I am yours, okay So let's shorten it a bit and here it is understood that the robbers are getting matatus and lung cancer. It was okay, so if they get the first cut, then they give the second cut to the prisoners. Next up, get likes here, welcome back to good, 231's. Sandhi Ban first posted here that Bigg Boss protest March 2018 9th, I get a little mention of it that it tells the size difference of both, cash deposit is 0162 point two, I like and share it 05261 and want to see the ride point of both, the front part is Ek Ma Pa MP3 I would like to pick it up from here, I will have to run away again, or if I look left, I will have to ride it, collect it to the right, 204 Subscribe to Start 2012, now like this page once, my friend, wrinkles increase to a great extent. The first string starting index is near the second string discussed in length so first I said get it done on both the decisions please that starting this chart is length one get both side company done this trick it will be three to four next two to a pretty simple Now I said that or there is another option, his left is with his right, tips is on the left of Singh, right is on the printer, 1031 is collected, right is just tuk, so I hope you have been given these intakes, you should know by now. Otherwise, once again go back a little and play this video again. If we make it tighter then our focus will be on inch above. Watch carefully. In the frame of 012 length one rank one, show Gaya Khusro on death, lying face down on tomato. New commercial X2 Thanks to all the family, went and defeated one by a quarter inch, got spread at one place on the top of manti and the result becomes a duty, instead of another option, there is a second option, 2014 length one went to rank one and the ends are como two. Make a is next one and two were back to back two frames and they were seen going on the cases that from here too you are from here Mittu and will definitely become one of these two who come all around wait for a minute oh friend while ramble Off the gr8 was just correct, if the answer doesn't come from here then I have to cancel more sugar, then he starts another 380 and takes three lengths, then he gets cleared by 3 lengths, where is the place to make the cut, tell me first Meghna, next My point seems to be here and if I write something to Falguni Pathak then try this book, the length to be cleared from 042, you answer two n24, the length to be with then a that its left C is on the phone, right with land students and subscribe and the place is I. Answer the length one, that cigarette, then if any one or two answers of this or this are found, then my decision is hostility. Okay, so you feel it once and I will give you the length and I am going somewhere but I will explain something to you again. Okay, I will hold the goat and understand it. At this place of my daughter, there is no blanket or a scramble. And this is not a scramble. Just tell more let's maximize this last option and I think you should go comfortable here co tight here you should go comment double is so I to talk to strong so talk to them joke role is one thing to replace ring inductors and 2031 Second Leo Sheoran Oil first click here then to tighten then first under the house it is written that if there is a place to walk or zero length descent then you need short 80 length one and C1 length or else it should be written with left and right. With its left, that cigarette or if I get cut above 2 lakhs, then what happens after lunch, then what happens now, so that friend, its left, give you ma length to the answer and stop 482 length that on this side of it Right as well to cotton length to and e jhal 98100 time jhal you net from here always - drink you net from here always - drink you net from here always - drink joint study length remove whatever remains then reply like to turn off the light now want such gays I will reply immediately ok job also J2 The topic of this type of thing is complete that you will go inside TTP and then after getting the result, apart from finding the length in the X-ray, there will be length in the X-ray, there will be length in the X-ray, there will be a lot of problem for them too. It is okay to make the answer of this love. Frame of this answer is needed because this is the truth of love. It is only a topic, you go on a full stomach, put your result from there and it is ready, then let's go love, if you click on it then select one and how to close loop is fast, how can I not be able to see the other one, if you see the checkup, then it is ok, open lens. To two and this also from Bol to Next to quora Two lines one is a super fine machine Rolex two from here one and a half inches from here and friends get it tightened till I get it then I have to do this in the pattern Whether this work is over or medicine time is also to be seen, new 100 stop writing of comfortable with it Bhagat, I free it quickly and we break our answer and see, if it is rough then TRP rating will not be subscribed, friend, this scrub. Inch length so thanks for all these sports are of no use to us 234 If we do this bundle then is ATR GRP a scramble spokesperson Dr SP RJD Chief said that when it does not happen now let us know whether ATR is an ant's blanket or There are 888 people with input and we are not drivers beyond a specific artist. Once you try to make a support consul out of you, all these sports people will be there in life, they are of no use, then why not the useful thing, it was useless or not. After clearing the first index, I will not be able to inspire you with five lenses top gun, tight, finally, you will start from here, this will be the final answer, which street, let's go, now let's try to fold it, first of all, a puja in the village. Make deputy of a new one, now I have made it so F-18 but have become a part now I have made it so F-18 but have become a part that Aishwarya is doctor leg torch light welcome and over and plus tied I am lying on panty only yesterday I made state champion because lines Vivo v11 is also needed A Commercial N0 Thank 12345 Remind Me Like Jab Wahan Tak Main Prem Chahiye To Zero Seven Don't Like Uh Schools Are Closed On 90 Have Profit Alarm Has Been Installed On Length Bank One Seven Will Start And Where Will You Click And Last Till Grand Slam Blank, that travel in every frame, play it from Servi Plus app, my tab page. Well, see how far you travel, rank once, okay, look at the gas, thanks that in this you are only one, go next, that cigarette, then end. - Let's travel till the length, that cigarette, then end. - Let's travel till the length, that cigarette, then end. - Let's travel till the length, come bring the lace daily and you end - loop is that they request you a pan - loop is a pan - loop is a pan - loop is happened to Ajay till today now I click here that if you are doing the length one frame again If yes then what is the answer of SDPO Paikmal Jagmal Bank that if both the characters are equal fair don't drink drink drink and carat my dear tie if equal s you don't vote on me when I have these two computers if both are equal then more This is because the fans of the apps keep bringing me that cut point one till youth and how many edit changes till Kuruvansh do Capricorn lagna rank like five length, this is the eligible people of one, after two, after three, where From one to the court till the last or till the time you did not get the truth, you used to pay me on the bank till the post that I Kumar Jain Komal Bank's answer is made, now I understand it. To understand for, set the phone that a one becomes a mask to the oppressed for an hour to 120 length, there is some length and meaning rank one that this open loop of war will run or it is for the appointment at this time when you run their forms. Then what I want from here is that both of us collect from the legs. Okay, just that your I, this is your J and that your length is, this is a short dress, start and answer the balance, it's been two minutes, okay, or else. And along with this, it does the right things for both of them, so the ride point of both of them, how many people are planning to press the A link of I Plus - 2 Jhal will just see, if it is written like this then think about Play Store, think more. The only need is to think about making a sequence, thank you, think about it, I will give you the answer by making an angry 120 length and have taken the length one step further, which prevents people from doing both here from both the collections. Office is the first left, each other's right is the other's right leg, answer one I am a friend, this is the first right, each other's left, if you will learn the length, then if I write this, then kill the brother, jack ma liquid. How should it be written? First, you are closing, so I said that the starting point will remain there, start the list, I am social, if we assume, how much progress has been made till now, or whether its next point will be the license start, where are the front part, the four, G plus. K - Let's start, how many plus. K - Let's start, how many plus. K - Let's start, how many should be taken, the first one has the right, how are the ruffles cleaned, the second collect like, how many electrons have come, how many electrons, the traffic is discussed, where will we get this complete photo from, I just let's do it on 24th AP. P ho hua tha, I like to write money, I like to write left of both of them, left of these two of light or this is the earlier reference of York and Raw, I am doing the first of the second, tomorrow aa jhal pai ko strong length for K5 Plus show that Sanjay Place - K you give your answer that Sanjay Place - K you give your answer that Sanjay Place - K you give your answer 256 collect do both ok second is i first scissor left second share right ten plus two i length - k how many likes sharing is i length - k how many likes sharing is i length - k how many likes sharing is i first factor first do i don't see i plus ki rate ki so many lagi to thanks Yes - Sachin, we will defeat completely like this and what is Yes - Sachin, we will defeat completely like this and what is Yes - Sachin, we will defeat completely like this and what is our answer in the last minute, then what can we make for free? By placing the zero on the top, why is Ajay okay, so we have put it here, Shrimad Sintu, if we have kept it nearby. If you look at it like this, then the process is cool and submit. Okay, it's all matter. The question was a little complex and I understand the skirt regulation and also contractor Edward compression. What is the reason that Frida went effective now 3D key. It becomes a bit difficult to visualize on the plane, so I made the frames and showed them, once you subscribe and see, it will create the formula like the answer to this old one, stop in the middle, make 210 answers, which can be completely solved by making the answer of Mattu. If you make it out of mosques then it will be ok then you will get the complete hit that to make the answer of this you should also know the answer of Link China. Next two you should know the like and superstition of the airplane. To know the answer of the tight one you will have to know the complete answer of this. You will have to go to the dip and extract the job from there and bring a new one. Okay, so I request you again that first you watch the video of his memory child, first think of the request a solution, then I go to Bishu, then the favorite application will come up, okay. Thank you very much date sheet for this video. If you like it then do like the video. Thank you Shravan.
|
Scramble String
|
scramble-string
|
We can scramble a string s to get a string t using the following algorithm:
1. If the length of the string is 1, stop.
2. If the length of the string is > 1, do the following:
* Split the string into two non-empty substrings at a random index, i.e., if the string is `s`, divide it to `x` and `y` where `s = x + y`.
* **Randomly** decide to swap the two substrings or to keep them in the same order. i.e., after this step, `s` may become `s = x + y` or `s = y + x`.
* Apply step 1 recursively on each of the two substrings `x` and `y`.
Given two strings `s1` and `s2` of **the same length**, return `true` if `s2` is a scrambled string of `s1`, otherwise, return `false`.
**Example 1:**
**Input:** s1 = "great ", s2 = "rgeat "
**Output:** true
**Explanation:** One possible scenario applied on s1 is:
"great " --> "gr/eat " // divide at random index.
"gr/eat " --> "gr/eat " // random decision is not to swap the two substrings and keep them in order.
"gr/eat " --> "g/r / e/at " // apply the same algorithm recursively on both substrings. divide at random index each of them.
"g/r / e/at " --> "r/g / e/at " // random decision was to swap the first substring and to keep the second substring in the same order.
"r/g / e/at " --> "r/g / e/ a/t " // again apply the algorithm recursively, divide "at " to "a/t ".
"r/g / e/ a/t " --> "r/g / e/ a/t " // random decision is to keep both substrings in the same order.
The algorithm stops now, and the result string is "rgeat " which is s2.
As one possible scenario led s1 to be scrambled to s2, we return true.
**Example 2:**
**Input:** s1 = "abcde ", s2 = "caebd "
**Output:** false
**Example 3:**
**Input:** s1 = "a ", s2 = "a "
**Output:** true
**Constraints:**
* `s1.length == s2.length`
* `1 <= s1.length <= 30`
* `s1` and `s2` consist of lowercase English letters.
| null |
String,Dynamic Programming
|
Hard
| null |
1,704 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is determine if string halves are alike so in this question we given a string is consisting of even length we have to split this string into two halves of equal length and let a be the first half and B be the half we have given a string s we have to split it into two halves A and B two strings are alike if they have the same number of vbls so bubbles are a iio u both in uppercase and lower case and we can assume that s contains both uppercase and lowercase characters we have to check if the number of bubbles in a and number of bubbles in B are equal if they're both equal then we have to return true as the output if they're not equal then we have to return false as the output so this is a easy question so let's take the first example we have given the word book so we split it into two halves since it is of even length you can split it at uh half length so the a will be the first half which is b o b will be the second half which is okay now we have to count the number of vbls in this so I'll write a help of function and which will check the number of vbls in a string this will give you one and this will give you one because O is a v here and since both their counts are same we can return true as the output which is the expected output here now let's take this example s is equal to textbook so if you split this into two halves it will become a which is the first four characters and the B is the second half which is book now we have to count the number of bubbles in this is one number of bubbles in this is two because e is the only wble here and here o and O are two Wes since one and two are not equal we can return false as the output which is the expected output here so let's Implement these steps in a Java program and then do a dry run so this is the function and the input so let's take that as book as the first example mentioned now we'll convert this entire string into a lower case so book will become book just in case there are any uppercase characters so that you don't have to compare both lowercase and uppercase wvs if you convert the input string into lower case you can just compare the five vels present else you have to do 10 comparisons which is also fine but this is a short hack now I'm forming string a by taking out the substring from the first half zero index to the half of length so a is equal to b o because index position start from 0 1 2 3 so 0 to length is 4x2 2 so this and second index won't be included in the substring so b o is a and b is the second half which is okay because we taking the substring from half of the length and if you don't mention the second parameter it will take the substring till the end here we mentioned only one parameter now we are creating a count variable which will first be called on a so here we pass a which is b o we count the number of character we iterate through this from left to right starting from 0o and one first it will check B if it is matching with a e i o u none of them is matching with B so count is still zero next it will check character I is equal to O it is matching here so count will be incremented from 0 to 1 will be returned as one for a count so a count is one now B count we create another variable and call this helper function count WBLS on B so this is B string which is okay we iterate through this from left to right first it will check o it is matching here so count will be incremented from 0 to 1 count was initially zero now it will check K if K is a Vel which is matching with a i u no it's not so count is one so one will be returned and it will be caught inside B count variable so B count is also one now it will check if a count and B count are same 1 is equal to 1 because both are same so we return true as the output which is matching here if both were not same false would have been returned outside the for loop as this condition would have been failed but here true is the output so the time complexity of this approach is O of n where n is the length of the string s and the space complexity is O of one because we're not using any extra space to solve this question that's guys thank you for watching and I'll see you in the next video
|
Determine if String Halves Are Alike
|
special-positions-in-a-binary-matrix
|
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters.
|
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
|
Array,Matrix
|
Easy
| null |
382 |
Hello hello guys welcome to sameer and subscribe button click subscribe and subscribe the Video then subscribe to hai na ho will to values in to-do list na ho will to values in to-do list na ho will to values in to-do list meeting hai ko strong hum old amazing last veer value setting on loot index members also office approach To solve this problem in this code on here item girl spoon scored and sunao to kutkar samridhi mein and complexity of algorithm for constructive veer setting don't forget to subscribe Channel and subscribe this Video subscribe to this all of that house Bane are ofton combined with select loot no problem subscribe must subscribe pimples and subscribe dip newly appointed subscribe must subscribe ki naag will see all probability is equal in a bid to withdraw all difficulties in to-do list you will have ability of newly to-do list you will have ability of newly to-do list you will have ability of newly appointed loot Subscribe Now To Receive And Subscribe The Amazing Dars Sudhir Valid Only One Value Subscribe Loot Jaane Loot Subscribe To A Message In Inke Vikram 358 Sulabh Little Value Subscribe Must Subscribe To Me Help And Sunao A Gross Jawan ki hawa current luttu head ghee induction hai lucknow blue picture 10 current is not done in the travels and the whole 10 rich persons 2008 subscribe and replace the current person compound electronic movie suggestion melted function one message person features doodh le janna hai One by measure in this question on one wonder assembly to replace first not doing so will result appointed result will be that see bin is increment ayurveda till thursday cause give that student like yourself it is simply data on sunday this stage a running fine Increased Acid Complexity of Algorithm Changes subscribe kare subscribe and subscribe thanks for watching a
|
Linked List Random Node
|
linked-list-random-node
|
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen.
Implement the `Solution` class:
* `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`.
* `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
**Example 1:**
**Input**
\[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 3, 2, 2, 3\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3\]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
**Constraints:**
* The number of nodes in the linked list will be in the range `[1, 104]`.
* `-104 <= Node.val <= 104`
* At most `104` calls will be made to `getRandom`.
**Follow up:**
* What if the linked list is extremely large and its length is unknown to you?
* Could you solve this efficiently without using extra space?
| null |
Linked List,Math,Reservoir Sampling,Randomized
|
Medium
|
398
|
84 |
hi today let's do this question on Lake Oh question number a four largest rectangle in this program so we are given a n non-negative integers given a n non-negative integers given a n non-negative integers representing a histogram for example given s we are having a histogram like this and we want to find the area of the largest rectangle in the histogram and for the given example the correct answer should be this one this rectangular in the shadow and the area should be 2 times 5 which is 10 and for this question a naive solution would obviously be brute force and we can just perforce to the left hand and the right edge of the rectangular and to find the height of it and get area and compare all of all the areas right but it's very inefficient a better way but not a better way is to go through all the possible height and for the given example there is only 6 possible height for example if the height is 2 the first tool the rectangular will only be the tool itself but if the possible height is 1 then the width of the rectangular can be as big as 6 right if the height is 1 and then the width is 6 the rectangular area will be just a 6 right but if the height of the rectangle is 5 and then we can get the answer that their answer rectangular which is 2 times 5 so by going through all the possible height we can just to find the right edge and the left edge for all the heights for all the numbers in the given array ok is an efficient way to do that and the correct way is just using monotonic stack and let's see how we do it first of all we need have a stack and in the stack we are maintaining increasing subsequence of the given away and we are going to store the indexes of the numbers and we should also have answer and initiate it with zero and for all a possible area of the rectangular we just compare it with it and update it with the maximum of the areas okay and then we go through the right edge of the rectangles for right in range then oh that's right so if the right if the height of the right hand is bigger we will just directly appended I'll push it into the stack but otherwise we need to pop at the top of the stack so while the length of the stack is bigger than one because the first one is minus one this minute is right and the coming height of the right edge is all smaller than the top of the stack then we have to pop it out and we have to use that the one that has just been popped out as the height of the rectangular okay and what is the left edge of the rectangular it is just the one the top that is remaining in the stack why because it is a monotonic stack all the numbers in crazing from the bottom of the stack to the top of the stack and we know after we pop up the top of the stack the remaining top will be the one that is smaller than the one that is just being Pop Tart for example if we have a six one five six okay one five six in a stack after we pop up pop out of six out of the stack and the top will be just the five and the five will be the left edge of the rectangular that using six as the height right and we can update the answer height times right - left - what answer height times right - left - what answer height times right - left - what because both right edge and the left edge our exclusive edges of the rectangular they are not the real edge okay so for example for the given and for the given array they recommend color in the shadow will have one two as the exclusive action right and after that we just append the right edge into this deck right because all the values that is eco are bigger then a carbon win has been popped out okay are we done no because after doing this for loop all the values has been pushed in the stack but only some of them has been popped out and there are still some remaining ones that is in stored in the stack and we have to pop the mod also and for all the values that is remaining in the stack the right edge of the rectangular will be just the land of the heights of the right itself okay and while the lens of stack is bigger than one because we know there is a minus one a minute is one right and for this one we have to have H basically do the same thing right you know we just directly copy and then we can just return the answer let's try if it works and since it is and let's submit okay thanks for watching
|
Largest Rectangle in Histogram
|
largest-rectangle-in-histogram
|
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104`
| null |
Array,Stack,Monotonic Stack
|
Hard
|
85,1918
|
220 |
welcome to september's leeco challenge today's problem is contains duplicate three given array of integers find out whether there are two distinct indices i and j in the array such that the absolute difference between the numbers i and j are at most t and the absolute difference between the i and j indices are at most k say we're given this example here we could see that we want to find if there are numbers that are most three indices apart and have a difference of zero so here we can see one has one here that's going to be three indices apart and that is only a difference of well they're the same so there's no difference at all it's zero so this would be true say with this example here though one five nine we want to find a difference of three um with being two indices apart but you can see that it's never going to be the case because one five nine we see that one is going to be two apart from five that's not a difference of uh two same with um to its right to indices it's not going to be a difference of two so all right that's kind of a complicated problem and this problem is really hard it's categorized as medium but i don't think that's the case how could we do this well if we did the brute force method we could just start with every number check to see the um let's see k numbers to its right and see if any of them have a difference of t or less and that would just be the brute force method and that would be well time complexity n all the numbers times k which is going to be the number of indices uh difference and we could code that out pretty easily but that's going to give us a time exception give us a hint here we want to solve it in n log k meaning that there's going to be some sort of sorting involved for the k elements which is like the elements um in number of differences in indexes they also give us another hint here to say hey you can use the existing state use some sort of set hopefully some sort of sorted set to check to see if the number exists so really what they're telling us to do is use some sort of data structure to get the number um of k's first and when we check the next number check to see if this exists inside of our set with a difference of t but that's the hard part right how do we do that because if we had it just normally sorted and checked to see if hey this one exists let's start with one and five now we'll check all right nine are you three or less apart from any of these numbers we basically have to check every single one right so that ends up becoming n times k again so what can we do um well we're gonna have to have some sort of data structure when we do our comparison to have it be log k instead of k and that's the hard part now i had to look up the solution for this because it's not an easy problem at all and there is a you can use like you can set up like a binary tree set that up yourself or binary search tree anyway or maybe a heap but all that's really difficult what i decided or what i looked up and saw was there is already a data structure called sorted list that you can use and we're going to use this to automatically sort our k numbers and every time we check the next number that's going to be log k instead of k and what we have to do is check to see if um the positions for the range of minus t and plus t are um well they exist and if they're not the same because if they're not the same then that means that yes this next number does exist in our set it can be basically it fulfills the conditions of being k apart and having a difference of t for one of those numbers so then we can return it true all right so how do we do this um okay well let's start by thinking about what sort of things we need in here first we need our sorted list right so we'll just call that s for sorted list and we will just initialize that and what we are going to do is for every number and for i and n in enumerate nums numerate nums we're first going to make check to see if r i is greater than k because if it's get greater than k then we want to pop off from our set from this s we want to remove the previous number that was i minus k and we actually need to minus one because it's zero indexed um so because the order of this list matters we have to pop off from our set the one that's um before k right and we only want to do that once we've exceeded our k for the first couple numbers we don't need to check that we can just do it normally all right so now we want to find our positions and we can use the bisect method that exists in python what we'll do is say all right bisect left and this is going to give us the position in our sorted list of the numbers so we'll pass in our sorted list and we'll say hey find the bisect left position of n but we want a minus t here we want to find the ring because we can have a difference of up to t so we want to find the minus t and we'll do the same thing for position two except we'll do a bisect right and here we will do plus t to get the other range now if we do find a position that's not the same if we say all right if position one does not equal position two that means we've had yes this next number that we checked can exist in our set meeting all our conditions so we can return it true immediately there otherwise we will add to our sorted list our number and then just continue to loop again if we get through our entire loop and we weren't able to hit this condition then we return a false now there is one edge case they might give us negative k's and negative t's but because this is caring about the absolute difference that should never be the case so if k is less than zero or t is less than zero then just return a false immediately because that can never work so let's make sure this works here this should return a true oop remove nums uh hmm let's remove ah let's see okay legal target for okay i don't know what i was thinking there it's an if so please ignore that nice index problems all right so that looks like it's working i should probably do more test cases but forget it let's just see and that does get accepted so hooray now this solution is a n log k solution there is an o n solution but that solution involves bucket sorting and it's honestly above my understanding so i just don't really think i should go into it without really understanding it frankly i think this is hard enough getting this solution knowing that you could use sort of lists and the whole not so i'm just going to stick with this you know let me know if you have better solutions of the event solutions you can put them in the comments um i would recommend looking at it but understanding it is a completely different beast so whatever i think this is fine all right so thanks for watching my channel and remember do not trust me i know nothing
|
Contains Duplicate III
|
contains-duplicate-iii
|
You are given an integer array `nums` and two integers `indexDiff` and `valueDiff`.
Find a pair of indices `(i, j)` such that:
* `i != j`,
* `abs(i - j) <= indexDiff`.
* `abs(nums[i] - nums[j]) <= valueDiff`, and
Return `true` _if such pair exists or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[1,2,3,1\], indexDiff = 3, valueDiff = 0
**Output:** true
**Explanation:** We can choose (i, j) = (0, 3).
We satisfy the three conditions:
i != j --> 0 != 3
abs(i - j) <= indexDiff --> abs(0 - 3) <= 3
abs(nums\[i\] - nums\[j\]) <= valueDiff --> abs(1 - 1) <= 0
**Example 2:**
**Input:** nums = \[1,5,9,1,5,9\], indexDiff = 2, valueDiff = 3
**Output:** false
**Explanation:** After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.
**Constraints:**
* `2 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `1 <= indexDiff <= nums.length`
* `0 <= valueDiff <= 109`
|
Time complexity O(n logk) - This will give an indication that sorting is involved for k elements. Use already existing state to evaluate next state - Like, a set of k sorted numbers are only needed to be tracked. When we are processing the next number in array, then we can utilize the existing sorted state and it is not necessary to sort next overlapping set of k numbers again.
|
Array,Sliding Window,Sorting,Bucket Sort,Ordered Set
|
Medium
|
217,219
|
621 |
That The Problems Doctor Schedule And They Will Send You Will Add A Few Tests To Time And Distance Between Central Midfielder Letters For Patent This First Thing He Did Not Alone But It's Positive This Is Not Satire For Next Two Units Subscribe To So let's go through the problem share transfer denoted by latest 2G hai android unit of time show is dhund time ki and innovative interior in backstreet boys school and period aa ki between same to 10 let's look at this example nirvighnam need to stay important tabs different times So You Can't See You Later's Exam Wife Rose Minimum Graph Too So You Should Be a Volume Minimum Number GPS Settings Show Hair Science Notes and Will Exam Scenes Dozens of Gaps Between Juts and You Will Be I Must Be Well Burst Find Her Came Back She Will Be No Bigg Boss-2 Cycle Se She Will Be No Bigg Boss-2 Cycle Se She Will Be No Bigg Boss-2 Cycle Se Notifications To Only One Hai Select ₹100 Notifications To Only One Hai Select ₹100 Notifications To Only One Hai Select ₹100 Note Serious Topics Learning Stuff But No Sir But Just Know You Can Only Hero Cycle Sas Electronics Competition As per Soil Test Dual Pure Cycle We Idle Now He Backem Widow take yes to cyclist youth hair spa in the Indian Idol Amazon syndicates and to this effect in this can be just came with equal frequency but in general house which celebrates its a this cream five times 2013 a times and see the calling two times nature Schedule Se Zameen The Most How To Solve This System Was Developed By Oxford University And Good Bye One To The Limitations And YouTube This Sim Trust Deficit Se Motors Services Number Code Which Can Always Alternates Between Translate This BCCI Now Good After Which Acid Number 102 Problems Due To Subscribe Our Lady Of The Currency Of Subscribe 30 Subscribe Not Trust Enough Will Only Be To Person Cycle Hai Inside Wash Su Our Goal Bluetooth Is Dish Subscribe To As Soon S Possible So First Transcribing Will See What Is The Counter Different Subjects And Mrs day specific which can be put there seniors tree video subscribe now he will not benefit bmc wanted beating of country will be i safe common what is the maximum nurses association with her now with different convention senior executive lineage yr it's too late Now you can put a b and c voice mail and department two three some days and harbhajan footwear c maximum meanwhile * romantic two meanwhile * romantic two meanwhile * romantic two subject to one growth serum report support sian impatient science 10th schezwan subscribe id 's notes account is to here vikrampur 's notes account is to here vikrampur 's notes account is to here vikrampur bbi only An Android Swift B.Ed 2009 bbi only An Android Swift B.Ed 2009 bbi only An Android Swift B.Ed 2009 Hair's Notifications and Gifts BMC Middle Ye Duniya Colorful People Put this in the left that in the ultra small task is fuel but it's a way for later than you have more idle cycle Share SlideAisho Wallpapers Execute Subscribe Debit Can See What You Have First Subscribe To That Chali Staff Tasks That And What Will U Will Executive Suite To -Do List In MP Account Also This Account -Do List In MP Account Also This Account -Do List In MP Account Also This Account After Hours Counter Free Hit Counter For And Time Task B.Ed This Quantum Language In Reverse Se Task B.Ed This Quantum Language In Reverse Se Task B.Ed This Quantum Language In Reverse Se 300 Know what will oo 2010 account certificate admin maximum 10 inches plus wwe united cycle and will check which is the most popular egg unadhe points 102 is MS Word dish total population in that point maximum subscribe 2010 points weaver running all will not spare subscribe this Video Subscribe Avoid Her Widowed Mother To Remove A Temporary Server Error That's The End Of Next Month Before Swift Servi And Under There Is Next Month Baby Inside Will Have D Improve Tuition-Husson Poet Having Improve Tuition-Husson Poet Having Improve Tuition-Husson Poet Having Electronic Instruments But Others Toot But Avoid Any Thing In Removing All Will Be Adding One Plus One Time Units If Result Just Equal To Impress One But Will Need A Little Ki Fee Know It Somewhere In One's Life Lessons In Pisces Then In The Morning Officer That In Bihar Just To Task Wrap Izzat Account Of One So Lets Contact Don't Vansh And Executive Which Is The State Of But Some Time And Bold Kiya Process Minutes In This Loot Cycle Navya Previous Video then subscribe to subscribe and subscribe the Video then subscribe to subscribe our Channel subscribe this Video give 120 days in this updater account So let's go straight to this, tomorrow morning the need unwanted map has happened that the said train has entered that backward people in the state have been created know what will happen, this will have a priority queue of intent that the payroll software of science, let's go are interested in which was Scheduled in which order soon and fear the are not required to hua do that dangal kushti exist this account into practice you were so there editing is those modern medicine is pair with it on off character enter interested in the second part of this speech you Don't push on WhatsApp that in old accounts of respect you know they can have result equal to zero and wild a picture with not MP3 to sudhar temp list database to convert a that in the world record for inflation skills hua hai ajay ko kar do ko Ticket Whatsapp Record - We According Saw It's ko Ticket Whatsapp Record - We According Saw It's ko Ticket Whatsapp Record - We According Saw It's Control Vikram Listen To Take Into This Temporary And Subscribe To On That Contract Sleep And Seizure Person Good Evening All Ther Recent Posts That This Special Account Is Britain Zero-Valued Max To The Prime Tube Zero-Valued Max To The Prime Tube Zero-Valued Max To The Prime Tube Skirt Complete Result Blood Is Pvt Ltd Ek Ajnabi Tasks Pit Dam Hai Samudra Idle Cycle Network Immuno Twist Head South Number Platform And Last Ke Do Sun That This Will Right Time Also Will Right In Plus One Effective Smart MP3 Ki And Finally Back To The return result is that line 5 that also abcd 123 a person who is diabetic year deposit rates that and what is the mistake in plus suggestion is accepted in jai hind swaraj shiv vilas do something in javad kar do hai so this special screening at First time ki dangal default value 90 what is the value of district jai hind plus one pinch of baroda road value get hurt and one month in fact it is not good at 30 2012 these days bihar were priority why hua hai that these were two provider counter each Person divide maximum video provider computer and subscribe to and element soldier what is the size of map of many distance characters and this time job sir da that we return from day 's collection to 's collection to 's collection to reverse order on something improved to maxi that hand this pick Why scold happy and do it MP3 happen do it inform police solves behavior of adol is method that and solution checked in jobs force intelligence time complexity is soft toys subscribe number birth specific creating a priority cue salutation clear putting IT TO THE MATCH KEEP KI CHANDAN BHAI LIYE BINA TEMPT YOU AGAIN A TOP IS QUESTION TIME BUT THE ARE A WEDDING ELEMENT BACK TO LAGI MUVWA IN LOGIN STATES WHERE YOU CAN SEE IN LOGIN WEDDING AT 7.25 WIN THE KEY OR LOGIN WEDDING AT 7.25 WIN THE KEY OR LOGIN WEDDING AT 7.25 WIN THE KEY OR LOGIN In One Lotto Lottery Login Key In Space Views and Functionalities Complexity of
|
Task Scheduler
|
task-scheduler
|
Given a characters array `tasks`, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.
However, there is a non-negative integer `n` that represents the cooldown period between two **same tasks** (the same letter in the array), that is that there must be at least `n` units of time between any two same tasks.
Return _the least number of units of times that the CPU will take to finish all the given tasks_.
**Example 1:**
**Input:** tasks = \[ "A ", "A ", "A ", "B ", "B ", "B "\], n = 2
**Output:** 8
**Explanation:**
A -> B -> idle -> A -> B -> idle -> A -> B
There is at least 2 units of time between any two same tasks.
**Example 2:**
**Input:** tasks = \[ "A ", "A ", "A ", "B ", "B ", "B "\], n = 0
**Output:** 6
**Explanation:** On this case any permutation of size 6 would work since n = 0.
\[ "A ", "A ", "A ", "B ", "B ", "B "\]
\[ "A ", "B ", "A ", "B ", "A ", "B "\]
\[ "B ", "B ", "B ", "A ", "A ", "A "\]
...
And so on.
**Example 3:**
**Input:** tasks = \[ "A ", "A ", "A ", "A ", "A ", "A ", "B ", "C ", "D ", "E ", "F ", "G "\], n = 2
**Output:** 16
**Explanation:**
One possible solution is
A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A
**Constraints:**
* `1 <= task.length <= 104`
* `tasks[i]` is upper-case English letter.
* The integer `n` is in the range `[0, 100]`.
| null |
Array,Hash Table,Greedy,Sorting,Heap (Priority Queue),Counting
|
Medium
|
358,778,2084
|
207 |
course schedule 207 there are a total of n courses you have to take label from 0 to and minus 1 some courses may have prerequisites for example to take course zero you have to first take course one which expresses appear 0 1 give it a total number of courses and a list of prerequisite is it possible for you to finish all courses so we're about winning the exam well I mean I feel a little bad that I picked a graph theory problem back to back I mean it's you kind of yeah I mean the way they yeah it's way query of a graph problem and it's it core it's a topological sort that basically you trying to sort this schedule by you know they're by ticking off something that you don't have to take or writing after basically the leaves of the end graph a kind of mumbling yeah little bit open basically this is just a topological sword and you can do something the idea is that and this is actually I mean it's a medium difficulty but it is a very standard graph we if we problem with in algorithm course this is actually like they would probably use this exact wording give or take as like the canonical example for topological sort actually even I notice or like some kind of you know requirement dag thing so yeah so it seems pretty straightforward so it's possible for you to finish all the courses and yeah and that's pretty much it and actually this is to be honest I maybe spoke a little bit too hastily you don't even need to necessarily topologically so this listen maybe do you need to course I think maybe it's ok to see if there's a cycle in the graph yeah Chris hmm of course if you're given a graph as long as there's no psychos maybe I mean then you can complete then you could complete all your courses so actually this is even slight user than a topological SOI dota that would definitely give you the answer I would actually do some yeah I mean I think you just need to do it that first search for psycho finding and you could do that we perceive time yeah so you could do that we perceive time so the little tricky thing that we have to consider is that you're given an adjacency edge adjacency list not adjacency matrix and at least two different type of complexity for that first search is actually depend on who you ask no they don't give you an but it's actually it allows your depth-first actually it allows your depth-first actually it allows your depth-first search to be even more well it's not sorry they don't actually give you a notation C list per se they give you the list of edges which is relatively trivial to convert into an adjacency list and that allows you to get that magical we plus Yi yeah we plus DZ time for depth per search instead of some Reis quare because if you do that research with adjacency matrix then it's kind of we squared even though you have given though it's technically then I mean it's technically linear but it ends up being we square because you have to like check all the other vertex for each you know each of the visited things so yeah so I think yeah so this is the century cycle finding or so we can kind of get started right away and with the and the first thing we have to do is pre pass us an adjacency list so let's get that started okay them of course is let me take a quick look to make sure the input yeah okay so we want to list a blister pack yeah we have many typos and maybe I'll just abbreviate this just for typing sake so sometimes I get confused about different languages okay yeah for the Python hack you know Python view is definitely let me know if there's a easier way to do this I think the last time I was trying to do something a little funky and fancy and it end up sharing pointers or something so I sorry so I'm doing just a little kind of yeah but um okay Oh yeah okay I think that this should be sufficient try to think it is some of your things panocha and this is the part where I kind of oops I'm trying to think right now do you need to start at the leaves or the root hmm that's interesting actually I'm also trying to think right now maybe I could use Union fine to make the slightly easier for ya I don't know if I'm convinced about that one but maybe I should have just done topological sort still not impossible yeah maybe I might actually even do this in topological sort because it still has the same one time we past year we do it correctly so I was always worried that I get the ordering coaxial so Dixie will you take one so one points to zero okay that was fear there's a pop in Python no Olga that may be weeks it's also just yeah that's just bad but okay cool maybe I have to okay so Dutch been mostly so the only thing you have to do is to cycle checking well I mean you have to make sure that you actually visited all of them so actually okay now let's see what silly mistake I made now what is this I is very confusing maybe it cause having some issues okay but this should be true so that this is wrong like a life or these are directed edge crafts or directed graphs I always maybe have to always worried I have them in the water which I'll just get perfect except it did I set up to address school okay side them set up the edges correctly well I guess always mixed I'm packing for okay so I mean at least this output makes sense as I usually say on these is that you also have to make sure that your when you have suspicions that your code is wrong yet to make sure that's also true meaning because especially in cases like this where the output the possible outputs it's only true or force sometimes if you're a little arrogant or cocky which I have been known to be one time to time you definitely get you definitely accidentally uh you know just roughly let's just say fifty percent of time you just get something that's white by accident where you should and regular I fixed this bug and it's why because Pope the answers were true but you know but that's sometimes not sufficient right because half the time you'll be right so I think I would try to force myself to which you know do a more complicated case I would actually probably test myself a little bit more but this kind of worked out I think I would maybe stress tested a little bit because they don't tell you what n is so maybe I've tried a bigger end which in this leak code interface is a little tricky to choose a huge n well I mean you choose to pick a huge n but what edges I think this yes I said I think this is slightly a little bit on the easier side or it's tough to say because it's light on the easier side you know topological sort which it's almost like hey like for an interview poem if it's like hey you know into topological sort and can you implement it since that is like really yeah then yeah okay but I don't know if I like as a it's an interviewer I don't know I would get that much while you have this per se maybe I could look for kind of coding style and kind of considerations but there's nobody that much thought process and like working through the problem because it's literally like hey if you know topologically was soil then you know how to do this and if you don't then I mean make it you know you might have a rough time so yeah so for this I don't reason I don't really like it as an interview problem at least not when on site I mean maybe for like for phone screen and yeah allocate maybe twenty to thirty minutes of the time for coding then maybe I would use this as a problem and maybe for someone on the motor side you've been but uh yeah pin over it's okay I missed topological soy and I don't know how much it is how much more while you could add on a problem that is basically a textbook problem and they even use the textbook example to do it but no pun intended because it's conversatio great oh yeah so cool can be cursive TFS we used for this um yeah I think so I think the thing that I yes I got a question about Ken because of TFS be used for this idea early on I was actually thinking that could be enough for maybe psycho checking I think the yeah and you could probably do it in refresh the time only because at most you would visit each at once which means you can't be past year time I think the thing that and you could definitely do it I think the reason why I didn't do it that way specifically was kind of finding the current quote the roots or the leaves whichever direction you want to go I think the leaves kind of made like which I have here by having keeping a cow and checking this so you could actually in this way I mean you kind of look at this part of the code it actually lends itself to very straightforward TFS solution because you could just drink of it instead of essentially using a queue we're using the implicit stack way and just palmed you could probably use the Q or the stack interchangeably because for tableau Chickasaw it doesn't necessarily matter which order you do things in as long as you kind of keep track of what would get the TFS which I haven't put DFS's of new tricky because you have to keep like I'm essentially a list of things you need to visit at some point yeah exactly like you don't need to know the topological order so you could definitely do it but you just have to kind of still keep track of like hey I like foods like I visited now you're gonna imagine like almost like a linked list or linked list was like with a fork at the bottom way so like zero look at one or still requires one requires two requires 3 and 2 requires 4 so in that case you can imagine so you're given of TFS you would have to do to order we yeah 3 & 4 first have to do to order we yeah 3 & 4 first have to do to order we yeah 3 & 4 first because so your DFS but essentially yeah you need explicit stat but you still need to keep track in some way because you would visit 3 first to read you then go to 2 and any but 2 is not ready yet so you have to do in order you have to do node 4 first and then go TFS will allow you to go to 2 and then 1 so you have to keep track of things a little bit more with two recursion and I mean and you can maybe yeah like you see yeah I mean I think it's more originally I mean you could implement a iteration with TFS or like with a recursion but when you still need a way to like kind of for every like for every iteration I get the next number two to search and that next number to search may not be one necessarily one of the edge that you are your current notice we are recommending or maybe relaxing another one like yeah I mean in the case I wouldn't draw is let's say you have four and you have soup so request one requires two and then to request we and then to request for something like this way so you'll be questioned because if you want to get at the leap you want to start the leaves first you started at three and we would decrement to maybe but then your deaf for search foot we because to still has a prerequisite so maybe you could go down the other way with like two going to four and then do some math that wait but then you would have to implement something in both directions which is maybe a little tricky yeah I mean I yeah I mean yeah that's like almost you have you sorted edges into a dictionary then it's almost the century like ever yeah I mean it's kind of like an adjacency matrix but maybe like a spa some adjacency matrix so you're running but if you do it that way that I think the problem with doing that it that way is that it depends on how you construct the pre-processing of you construct the pre-processing of you construct the pre-processing of course but so there's two ways to do everyone is kind of what I did here but the pre-processing the edge into the pre-processing the edge into the pre-processing the edge into adjacent see list or except for the end instead of a pen you store in a dictionary which maybe it's okay but if you do it the other way where you just have one big adjacency matrix or one dictionary where it is then you don't get that benefit of having an adjacency list because you would have to ill away for every edge all the time so then maybe as possible at the end up being like doing three times the running time or something like that and I think there's some complication about like going up a graph and down the graph and stuff like that I mean is that way doable which is for me when I'm doing these funds I'm already trying to do things the easiest way in terms of coding as possible no easier after you know how to do it anyway - because it's just there might be a lot - because it's just there might be a lot - because it's just there might be a lot of possible mistakes but yeah definitely then we try later send me a message and we'll kind of review and maybe next week or something like that I'm curious now maybe I'm the lazy but I am still curious oh yeah definitely
|
Course Schedule
|
course-schedule
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
210,261,310,630
|
708 |
hello friends today less of the insert into a cyclic salted ELISA problem we are given note from unsightly linked list which is sorted in ascending order we need to write a function to insert a value into the list so that it remains a sacre coeur so to the list and the given list node can be a reference to ending single node in the list and may not be necessarily a smallest value in the cyclic list and if we have multiple suitable places for in section we may choose any place to insert the new value we just needed to meet a DC requirement after the in section the cyclic list should remain so today I think the key to this problem is that we need to think of all the possibilities our one simple case that the given node is a empty node we just need to new a node but as it is a cyclic kurz list we just hack we also needed two sets and next node through the self then we are done another common case that we are given a so deities and we need that you find it a suitable position to insert the value our algorithm is to first to find the maximum node the reason is that once we have the maximum node we know the next node of the maximum node is a minimum node then we can do the simple iteration to find a suitable position to insert that value but we can also divide the KC into two situations one is that if there insult value is greater or equal than the max value order insert value is less than or equal then minimum value we know that we do not have to iterate the node again because we just need to insert that Valerie after the maximum value you see if the given circular a cyclic curse or either this is one two three we need to insert zero where should we insert after the maximum note before the minimum note the same idea if we need to insert four which is greater than the maximum note we also needed to insert between the minimum and maximum load so just need to new a note and there that means then no the next value no there will be the minimum note and the maximum no the next just be the new note but if not the case we'll also need a cure iterates there Lisa from the minimum note you see if the given no Lisa is one to four we needed to insert a three where should a we insert we wish to find a place that the current node E is less than there insert value but is er next node of the current node is greater than an insult value we can insert that between these two notes so while occurring the next value is lesser value we know we should keep going till that occur you got your next otherwise we know there occurred on acid greater than there in so value we just add to the node next equal to the connects and the Kern exit points to the new node so let's see it again first a check whether the head is no if it's not we just knew a node otherwise we first find a minimun node how do you find a minimum node if we haven't reached the beginning because is a so click so we must check the max next not ecoute you hate otherwise we reach the beginning and the max value is less or equal to MX next well sorry it's a type of next well we never max equal to max start next then we find the minimum maximum note and minimum no that will be next or next then we also use a curve note there are two case it won't hit the insert value is great or you have them max well it's a very less or you have their minimum well you just inserted between the minimum note and maximum note otherwise we sure it's a note to find the suitable position okay now let's write the code first if hate ego you know we should you an old know the value go to insert well and know the tone X ego to note and they will written note otherwise we will try to find the maximum note at the first echo to hate and then we try to find it well master next not ego to hate and Max dull Maxwell less oil co then max next over net max equal to max tall next now we have the max we know the minimum will be maxed on next and the curve start from the minimum to case one case either insert bow is great we call them max Java or insert well let's all kill each other minimal Java we insert after minimum so the node will be new node the value will be in service well the next will be the minimum and then max will be note otherwise we should find the suitable position while Kurt next Java is less than there insert well with that Kurt you go to curdle next so now we find the suitable position so the now there will be new note insert well and though it's next will be kirtan next and there then Kurt next will be the note finally return this hate okay thank you for watching see you next time
|
Insert into a Sorted Circular Linked List
|
insert-into-a-sorted-circular-linked-list
|
Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value `insertVal` into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list and may not necessarily be the smallest value in the circular list.
If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted.
If the list is empty (i.e., the given node is `null`), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the originally given node.
**Example 1:**
**Input:** head = \[3,4,1\], insertVal = 2
**Output:** \[3,4,1,2\]
**Explanation:** In the figure above, there is a sorted circular list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list. The new node should be inserted between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.
**Example 2:**
**Input:** head = \[\], insertVal = 1
**Output:** \[1\]
**Explanation:** The list is empty (given head is `null`). We create a new single circular list and return the reference to that single node.
**Example 3:**
**Input:** head = \[1\], insertVal = 0
**Output:** \[1,0\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-106 <= Node.val, insertVal <= 106`
| null | null |
Medium
| null |
501 |
hey everyone welcome back to another video today we're going to talk about a question that is officially marked as easy and even has a pretty high acceptance rate however finding a method to solve this problem optimally is a surprisingly tough Challenge and I'm willing to bet you'll still be surprised when you see the solution I have for you stay tuned all right so here's the problem we're given the root of a BST we're also told that the left sub tree only contains values less than or equal to the root node value the right sub tree only contains values that are larger than the root node value and finally we're told to return the element that occurs the most frequently in this entire BST if there are multiple elements we have to return all of them in any order okay so at this point you're probably wondering how hard can this question be can we just iterate through the tree and keep track of the count of elements we've seen and then return to one that occurred the most frequently well yeah that's why this question is Mark as easy so the real challenge really lies in how to do this question of o in O of one space now you may already have some ideas about this but if your solution depends on recursion remember that each time you make a recursive call you're actually occupying Extra Space on the stack each call to the function occupies stack space resulting in linear time complexity additionally using a stack or cub based approach for BS BFS also won't help you these data structures will also take up space as they hold more and more nodes and will ultimately result in O of n space complexity still so what we're going to do instead is tree mutation which can be done in O of one space let's review how we're going to do this let's say this is our tree again our goal is to Traverse this tree with an inorder traversal why well if you had a sorted list and I asked you to return the most frequently occurring elements in this list could you do it in O of one space of course you just iterate through the list straightforwardly and keep a running count of how many times the current element has occurred for example at the first index we have current num set to one and this one has only occurred once so both the maximum and current streak are set to one when we iterate to the second element the number of times this element two has occurred is also one so we don't update Max streak or curse streak same thing for element 3 and same thing for the first occurrence of eight however once we reach the second occurrence of the number eight has now occurred twice so the current streak is now two and the maximum streak we've seen is also two on a third occurrence of eight we increment both to three and so on when we reach the nine then well we reset the current streak to one because there has only been one occurrence of nine but our maximum streak is still five so in the end we'll return the number that was associated with the maximum streak in this case that's eight now recall that an inorder traversal is one that gives us the values of the nodes in order assuming that the BST is sorted in this way that was described in the problem description so basically by doing an in order traversal we are doing the equivalent of iterating through a sorted array so let's say we're currently at the root node and we have some sort of loop like Kern node equals Kern node. left well once we iterate to the left node we're unable to ever revisit the node we just came from and unfortunately doing an inorder traversal will require us to re revisit nodes up the tree so let's rephrase this question let's say that our goal is to make every element connected to its next larger element via nodes to the right that might sound really confusing here's what I mean so you can see for yourself in this tree if you follow this procedure you'll visit all the nodes in the correct order for example let's say we start at the leftmost node of your current subtree which is one you move to the right so you go to two you move to the right again so you go to the three you move to the right again so you go to the four then once again you start over at the leftmost node in the right sub tree starting at five you move to the right you get to the six and then you move to the right again you get to the eight now this may seem difficult to grasp as to why we do this and this may also seem really hard to implement let's first talk about why this works recall all nodes in the left subtree have a smaller or equal value compared to the root node so therefore if we want to connect elements in a sequential order then we must connect the largest element in the left subtree to my current node how do I find the largest element in the left sub tree well that's actually really easy since all nodes in the right subtree are larger than the root node we just take the rightmost element in the left sub tree because all elements to the right of the current node are larger than the current node value so here's what we'll do if the current node has a left pointer we take that left pointer we then move all the way to the right within that subtree until there are no more right children we draw a rightward pointer toward the Cur node we delete this left pointer in the Cur node and then we repeat this process for the next subtree again we find the rightmost node in the left sub Tree in this case it's going to be the one and then we point it at the current node which in this case is going to be the two we then delete the left pointer and move on to the next element at this point there are no more left pointers to follow for the node labeled one so we move to the right and Mark one as visited again there are no more left pointers for this two node either so you move to the right and Mark two as visible Ed we repeat this process for three and four as well here we see that we indeed have a left pointer at the six so instead of marking six as visited we first find the rightmost node in the left sub tree of six that's just going to be five so we point five back to six and we delete the left pointer of six once again then since five has no more left pointers we visit five and we move to the right six has no more left pointers either so we move right once again and finally we end up at 8 so we visit eight and now if you take a look at the order in which we visited nodes you see that we indeed visited nodes in order okay so now let's implement this idea we'll need to walk through each line of the process together so that we don't get lost firstly let's initialize a kodde variable set to the root an empty result array Cur streak and Max streak set to zero and a Kern num which is set to Infinity again in the analogy of iterating through a sorted array you can imagine that Kern num is just a current number we're looking at Cur streak is the number of times a current element has occurred and finally Max streak represents the maximum streak of all numbers we've seen so far we'll then enter this Loop while K node let's first find the rightmost neighbor of the left subtree we'll set neighbor equal to Cur node. left and then we'll just iterate to the right until we have no more elements to the right we'll then set this neighbor's right pointer to the current node which at the moment is still set to the root node then we need to repeat this process for the next subtree and also delete the left pointer of the node for which we have already found the neighbor so let's set this temp variable equal to K node. left we'll delete the left pointer and then we'll set the Cur node to the temp variable okay so that's going to take care of all cases in which we have to populate the right pointer let's now take care of the case in which we find a node that has no left pointer remember since we're deleting the left pointer after we're done drawing the right pointer to the current node that means that we'll only ever arrive at this else case if we've already processed this node before if we've already processed this node that means that its right pointer has been reappropriated to point back up the tree and we can use it to do our in order traversal so firstly we'll see if the current value is equal to current num if so we increment our Cur streak variable if not that means we have found a new number in our quote sorted array and if we've found a new element in our sorted order that means we'll never see the previous element ever again so we set the curve streak equal to zero and set the current num equal to the current node value then we take a look at our curve streak variable if the curse streak variable is equal to the maximum streak that means we have found a variable that occurs at least as frequently as the current mode if the Cur streak ever exceeds the value of the max streak then we reset our Max streak to the current streak and set the result back to the current number finally now that we're done processing the element we move the current node to its right neighbor which again we know is pointing back up the tree to the next larger element and then we just returned this result and we can see that we beat 99% result and we can see that we beat 99% result and we can see that we beat 99% of all users in space complexity thanks for watching and if you found this video helpful or interesting please like comment and subscribe I'll see you in the next video
|
Find Mode in Binary Search Tree
|
find-mode-in-binary-search-tree
|
Given the `root` of a binary search tree (BST) with duplicates, return _all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (i.e., the most frequently occurred element) in it_.
If the tree has more than one mode, return them in **any order**.
Assume a BST is defined as follows:
* The left subtree of a node contains only nodes with keys **less than or equal to** the node's key.
* The right subtree of a node contains only nodes with keys **greater than or equal to** the node's key.
* Both the left and right subtrees must also be binary search trees.
**Example 1:**
**Input:** root = \[1,null,2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** root = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
98
|
1,897 |
So hello what is up guys so today's question is our re distributors to make all strings equal ok so our question today is easy you are given an array of strings words ok zero index ok in one operation pick two distinct index i and j where words i is a non mt string and move any character from words of a to any position in words of j ok so what we have given see let's take an example from here we will have an array of words where There will be number of strings, so we have to see that if we remove A from this and move it here, it is okay in the beginning, then these three strings will become equal, A B C A B S and A S are okay, then we All we have to do is see how many such operations we have to do so that we can pick it up from one place and put it at another place. Okay, what else is said, we have to find out that we can do this, that is, if we do the operation like this, then all the strings will be equal. Will you be able to or wo n't you be able to? Okay, return true if you can make every string and words equal and any using any number of operations, hand falls other wise. Okay, so what he said is that if you do any number of operations, there is no difference in increase. If you can equal these strings all the strings are ok then you return us true otherwise return us false ok so let's think about the question how to see now let's talk about the second one a and a It has been given to us, so look, we can move anything anywhere here, so if you see, if we moved a here, then a will also be a or a, that means an a will be added there, here if we moved anything, then it means it is equal. If we ca n't, that's why we made it false. Okay, so it's a simple thing, friend, we have to see when they say that we can do this division, meaning when can we shift to another place and when can't we do it, okay? So let's assume that first of all, look here, if we think that we can use some counting, then it is okay. Look, if we use some counting and by using it, we see something, then it is okay, then look. If we assume here that A B C and A B C are okay, then if we look at A's, count B's, C's, how much A's do we have, okay, we don't have F. Sorry Y no okay B how much do we have and C how much do we have th okay so we just have to see that man if look if we have to A to equal distributor character to equal distributor pass okay three kids okay And we have n toffees, okay if we understand them to be equal then n should be divisible by thi, if we have to give to three children, only if we have not toffees, we will be able to distribute them among three children, okay only if there are 12. We will be able to distribute among three children but if the number is 11 then that equal distributor is correct, so what if we say take a count of all the characters like A has got one count, B has got one count, C has got one count or Let us take count of all the characters that come. It is okay if we take the count of all and if all the characters are okay, all the characters can be divisible, that means a number of words can be divided into number of words. Okay, what does this mean? It means we can do division by doing operations, it means true, it means it is ok and if it cannot be done, it means false, ok, I think I have understood the point, it should be clear from here, ok, now let us move towards the code. Let's see the code, how can this be done, so look, first of all we make a vector, okay, let's assume the vector count, okay, the count is okay, now do we have 26 characters in our alphabet, okay so let it be 26, okay what does everyone say? Look, here we have given the words of I consist of lower case English letters, so only we are going to have lower case, so we will take 26, okay, and we have to count all of them, so we have made all of them zero, okay, now see. For is ok, string word belongs to word is ok, so now it will run on every word, ok now for character C belongs to word, ok, now we are talking about this word, ok cout, now see how we will remove it, see whatever character. See ya see ya ok whatever character is let's say C is ok or D is or Hai is ok and A is ok then 0 tooth AB CD is ok C mine A i.e. C mine A is. So here it will come to i.e. C mine A is. So here it will come to i.e. C mine A is. So here it will come to okay d - a is 3 so here th okay d - a is 3 so here th okay d - a is 3 so here th here d okay so we have to take nothing a minus from that okay so what do we do here c minus a character okay plus here What has happened to us, counting is done, okay, now for is okay, for it's value belongs to, okay, this count has come into this, now if the value is divisible by, see words dot size, okay if this means it is not divisible. So what will we do return f ok if it is not then anywhere if any character at any step is not divisible then return false if everywhere p is divisible then return true ok then there is some mistake ok y P, we did not enter Semicalculus, OK, he is judging, OK, it is passed, let's submit it and see, OK, so see, the question has been run, OK, so what does the code of this question say? Give its link in the description. I will give it okay, you can refer it from there, so from now on, whatever code we are going to do, what are its links, you will find it in the comment section, not in the description section, okay, so I hope you have understood the explanation, if you like. Then give it a like and share with your friends and subscribe the channel and I will see you in the next one guys thank you 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
|
74 |
hey everybody this is larry this is day 16 of the leeco daily challenge uh hit the like button hit the subscribe button join me on discord uh let me know what you think about today's problem uh search a 2d matrix why did you fishing matrix uh yeah you official album that search a value in m times n the matrix are sorted from left to right the first row is greater than less so this is a classic problem that you can do so obviously if you look at every element it's going to be linear time or o of m times n that's obviously not what you want because if that's the answer then i don't know this is just not a you know it becomes a can you write for loop right so this is a i wouldn't say standard but um but it does get asked a lot for whatever reason on interviews uh i hear uh i have never seen it per se uh on an interview but the idea is uh basically you know that is sort in two dimensions right or not sorted in two dimensions but uh there is this uh invariant which is that going from left to right it's going to be going from smaller to greater and also down and in right so that means that um that means that we can figure out which row it is in and also which um is that true um and then column for which it is in later um and the idea is just basically you walk uh the matrix uh one element at a time either going uh either going right or down um something like that and be good and because you only need to um let me say it another way actually um the first center is greater than the last image of prefix as well okay i misread this actually i thought it was going down okay but so this makes it easier so uh so basically the idea here is just eliminate uh one thing every time right that's the idea behind this problem i'm just doing this for visualization uh maybe i could one of these days i'll get a ipad or something right but basically you have this matrix say and let's say you're looking for 16 right well looking at the next number you know that um well this is 10 right if this is 10 that means that um all the numbers in this row is less than 10. so that means that you're looking for 16 then it cannot be in this number so then you eliminate it and then here it's 23 so that you know in this world so then you just keep on going right so from that you can just keep on going down until you have to go right uh so that's the strategy i'm going to use uh you could show why this is in um of n plus m times uh which is sublinear actually so that's pretty cool right so yeah uh so this is how we're gonna go do it uh by eliminating a row at a time and then the column afterwards so let's do what was your income from the single length of matrix sub zero uh if rose is equal to zero i'll return to fourth because it's tied in right yeah and then now um let's just do x y is equal to zero and then we go um yeah and then okay so then now we check if x plus one uh or with if x plus one is less than rows because otherwise if you've gone too far um then this is a little bit weird i think you could just look at the last element as well um yeah i think you just look at the last element maybe that's a little bit easier to read so let's say the last element of this row um is if matrix of x of s element is if it's uh greater than target what does that mean right that means that the last element is greater well just strictly greater than that means that none of the elements on this row is good so then we could go to the next row right and then if uh otherwise then it is in this row so then we increment by one um and that's pretty much it uh oh this is lowercase now we put in a while loop and oh yeah we probably we should add a if statement which is if matrix of x sub y is equal to target uh return true else we do this thing uh and at the very end that means that we ran out of bounce and then it's returned first um yeah so basically the idea is still we move a row at a time and then if you can't we move a column at a time uh unless i get the science wrong no i think i got the sign from whoops okay um yeah i didn't even have to look at the answers yet let's copy and paste more examples and this one that brings the last one let's do 16. let's look for other numbers um also let's look for a number that's not in it what does it fail is it just because i submitted too much that's why okay so looks good feels good let's submit it and i don't know why it doesn't let me scroll down but okay accept it yay uh okay so again because x we only increment x at most number of rows times and we increment y at most columns number of times so this is going to be over rows plus columns uh and you can see that space is just um oh of one because we only have rows columns x and y right um yeah that's all i have for this problem uh let me know what you think hit the like button hit the subscribe and join me on discord and i will see y'all tomorrow bye
|
Search a 2D Matrix
|
search-a-2d-matrix
|
You are given an `m x n` integer matrix `matrix` with the following two properties:
* Each row is sorted in non-decreasing order.
* The first integer of each row is greater than the last integer of the previous row.
Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_.
You must write a solution in `O(log(m * n))` time complexity.
**Example 1:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-104 <= matrix[i][j], target <= 104`
| null |
Array,Binary Search,Matrix
|
Medium
|
240
|
463 |
yo what's up guys this is Chung here again so let's take a look at another least called problem today number 463 island perimeter so yeah I think I like this problem here so you're given like a map a two-dimensional array here which map a two-dimensional array here which map a two-dimensional array here which consists of only 0 & 1 and the ones consists of only 0 & 1 and the ones consists of only 0 & 1 and the ones represent 1 represents the part of the island 0 means water and so and it tells you there's no lake inside of the island which means inside of the area of the one's there's no 0 right and you need to return the perimeter of this island so what is the perimeter minute rights for example here we have a this is the one's right so the one is consists of the forms the island and the parameter is that out address and outside so that's one two three basically 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 and 16 that's where this 16 come from right so how can we get this number right I think one of the observations we need to think about in Odia let's say there's one square here let's see so if there's only one square then obviously the answer will is 4 right so and every time okay every time let's see it we find another square honest neighbor no matter what direction can be up down left or right but no matter what and in which direction right so what does it mean to this for here it means that okay so basically the two will be become one right so that's why we'll be doing 4-1 so basically for the current doing 4-1 so basically for the current doing 4-1 so basically for the current square here as long as there is like neighbors on any directions we simply decrease by one and we simply can just look through all the other ones and for all the ones we track if the if this one has any neighbors on four directions if there is for each direction treats neighbor we miners we do a minus one okay cool so pretty three four let's start coding here and okay and let's great okay and it's nice to great zero right and then I'm gonna directions so that I don't have to write the same code for four times so I'm gonna be up right up down left and right okay that's the four directions right that we need and for each which simply loop it loop through each of the element in this 2d array here into am right and then for chain range and right what do we do oh so if first kind of work so he goes to four right sorry zero if the creates IJ is one right so first we will plus with plus four to the answer here right and then we track how many neighbors does this 1/2 how many neighbors does this 1/2 how many neighbors does this 1/2 right the for direction in directions right new I plus D 0 and then new J equals to J plus D 1 right then if this and you know we do a boundary track first right and 2m right and the zero is the new J between 0 and the boundary of the column here right and what and a great right one and so I create a new I and J is 1 right and new J is 1 then do either one where we can skip that part right then we do what we miners point equates by one right in the end we simple just simply return the answer here so that's really do it all right so every time with a plus four here and then for each of the neighbors we decrease the answer by one for a current square for a current one right and since we were and then when we basically when we are here right there let's say there are like two ones next to each other at the total what's the total basically if we basically we will be reduced one for this square and also one from this square right basically if there is like cut us to ones connected to each other the total like address we need to decrease is to right but in this case since we're going to look through this one here once and then this one so that's why we every time we decrease it by one for the current one okay so let's just run it should just work cool yeah so pretty straightforward you know actually there's another way you know as you can you guys might must have thought about it so can we use DFS right or bi or BFS so that we only we can only loop through the ones because let's say there's like let's say the M and N is huge right and but the island is very small all right in that case we'll still traverse a loop through the whole m and n regard is even right so one of the small improvement we can do here is I think we can as long as we find in the first one here we can just start from there which we just use a DFS or BFS whatever whichever we feel complete comfortable we just start from there since there's we're gonna use that traverse to traverse all the ones right you know what let's try to call that solution here so similar logic here but in instead of that we just - we're gonna instead of that we just - we're gonna instead of that we just - we're gonna have a queue here basically and let's create a queue right so I think in this case I'm gonna use the breadth-first case I'm gonna use the breadth-first case I'm gonna use the breadth-first search as so I'm gonna use the queue here collections right thoughts DQ a and so what's gonna be in the in this like in the queue right so it's gonna be at Apple of the I and J right so since we're doing that and most likely we're gonna use likely visited or seen sad too so that will it won't stop into the infinite loop right so seen that ad I'm gonna add this like I and J to it right and then let's see so here and while Q right and we do a what we do a pop right so actually here it doesn't really matter actually if we do a lot a levels breadth first search we can simply do we just as long as we loop through all the ones here it's fine right so we can just do a the current a current I write current I and current J right he goes well he goes to the taquille dot hop left right we can do actually the poplar or pop right doesn't really matter and because sequence in this case doesn't it's just fine and it was to a same thing right plus four and then basically we're doing it the same thing here right basically for each four directions we do this right if and what okay I think here we're gonna do a little bit change here so if it's in the range we check and first we check if this one is one right then we know for sure we need to remove one from this from the corner result right that's the first thing window chart and second one we check what we check if this new I and J nu J not in the scene right then we know okay that's that this is the one we need to be processed later right then we add it to the queue I'll cute dot append and new I and new J right and then of don't forget to add this scene to the new coordinates to this today to the stat here alright and here we can simply return here returned this year right yeah that should also work let's see okay oh yeah add here since we're adding a topple here interesting let's see I think I know what happened here so this eve has to be inside here inside of this eve here basically everything has to be start from one so it if this one we decrease the dancer by one and if this one has not been seen before what is a pan this one for the next process alright and then I think another mistake here current I knot I hear ya current I yes not this is what happened if we didn't prepare for this video okay finger crossed all right this time at least it's accepted let's try to submit it alright cool at least I made it so okay so this is just like a little bit improvements by looping through everything from this for entire to the erase basically the first time when we see a one here let me see one here we just start from there we use it like this is like the BFS but without the level control here we just simply loop through all the ones starting from here and for each of the that one each of the one we see we use the same logic as before we are we plus it we increase the answer by four and then we check how many neighbors does this one have it right so how many new ones neighbor one neighbors right neighbor has the value equals to one if it has we just simply reduced by one and we do what we'll introduce as Harshad here if this like if the new name if the neighbor has not been seen then we know okay we can add it to the queue so that this neighbor can be processed next time okay cool guys I think that's it for this problem it's an easy problem yeah I think so but I like it cool guys I think that's it thank you so much for watching the video and let me know even if you guys want to see any other solutions or any other kind of videos yeah I'll be more than happy to do it thank you 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
|
106 |
hello everyone so today we will be doing lead code problem 106 that is constructing a binary tree from in order and post order traversal so we are given two integer arrays that is in order and post order where an order is of course our in order traversal and poster there is the posterior traversal of the binary tree so let's see how we can do that we know that an order is left root and right traversal we also know that post order is Left Right and root traversal so in here we can conclude that our last element of our post order array will be the root and once we find the root we can find the position of a root in the in order array once we figure out the position of our root and our in order array view we can conclude that to the right of the root will be the elements of the right subtree and the left of the root will be the elements of our left subtree so what we can do is we can recursively call our right and left subtrees and we can populate our binary tree so we will first pop 3 as it is the root so our new post order will be for the iteration it would be 9 15 7 20. and our in order will be now we will populate our right subdue first this is because this is just because our post order is left and right and then root so we will be uh popping out the like we will be popping out from uh like from the last so the elements that would come up first are the elements from our right subtree so we will populate our right subdue first and then we will populate our left subtree so what will happen that uh in the first calls in our first recursive calls we would get our in order as 15 20 and 7. so our 3 is there we have got 9 15 7 and 20. now in our next iteration what will happen that we will pop out 20 so 20 becomes our root so now as we know that 20 is the root so we have got uh for the elements in the right subtree and for the elements in the left subtree so next in our next iteration we would be getting in order as 7 while our post order will be 9 15 and we will be popping out seven so here comes our seven so when we iterate again now we will be popping out so in our next iteration what would happen so now we will be popping out 15 so we have now popped out 15 that would be in our left subtree as we have finished all the elements in the right sub tree then what will happen in the next iteration we will come to our left subtree and we will just be left with 9 so our an order will be 9 so here we will be populating our 9. so this is how we will be populating our binary tree from in order and post order and this should be our iterations and this would be our following iterations so let's go over to lead code and see how we can write this logic in the form of a code to start with what we got to do we got to check if we have got something in our post order and in order array we will return or not in order you'd return none if so and then let's initialize our root so this will be tree node and we will be popping out the last element from our post order array yeah so for the mid what we got to do is we have to check the index of our root value in our inorder array then first we will call our right subtree recursively so in our in order so in our forever in order we would be passing so for the right it would be mid plus 1 to the very end and then we would just be passing the post order as it is as we have already popped out so to populate root dot uh left subtree what we got to do is we will call it recursively again and then in our in order we would be passing to exactly the mid position because before our root index position we will be having our left sub tree elements so after that we will just pass our post order because we are already popping it out then let's return our root and check if the solution works let's run it yeah so this is basically a logic behind writing this code so yeah that's pretty much it I'll see you in the next video thank you for watching thank you
|
Construct Binary Tree from Inorder and Postorder Traversal
|
construct-binary-tree-from-inorder-and-postorder-traversal
|
Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** inorder = \[9,3,15,20,7\], postorder = \[9,15,7,20,3\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** inorder = \[-1\], postorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= inorder.length <= 3000`
* `postorder.length == inorder.length`
* `-3000 <= inorder[i], postorder[i] <= 3000`
* `inorder` and `postorder` consist of **unique** values.
* Each value of `postorder` also appears in `inorder`.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
* `postorder` is **guaranteed** to be the postorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
105
|
352 |
hey everyone welcome to the second leite code coding problem explanation today's problem is going to be data stream as to Joint intervals um so I already did the mock interview and it was actually this problem's actually pretty hard um so I spent like a whole hour and at the end I still had a bug or like a comp runtime error something like that so I couldn't I wasn't able to finish it um but that video the mock interview will be posted at the same time as this uh check it out if you want but it's long I don't know what you're going to get out of it um but it's there so anyway uh I expect that this explanation will also be pretty long so um yeah but I think actually this problem is pretty good and if you get stuck this explanation will definitely like hopefully help you out so um how I imagine you would do this is first if you haven't done this problem you should definitely um go do so it's called Data stream as destroy intervals um then if you have a solution and you just want to look at my solution or just better to better understand the problem or if you got stuck and you want someone to guide you through it kind of like step by step then watch this video and then uh if you're curious about how I did when I mocked interviewed this um then check out that other video anyway let's get to the problem so the problem is data stream as destroy intervals um so basically you're given a data stream of non- negative integers data stream of non- negative integers data stream of non- negative integers which is like zero and all positive integers and summarize the numberers seen so far as a list of distr intervals uh it will make more sense with this example so you get a data stream right like you get one number at a time the example they have is 1 3 7 2 6 so um when you put in one you make a interval from one to one then when they put in three it's uh interval 1 3 7 same thing 1 3 7 when there's a two it connects 1 and 3 three and becomes 1 to 3 so now it's 1 to 3 and 7 to 7 and same thing with six combines with the interval 7 to make 6 to 7 so um yeah so basically you have to make a data structure um you set it up over here then and you add numbers to your intervals and then um get intervals returns those intervals so um first of all when I approach a problem I think about how would I do this by hand um my general process is I sort of think about some test cases or just trying to do it by hand and then afterwards after I do that for a while or for like maybe 30 seconds and I try to figure out some sort of pattern that I can then uh generate some pseudo code for um and basically an algorithm and after I have some idea of that pseud code or algorithm then I just code and uh do the rest of the thinking as I code so um so first of all how would I do this by hand how would you do this by hand um what are some of the edge cases or test cases um I'll give you let's say I'll give you two to start off so one of them is there are no intervals and then one of another one is if uh if Val is one away from the end of an interval so let's say that uh the intervals are like 1 to 2 and then 5 to 8 right um if your value is N9 then 9 is one away from the end of this interval right so I'll give you 5 seconds but you should definitely pause the video and come up with your own edge cases go okay so did you come up with some test cases uh so the ones I came up with were and in addition to these two um first of all let's say so first of all there are no intervals and then um another case is there are intervals and um Val is in one of the intervals so uh if it was like one it I just use one I already gave 5 to 8 what if Val is seven right since Val is seven it's between 5 and 8 so Val is one of in one of these intervals um then we have if Val is one away from the end of an interval well what if uh Val is more than one away from the end of the interval like this right um then similarly uh if Val is one away from the beginning of an interval so something like um four so well I could say the start so four is one away from 5 to 8 right then as you might guess um if Val is more than 1 away from the start of an interval so uh this is a bad example but let's say this was 15 to 18 and Val was 10 and as you can see here um there might be some overlap between this rule in this rule because um the Val could be more than one away from 15 and it could be more than one away from two or it could be more than one away from 15 but it could be one away from two see so there's some overlap with these test cases um then seventh one is um there is a smaller interval and a larger interval that are both one away from Val so an example of this is 1 to two or let's say 1 to five and then uh 7 to 10 and then your value is six so yeah so these are I guess you could say more specific test cases um but we want to like come up with some patterns right um we don't want to make an if and else statement for each of these test cases uh so you want to when you're trying to solve algorithms you want to be able to notice patterns and then try to solve them so another way of saying finding patterns is generalizing these cases so I'll give you uh five or five seconds to uh come up with your own generalized cases and as I've mentioned just a few minutes ago there are some overlaps so good luck uh 5 Seconds go okay so did you come up with some generalized cases um how I would generalize this would be first of all we would want to keep that there are no intervals and then also um you want to keep that Val is in one of the intervals now for the rule the cases after that um you can see that if vows went away from the end and then if vows one away from the start then you can say you could generalize it and say V is one away from an interval um then there's if Val is more than one away from the end of interval if Val is more than one away from the start of the interval um you can say Val is more than one away from all intervals um and then 1 two intervals that are one away so basically the same as there's a smaller interval and a larger interval okay so now that you have generalized cases um how do we deal with each of these cases I'll give you 5 Seconds um basically if you to do this by hand in each of these cases um what would you do like if there are no intervals you'd make an interval right and if Val is in one of the interal you don't do anything what would you do in the other three cases okay so um as I said earlier when there are no intervals make an interval when Val is in one of the intervals uh do nothing now when Val is one away from interval uh merge slash modify the interval uh when vales more than one away from inter from all intervals make an interval and then when there are two intervals that are one away uh combine the intervals um and looking at this you when Val is more than one away from all intervals um you can sort of combine that with there are no intervals right so uh that's an optimization we can make later on and yeah so once you think of those cases um then you can start to formulate uh what you want your algorithm to kind of uh look like and your idea of the AL sort of starts to take shape so just a side note um on an actual interview um I don't think I would have the time to write all of this out and at the same time um my thinking also wouldn't be this coherent and this uh logical it'd be a lot more messy but uh since this is an explanation I'm trying to go in depth but just keep in mind that in a real interview um you're going to have you might like think of a few of these test cases and then notice other ones later on as you go like maybe this one uh you'll sort of like derive or figure out uh as use a code but anyway so these are the test cases now you have the test cases um it's time to think of an algorithm um the problem with these test cases is that you can't immediately translate them in code right um so why don't I give you some time uh try to write your own pseudo code and then uh afterwards check back and um see the studo code I wrote or if you get stuck then I'll try to help you I'll try to guide you through the studo code go okay so how'd it go um one thing to realize is that you really only need to find two intervals that are next to the value one on the left and one on the right um and the thing is we have to find them one at a time and when we find one we can find the other so uh what I mean by this is let's say you have a couple of intervals okay so we have a couple of intervals right and the value let's say is um 9 or 11 so when we look at 11 we actually don't really need to care about 1 to 5 or 33 to 35 we only care about 2 to 8 and 15 to 30 and even if we add like another one like 50 to 51 um with the value of 11 we still only care about 2 to 8 and 15 to 30 because these are ones that we uh will potentially these are intervals that will potentially contain the value or be one away from the value or yeah or value might actually combine both of these intervals in all the cases 1 5 33 to 35 and 50 51 aren't intervals of Interest so first thing to realize is that uh only intervals immediately left and right of Val are of interest and the thing is um also keep in mind that left and right might not left or right might not exist if you're like on the edge or values less than all the intervals anyway um so basically left and right matter the most right so um it doesn't really M it doesn't matter which one you choose when you're solving this problem but I like to uh choose always the left one because I like to think about things from left to right uh and in other words it's finding the interval that has the largest star time less than the given value so um basically if 11 is my value two is the largest star time less than 11 so uh find the so um you if you've done interview or interview prep this might not be something new to you but if you're just starting out to do to prepare for interviews you might ask like oh um how would you even know to think about this well with time and practice you should develop an intuition to figure this out pretty quickly uh with intervals especially with intervals um you always almost always want to sort them because it's like an nlog and um it's an nlog and operation to sort and normally uh that like makes things a lot better and simpler to work with and easier to think about um so after you sort it then you should realize that the ones that matter are just the ones on the left and the right because um those are the only ones you have to worry about modifying so uh this comes with practice and every kind of question like tree questions stream questions they all come with their own uh tricks I guess that you tricks and patterns that you sort of notice and start to implement over and over again as you keep doing these problems anyway yeah so uh don't worry if you're like oh my God how am I supposed to figure that out on a on interview uh sooner or later it's going to all look the same to you um so yeah anyway so now that you uh know that you need the interval with the largest St time less than the value how do you write the algorithm with this hint um you don't have to write an algorithm just yet or write code but just do an init a code so 5 Seconds go okay so um how's your C code so uh I'll write some myself so first of all we have to check um if there are no intervals then we make an interval right so uh if intervals is empty then uh make new interval uh insert and sorry if my pseudo code is like really not pseudo code syntax but whatever uh fine the second one is um value is in one of the intervals right so how do we figure that out well as I said before um we want to find the interval with the largest star time less than the value so the interval on the left and after finding that all we have to do is see if that interval's end time is greater than the value so that might be a lot to take in so let's say we have the interval 5 to 10 and the value is 11 so of course 11 isn't in 10 right but if value was eight then um this interval's end time is greater than the value meaning that a is in the interval so um in order to do that first of all we have to find uh let interval equal or let's call it at left interval equal uh you greatest start time less than Val um so we're going to have to write an algorithm for that too but for now we'll do that and then afterwards then we can see really easily if Val is in one of the intervals so if left inter is end is greater than Val then return okay so we took care of number two all right let's look at number three so for uh test case number three um Val is one away from an interval so um let's look at uh left interval um so um let's look at uh left interval first right since we already have it so um f Left interval. End is equal to valve minus one then um left interval end equal Val so we modify uh that and then at this point um if we merge it in we also have to keep in mind that by changing left interval end we might connect it with the next interval so at the very end uh see if we can merge left interval with right interval and then um afterwards if that's not the case then we want to check right interval do start if that's equal to Val + one and if it is then right interval. + one and if it is then right interval. + one and if it is then right interval. start equal to Val so that takes care of if Val is one away from interval now what if vow is neither of these so vow is more than one away from all intervals or basically a more than one away from the left and the right interval in that case then we just have to make a new interval so uh make new interval and insert okay and um you might be saying oh well what if left interval or right interval don't exist then we have to have checks for that and what if you say well how do we find right interval well if we have the index of the left interval then right interval would just be index + one be index + one be index + one right anyway so this is the pseudo code um please note that you don't have to be this detailed in your pseudo code on an actual interview um normally I just write some pseudo code but once I have an idea of the algor them uh I just do the rest of the thinking in code and um I think it's actually kind of detrimental if you just try to figure out the algorithm and perfect it before you write like a single line of code um and this happens to me where I just get so caught up in thinking and the interviewer is just like okay uh I think we just should just start writing some code now and like okay yeah I agree anyway so this is the pseudo code um the next step is to actually code out this algorithm um so why don't I give you 5 Seconds obviously not really 5 seconds but pause the video and um why don't you first try to write the code yourself and maybe even get it to uh compile and pass all the test cases and yeah so go okay so hopefully that wasn't too bad um now I'll actually code this out so um first of all we have to initialize our Vector to uh return and if you're not familiar with C++ a vector is kind not familiar with C++ a vector is kind not familiar with C++ a vector is kind of like an array list or like an array uh yeah so uh let's see Vector of in and let's call this intervals and then when we get intervals all we have to do is return uh intervals just to be safe we'll initialize it so there's a fresh copy okay so um H I'm wondering if I should put the pseudo code in there I don't see why not okay so um if intervals is empty then we make a new interval so if intervals do size equal to Z then we make a new interval um so how do we make a new interval so I'm doing the inserting and making the interval on the same line so to make a new interval I just do this interval Val which is the start and Val which is the end and then after that I push back so I basically push this interval um into um the intervals Vector after that I just return so that's test case number one test case number two is uh I have to first of all find the left interval right um so when you're given a sorted array right uh there's something called binary search which lets you find an element you're looking for um and log in time but for now I'm just going to do something very simple I'm just going to have a index that is uh the size of intervals minus one so basically what this does is I just start on the last element right and I just have a simple while loop that says while the index is greater than or equal to zero and um intervals uh intervals at index. start is greater than Val then we decrement index okay so we start at the last element and we keep going left until we hit a interval whose start time is not greater than value which means that um basically at the end of this while loop intervals at index. start will be less than or equal to value or um that doesn't exist and index will now equal -1 -1 -1 okay so after that we just check um check if Val is in left interval so yeah in that case we just don't do anything okay so now we have to check what if it's one away well if it's one away seems like my pseud code's pretty helpful if it's if value is um one away from the left interval then we set um the interval. N equal to value now if um the interval if that's not the case then we check the interval on the right if the interval on the right start time is equal to the value + one that time is equal to the value + one that time is equal to the value + one that means that we want to modify the right intervals start time otherwise we have to make a new interval so uh intervals St push back and we push back new interval from Val to Val now as I mentioned earlier uh we have to address edge cases where the left interval doesn't exist or the right interval doesn't exist right so if index um so we have to say in index is not equal to1 and Left interval. End blah in this case uh we need index + one to be less case uh we need index + one to be less case uh we need index + one to be less than um intervals. size now how do we get right interval we just change that to be intervals at index + 1 okay and then finally um at the end of this we have to check if um we want to merge the two intervals so first of all we have to do these checks again if um the intervals even exist if both intervals exist so if index is not equal to 1 and um index plus one is less than intervals. size then we have to check and um intervals at index do end so how do we check if we want to merge them well the end and the start have to be the same so um we do intervals at index. equal to intervals at index +1. index +1. index +1. start and then in this casee if that's true then we want to merge them right so intervals at index. end will equal intervals at index intervals will equal intervals at index + + + 1 um end right so we now set the end so if you want to merge 2 to 5 and 6 to 10 we want to just take the end of the second right interval and put it into the end of the first interval so now we make this 2 to 10 that's basically what it does after that we have to erase the interval so intervals. erase and this is C++ syntax so intervals. begin C++ syntax so intervals. begin C++ syntax so intervals. begin uh plus index + one and all this does plus index + one and all this does plus index + one and all this does is basically erase uh the element at index + one which is right index + one which is right index + one which is right interval and that should be the code um let's try running this and hopefully it works uh 79 okay so actually um I made a mistake this should be a vector of intervals not a vector of uh ins is that confused me left interval was not declared in the scope of course so um yeah oh my gosh there's so many 92 forgot my semicolon too much Swift programming 95 okay yeah maybe it's not a good idea to directly use pseudo code okay so there's actually a bug in my code uh this is the output and this is the expected output now after you see what's what went wrong here why don't you look at my code and why don't you tell me um where's the bug in my code I'll give you 5 Seconds okay so did you find it so um let's first go through the output everything is good when I put in a one a three and a seven when I put in a two it successfully merged with the 1 one interval but afterwards it was supposed to merge it into the 33 interval too right it was supposed to combine them but how come the code didn't really combine the one and the two and the three everything up to here is fine but then when you look at uh the left interval. end so two and then the uh right interval. start three I'm expecting them to be equal before combining but actually all I need what I actually need is um the start intervals. end equal to the right intervals so the Left intervals. End equal to the right intervals do start minus one and that will effectively combine the two intervals okay and now I have another error and what's happening this time well um I put in a six and when I put in another six it uh adds it in wonder why that is can you figure it out um I'll give you 5 seconds but it should be pretty easy right okay so did you find it um so right now we're checking if Val is less than the interval's end but what if it's equal if Val is less with Val is equal to the N it's still in the interval so you have to add that uh in addition I also have to check if uh the left interval even exists so that's something I didn't check before okay so now that we fixed that there's still one more bug over here now I'm not expecting you to find it but if you're up for the challenge then go ahead I'll give you five more seconds this is the final bug okay so looking at my code I still see one more bug and I think it's the final bug it's kind of tricky but if you're up for the challenge I'll give you five more seconds to try to find it otherwise just wait 5 seconds with me and I'll let you know what it is go okay so did you find it so right now online 100 um I'm making a new interval and I'm putting at the back of intervals what I want to do is I want to insert it uh between left and right interval so what I should have done was intervals. insert intervals. begin at uh index + begin at uh index + begin at uh index + 1 and I want to put in there interval Val from Val to Val so uh instead of so it's if I had some intervals instead and then let's say the value is um let's say the value is zero instead of putting 0 um at the end over here I want to put it over here at index Z okay so hopefully this is the final bug and I'll get that green money I mean accept yeah okay awesome so um let's do some runtime analysis of this uh right now getting intervals is just o of one it's constant time um the main work is done in uh adding the number right so if you go through this step by step uh this is I guess o one um now when we find the interval with the greatest star time less than or equal to Value we're just going we just potentially go through the whole uh intervals right so this would be a runtime of O of n then uh these operations are constant time but when we insert this is another of n uh operation and then uh over here uh we're modifying and then we're erasing this could be another oen uh operation so basically overall this is O of 3n which turns to ENT now after runtime analysis we have to ask well are there any optimizations that we can make and um there are so first of all we can use as a said earlier binary search to find the interval with the greatest star time less than or equal to Value um I think biner search is a really valuable algorithm to learn and there's a really good topcoded tutorial on that so this could be uh o of login reduced to that um but when we when it comes to inserting and deleting elements uh in an array those are just um o of n operations so if we want to use an array or a vector it has to be these operations will cost o of n um now as you can see in uh the mock interview video I did think about using um I think I said a heat but thinking about it more uh we could use a rebalance binary search tree so that finding an element costs um log in and then inserting an element costs login and then also deleting element costs login so uh definitely um you could try to implement this using a rebalancing binary search tree so uh to wrap this up what is the tricky part about this problem um as you can see like even though I prepared for this question a little bit more before explaining it I still ran into some uh like Edge case um scenarios so definitely uh keeping track of all the edge cases and figuring out how to solve them is the tricky part for this problem um yeah and that's the tricky part uh if you don't want to watch the whole mock interview uh video I think you can skip to the end I kind of talked about uh how luck is sort of involved in these questions again I keep talking about that but at the end of the day uh if you get a question like this um you just have to try your best and uh and the more important thing is you want to prepare uh before your interview as much as possible so that um you either get super lucky and get a good question or you get a hard question but you're at least prepared enough to tackle that problem headon anyway um thank you for watching through this whole video uh I know it's it was really long um let me know if has helped you let me know if uh there's anything any feedback you can give me um if there's anything you want me to do or stop doing if there's anything you want me to do better maybe um if I should like have a working solution so that no bugs appear or if you're actually really enjoyed looking at that bug and figuring out uh what went wrong with my code um but yeah thank you until next time uh have a great day bye
|
Data Stream as Disjoint Intervals
|
data-stream-as-disjoint-intervals
|
Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals.
Implement the `SummaryRanges` class:
* `SummaryRanges()` Initializes the object with an empty stream.
* `void addNum(int value)` Adds the integer `value` to the stream.
* `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`. The answer should be sorted by `starti`.
**Example 1:**
**Input**
\[ "SummaryRanges ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals "\]
\[\[\], \[1\], \[\], \[3\], \[\], \[7\], \[\], \[2\], \[\], \[6\], \[\]\]
**Output**
\[null, null, \[\[1, 1\]\], null, \[\[1, 1\], \[3, 3\]\], null, \[\[1, 1\], \[3, 3\], \[7, 7\]\], null, \[\[1, 3\], \[7, 7\]\], null, \[\[1, 3\], \[6, 7\]\]\]
**Explanation**
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = \[1\]
summaryRanges.getIntervals(); // return \[\[1, 1\]\]
summaryRanges.addNum(3); // arr = \[1, 3\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\]\]
summaryRanges.addNum(7); // arr = \[1, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\], \[7, 7\]\]
summaryRanges.addNum(2); // arr = \[1, 2, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[7, 7\]\]
summaryRanges.addNum(6); // arr = \[1, 2, 3, 6, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[6, 7\]\]
**Constraints:**
* `0 <= value <= 104`
* At most `3 * 104` calls will be made to `addNum` and `getIntervals`.
* At most `102` calls will be made to `getIntervals`.
**Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
| null |
Binary Search,Design,Ordered Set
|
Hard
|
228,436,715
|
1,567 |
hey what's up guys we're back with another elite code video today we're gonna be doing problem 1567 maximum length of subarray with positive product what the hell was that give an array of integers and nums find the maximum length of a sub array where the product of all of its elements are is positive a sub array of an array is a consecutive sequence of zero or more values taken out of that array which are in the maximum length of a sub array with positive product okay so we have this nums array and 1 negative 2 negative 3 and then 4 that output is 4. there are any numbers already has a positive product of 24 yes okay so the longest sequence is 4 1 2 3 4. that's how we get 4. we have 0 1 negative 2 negative 3 negative 4. well the longest sequence not the longest positive sequence is 5 right but if you multiply them all together you would end up with 0 because the 0 is included so the longest a positive 1 would be 1 negative 2 negative 3. which has a product of six notice that we cannot include zero in the subway since that'll make the product zero which is not positive okay so the first thing to notice is that right there number one every time we see a zero we have to stop okay what do i mean by we have to stop so let's say we're just adding in numbers okay we're adding in one then we added negative two then we added negative 3 and we added 4 we just keep multiplying the products like this we have 1 then we do 1 times negative 2 which is negative 2 then that times negative 3 negative 2 times negative 3 is negative of positive 6 then we do 6 times the next one which is 4 and six times four is 24 and then we just we keep multiplying like that right but let's say we hit a zero let's say we had negative one negative two negative three four zero five six right so we know up to here we get 24 right from here and then sorry up to here and then we keep multiplying again we want to multiply zero now well what's when we multiply any number by zero it's a zero so then we end up with zero 24 times zero then we do zero times five zero six times uh zero and it keeps being zero and after again and again so one thing we need to keep in mind is now when we hit a zero it's a special case and that basically means now well we can't keep multiplying our numbers again so let's push our starting index for the starting of the array from right here and start multiplying other words from there okay so we're gonna divide each of these arrays into their own sections of zeros okay we're gonna divide them by zero okay so now either this is an answer or this has the answer okay now this is the answer sorry either this side has the an answer the answer or this side has the answer okay so now that we know that and we know one of these sides has to have an answer and every time we hit a zero we have to start another array by another sub array right we have to start another sub array now that's the first uh observation the second observation is that we have negative numbers right so when will a nega one negative numbers become positive well when it when two when even number of negative num numbers are multiplied by each other they'll end up with a positive answer when an odd number of negative numbers are multiplied by each other well we'll have an odd answer so just notice just remember basic math that an even number uh the product of an even number of negative numbers whatever is even and if it's an odd number of negative numbers then it's odd whatever i'm lagging okay so we can keep adding right so we have one and we have negative two then we have negative three so at negative two our number is not positive anymore so it's just what it's negative two then we have negative three it becomes positive turns into six and six times four is twenty-four so let's walk through that twenty-four so let's walk through that twenty-four so let's walk through that example so we have one negative two negative 3 and 4 okay now we're going to keep multiplying the number out to our full product so like our product whatever you want to call it and we just keep multiplying just imagine that right so our product becomes 1 first then we multiply by what negative two okay what's the answer to that is negative two right that's negative two so now let's take a step back i missed a step so a first step we start with a one as our product whatever you want to start with it doesn't matter well you have to start with one and then you multiply by the first number which is one so we're going to multiply by one okay and we're going to end up with one right so now we know the maximum positive product is already what one okay we had zero right so our answer was zero originally well now we see we got a size of one a size of sub array of one so we that becomes one then we go to the next step so then we do what we're gonna take that one we're gonna multiply with the next number which is negative two so we're gonna take it multiply by negative two and that's gonna give us what negative two but is that the positive no so we can't change our answer right so we're going to go again we're going to take that negative 2. we're going to apply it by the next number which is negative 3 and what is that's what 6. is that positive now yes so we know the index that negative three is at right and we know when we started right which is that in this case zero we know where we started this sub array from right imagine we're working at a sub array right now and we just subtract the indices and we see that we have a size of sub array of three and that's our new maximum right we got that well keep going okay let's just keep going now so now we see a four i'm gonna do the four i mean sorry we're gonna take out what we had previously we multiply by four and we end up with 24. that's already positive again so once again we can get our new uh length and that's going to be our answer and then we hit the end of the array and then we see that's four and that's our final answer but now let's say we had this example up there where we had four and then zero and then five and then six right so now we need to keep going we wanna check more but now so now i'm gonna take the 24 and i will multiply by the next one which is 24 times what zero but remember when we hit zero we have to start another sub array so i'm going to stop here i'm going to imagine that this is gone all this is gone and i have my maximum of four already and i'm gonna start a new product i'm start again from one okay and i'm gonna skip to zero because we have a zero and start from five so one times five so now what we're really doing is working at a rate of five six basically right you won't really know what it ends when this sub array ends but you'll know when it ends when you hit a zero or you hit the end of the um full array but we don't really know that right now but just to show you we're working our way up five six right now so what's that five and then we're gonna do it again five times the next one which is six that'll give us 30 right and then we update our size is it what size of this is two is that greater than four no so we just keep that and we keep going so that's how it's going to work we're going to have a subarrays of different sizes and we're going to keep working off of that so um yeah that's the basic gist of it every time we hit a zero we have to start a new sub array okay and we have to keep track of how many times we saw an odd number uh how many times we saw a negative number whether we saw an odd number of times or whether we saw it an even number of times and based on that we can kind of uh build the answer because we know if we saw an odd number of um negative numbers then we can't um increase our maximum size right because the final answer would be odd i mean it will be a negative number but if we saw an even number of negative numbers then we know our final answer will end up being positive okay but now let's say the example was like this so we had 1 negative two negative three and then we had negative five and then negative a four like that okay remember don't worry about the zeros anymore we explain the zeros just mean you have new sub arrays okay so we have to answer and handle this case now because you see now we have an odd number of negative numbers so now a product of one whatever it's not one then we're gonna keep doing that we're gonna say one times what times the first one which is one then we do it again and we make our answer it was one right it was originally zero then we made it one then we go to negative two so one times negative two is a negative number right and we don't keep that in into account and then we have um from that oh yeah so negative two times negative three six we see where it's positive once again we could update this now we got a array of size three sub array of size three take negative six multiply by what negative five um sorry positive six once over negative five we end up with uh negative 30. okay that is um negative so we can't update so we do negative 30 times four we see what negative 120 and that's still negative we can't update we hit the end so once we hit a zero or once we hit the end remember when we hit a zero that basically means we hit the end right when we hit a zero that basically means we hit the end so once we hit the end of our sub array then we need to check so now we have it i if we have an odd number of um uh negative numbers well now we need to see we want to get an even number of negative numbers right we don't want an odd number negative numbers so we'll remove the first negative number that we encountered and because as we're going through we're going to keep track of what was that first negative number and we'll start at one after that and we'll find the length of that sub-array right sub-array right sub-array right so we'll say we see we saw our first negative um number was at an index of one right here right the second number which is index of one and so we know that after that if we remove the one negative number we'll have an even number of negative numbers and so we're good so then i'll take the subarray of this size and i'll see it's a size three is that greater than my maximum or is it not greater than my maximum and from there we can work on and build and um basically get the answer so what we're doing once again we're splitting the e the arrays into sub arrays what's what are the sub arrays well sub arrays of uh we're splitting it at zeros we're splitting it at each zero at the zeros right so over here let's say this example so this will split into this sub array and then this sub array because the zero in between you split it then once we split it we're gonna go through okay and we're gonna keep track of how many times we saw a negative number okay if we see uh by at any time we see um what am i saying oh yeah so by the end of this subarray if we saw an even number of negative numbers right then we're good we could we know this is a possible this is our maximum length we could get and we'll just take the length of that sub array if we saw an odd number of um uh negative numbers we saw an odd number of negative numbers well to make it even we can either remove the first negative number we saw or the last negative number we saw we don't need to remove the last negative number we saw right because we already calculated as we were going through right the length of the maximum sub array before we hit that last negative number right before we got to this negative five we already calculated what could be our maximum sub rate from here right at this point okay this one so all we need to do is now try to remove the first negative number we saw so we get an even number of negative numbers and then see what the length of that is okay so that's the basic gist of it and we'll do that for each little sub array remember we're splitting it at zeros and we'll keep track of our maximum length at each point and we'll get the solution by the end of that um so see the code in one second what's happening here is you add this for loop okay and um you're going through it you keep track of the first time you saw a negative number like we mentioned you keep track of every time we see a zero position the sum it doesn't really mean sum it means like um that it's confusing the name over here it's not really sum it's the um basically the sum of the number of times we saw a negative number right whether it's in even times or odd times what i did was i just made a boolean uh variable and i just kept flipping it right every time we saw i said it was basically is even and it was set to true and then every time we saw it i get a number i would flip it so because then it would be one and then i set it to false so it's not even that's what i did anyways so remember now every time we see a negative number we want to um basically flip it or you can add it add to the number of times we saw but basically now um so we saw a negative number so then our negative number of negative numbers becomes one so it becomes odd so then two then three you'll see why that matters anyways in a bit then we keep track of the first time we saw a negative number right in this sub array and how do we know it's from a new sub array well first negative is set to one because you'll see now in the next step anytime we see a zero we'll reset everything we'll reset the number of times we saw a negative number we'll reset the first time we saw a negative number the position of the first negative number will reset the zeroth position right which is that i okay so that's that every time we see a zero that's what we mentioned every time we see a negative number we have to keep track of the number of times we saw a negative number it's a little confusing it's like a word a tongue twister and every time any other time so let's say we don't see a zero we see a positive or we see a negative number it doesn't really matter in this case because we're keeping track of how many times we saw a negative number in the right here so if we saw um an even number of negative numbers then we're good we just take our current position minus the beginning of the sub array right so the size of our current sub array or the maximum we already previously found and we check what's the new maximum and we set it to that else if we're at an odd number of negative numbers if what just keep in mind if we're at an odd number of negative numbers then we need to remove the first negative number remember we were keeping track of it so we do i minus the first negative and then the maximum and then we have that and so forth um it's pretty easy um this isn't that hard of a problem the explanation was probably a little long but once again my goal with these is to try to help you guys understand how to get to the problem not just the explanation of the problem but how to get to the problem and that's why i don't code out the answers or anything like that
|
Maximum Length of Subarray With Positive Product
|
maximum-number-of-vowels-in-a-substring-of-given-length
|
Given an array of integers `nums`, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return _the maximum length of a subarray with positive product_.
**Example 1:**
**Input:** nums = \[1,-2,-3,4\]
**Output:** 4
**Explanation:** The array nums already has a positive product of 24.
**Example 2:**
**Input:** nums = \[0,1,-2,-3,-4\]
**Output:** 3
**Explanation:** The longest subarray with positive product is \[1,-2,-3\] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
**Example 3:**
**Input:** nums = \[-1,-2,-3,0,1\]
**Output:** 2
**Explanation:** The longest subarray with positive product is \[-1,-2\] or \[-2,-3\].
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
|
Keep a window of size k and maintain the number of vowels in it. Keep moving the window and update the number of vowels while moving. Answer is max number of vowels of any window.
|
String,Sliding Window
|
Medium
| null |
151 |
good morning my name is Aran singana and in today's video I'll be solving the question number 551 with the title reverse word string in lead code uh so the question is of medium difficulty level and it covers topics such as uh two pointer and strings so the question is pretty simple it says that given a input string s reverse the order of the words a word is defined as a sequence of non-space characters the words is uh as non-space characters the words is uh as non-space characters the words is uh as uh the words in s will be separated by at least one space return a string of words in reverse order concatenated by a single space note that s may contain leading or trailing spaces or multiple spaces between two words the return string should only have a single space separating the words do not include any extra spaces so it is simply saying us that we have been provided with the string s and we have to just reverse the string B on basis of word of on the basis of What Not not letters or characters so uh it has also given us the H idea of what word is a non-space set of characters which do not non-space set of characters which do not non-space set of characters which do not contains any space in between of them uh like over here t h is one word SK Y is one word e i s is another word and B is another word uh so uh we have to just reverse the order of each and every word inside the S character so as you can see that the first example is the SK is blue with single spaces in between uh so the output is blue is SK the as you can see that the orientation of each word inside the string s has been reversed uh so now also there is a case where there can be leading or trailing spaces of or we can say that there can be uh huge amount of spaces between two words so we need to return the string that contains only single spaced uh singles distance uh correct words and having a single space between uh two concurrent words so as you can see that there's a leading bit of a leading space in hello world and trading space as well so as you can see that in the output the only thing we uh we are getting is World hello with the single space between hello and word world and the uh leading and the training spaces have been removed uh now coming to the third example as you can see that a good example there is um multiple spaces between good and example but in the output you can see that the output is says that example good up with single space between example and code so that's how the uh solution should be in any case so now coming to my solution uh what I have done over here is that first I split uh my C my string that I have been provided with into uh into separate words uh while using this uh res over here but now what uh forward SL S Plus does that it splits each and every word and removes moves Extra Spaces from each and every word or you can say the uh extra spaces between the concurrent word or before or after the words so this double slash s+ does the words so this double slash s+ does the words so this double slash s+ does that function uh after that I created a single uh string s with which is empty now the function of this string s you can say that I updated the previous string as that I've been provided as a input over here as you can see that I'm updating it as uh singles uh sorry empty string is equal to uh double quotes uh empty now what I did is uh I initiated a for Loop single for Loop inside of which I initiated a loop variable I which will start from the back of the splitted list uh array uh now as I told you SS over here contains the uh only words over uh in the array uh not any kind of spaces because of this function over here now uh as I told you uh the output should be in reverse order so to get the answer in reverse order I trating the loop in uh reverse so as you can see that I gave the uh index I value you can say the uh loop variable I the uh highest index or inside the array SS which is ss. length minus one and after that I gave the condition that I should be always greater than minus one and the adddition command over here is that um I minus which will decrement the value of the I by one after each and every iteration now what I'm doing over here is that if I is not equal to zero it means that if the index of the I is not the first element uh then uh what we will do is that S Plus s SS uh at uh character sorry the word at if index inside the SS array plus empty character space over here now why I'm doing this over here now as I told you currently the S is an empty string now whenever I add a string inside it would contain it uh so this command which is SS square bracket I would return as the word inside the SS array at the I index and after that it would add this space right after adding the SS in it now what I am doing uh if uh I is not equal to zero now uh why did I put this command over here uh I did it because for example I have a word like hi hello and I need to reverse it so the reverse would be like something like this okay uh and I'm also denoting it with these double quotation just to Mark the ending and the beginning of these strings so yes over here now as you can see that there is no leading space or trailing space in both uh input and output but if I do not apply this command which is if I is not equal to zero then even in the uh when after printing the or adding the last word inside the uh our answer string it would also add this extra space SP over here now because of that ex extra space the output would look something like this which would add an unnecessary space behind the back uh now to uh remove that we can also use as do remover here as you can see that inside the last command I did that so uh if we do not use S do frame then we need to use it like this over here otherwise we can simply do it like this in which s will simply keep on adding each and every word that is available inside the string uh string array uh SS so after that I am using return sorry I need to add space as well yes just a second yes as you can see that uh if I'm not using s. trim over here then uh I need to mention a command uh statement that if I is the last character that is to be added inside the our answer string that there is no need to add an extra white space behind the answer string uh but I'm using s. remov so it would remove all the leading and trailing wi spaces so that's how uh the uh whole string would be inverted or reverse reversed based on the words uh through splitting for splitting it uh and removing uh through splitting it with this and after that simply iterating from the back of it and it would go till the first index uh so I'm iterating in reverse order and I will keep on adding the string inside my answer uh answer string using this command over here and it would also add extra white space after adding each and every word inside the answer string but to just to remove the trailing and leading spaces I use uh return s. trim uh to remove all the trailing and leading spaces now I'm simply uh running my code okay it will give an arrow over here now I have run my code as you can see that all the test three of the test cases have been passed now I'm submitting all the code as you can see that my code has been successfully submitted now coming to the time complexity of this whole code is determined by the number of iterations the Fall Loop takes now the number of iterations the Fall Loop takes will solely depend on the number of words inside the SS uh string so we can say that it is all o of n uh well that's all for the solution for this question uh thank you for watching
|
Reverse Words in a String
|
reverse-words-in-a-string
|
Given an input string `s`, reverse the order of the **words**.
A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space.
Return _a string of the words in reverse order concatenated by a single space._
**Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
**Example 1:**
**Input:** s = "the sky is blue "
**Output:** "blue is sky the "
**Example 2:**
**Input:** s = " hello world "
**Output:** "world hello "
**Explanation:** Your reversed string should not contain leading or trailing spaces.
**Example 3:**
**Input:** s = "a good example "
**Output:** "example good a "
**Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string.
**Constraints:**
* `1 <= s.length <= 104`
* `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`.
* There is **at least one** word in `s`.
**Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space?
| null |
Two Pointers,String
|
Medium
|
186
|
814 |
Hi gas welcome and welcome back to my channel so what is our problem today so what has been given to us in this problem statement, here we have been given a binary tree and what do we have to do, the trick is to see if someone has such patience. Which one does not have van? If there is no van then what will we do? We will remove all those tricks from the tray. Okay, so look here, whatever is there, its value will be zero or it will be van. Okay, now let us understand it through an example. Is the problem ours? After that we will see how we can solve it. Okay, so look, we have taken both the examples here, we look at both the examples, we understand and then we will solve it. So look, here we have given you a retreat and The value of the note in this will be zero van. Look here, there is a van here, so what do we do, let's look at this part, then we look at this part, so there is a van here too, this one van is here, okay, this one here is only zero, so what do we do? We will remove it and here what will we attach to its left, the tap is fine, like here you have a tap, you have given taps on both the sides, here it will be polite, so what we have to do is to remove it from here, remove it and tap. You have to attach it, what will happen with it will be removed, okay, you know, it will go from here, so finally what will become of you, it will be made, we will see here, there is a van here too, it will always be free, we will see here too, there is a van, there is only zero here, what should we do? Okay, now let's see what is yours here, what we have to do is to remove this okay, so finally what will become of you is this, from here this is will go to zero, so what will remain of you only here, 1111 this one. Will stay connected because I will give you a van, it is a van, okay, this is the final answer, now how will we solve this problem, look here, I will tell you here, how we will do it, let me tell you first, so we will basically see with the gown, okay We will start from the leaf note, look here, first you will see that first we will see what is there on its left side, what is there on its right side, let's see if there is a tap on both sides, then we will see what is its value, then if we see it then we will see its condition. What will we do? If we remove it, there is a tap on its left side, it also has a tap on its right side and it itself is zero, so we do not remove it, but it is zero, what do we have to do to remove it, where did it come from? The one on the left, this is its left, what will we do in its left, we will put the tap here, it will point to the tap, okay, it will not go to zero, it also has a tap here, but this is the van itself, okay, so here, if we do not remove it, then this Let's go back, he knows that he has a van on his left, he also has a van on his right, so okay, for this, we will see for this too, don't take it on his left, there is a tap on his left, on the right, but this is a van, so okay, this We are from here, we will not move from here, okay then go back, this is what is on the right of this is your van, this is the van on the left of this, so this is yours, we will not move, then we will go back, what is this on the left of this is yours, okay then If it has zero on its left and right side, then it will not make any difference but what is it, if it has van on its left, it will work, so look here, I will tell you how to solve it, so basically you look for it, what are you looking for the left node, first look at its value. Yes, you are looking towards the left, then looking towards its right. Okay, then now you are looking at the value of the load, considering all three, so first we are looking at the left, then looking at the right, then looking at the note, then looking at the right. When do we do this in post order? So here we will do that in post order and solve that problem. Okay, so now we come to which problem, how will we solve it. Okay, so start from here. Let's do it, first start from here, is it zero, let's have this condition which is ours, it is being fulfilled by the pearling, that is, it has a tap on the left side, there is a tap on the right side too and if it itself is zero, then we What will we do if we remove this, what will we do with it, to the left of the root, with this, we will sign this, okay here, what will we do with it, we will make it on the left side, so it is null, okay, so it is done, now we We will go towards its right and there is a null on its right too, so we will see its value, is it zero or not, if it is not zero, then it will return its value from its left, it will know what is its left, so let's go. Right, then it will go towards its right, then it will look towards its left, this tap will give it, then it will look towards its right, it will give tap to this, okay, the tap will look towards it, then it will look towards its own value, it will see the value of the note, let's both these taps. But its value is Van, so it means that we will not use its protein. Okay, if we do n't remove it, then what will it do in the condition, it will return its right i.e. Van, then it will return it, so this is Van, this return its right i.e. Van, then it will return it, so this is Van, this return its right i.e. Van, then it will return it, so this is Van, so this is It will not even move, what will we give by returning it? By looking at it from the left, we will see that this is a van, now we will make it go towards the right, okay, it will go towards the right, then it will go towards its left, then towards its left. Here, there is a channel and its right side is null, its right side is also null and it itself is zero in date, what do we have to do here, we have to return null, okay, so what will it do, what is left of it is null, it will be okay. Its nature is, what will we do, we will tap its left, then what will happen here, towards this, then it will go towards its left, okay, it will go towards its right, we will get both case NAND and its value is van, then none, this is called van. It will give by turning it is not zero, the full condition for removing is not getting full because if you return it with van, then it will know that this is its tap, but from here, it has got van from the right side, so okay, it is okay here. If you will not remove it, this too will give you zero attendance, but here it has its van, so this too will not be yours to remove, so tap here, you have signed in the sketch also, you have signed here, you have signed in the sketch also, you will get this finally i.e. this tap, you will get this finally i.e. this tap, you will get this finally i.e. this tap. This tap, this is ours, this is okay, so now we come to the text of the code, court is also like this, it is quite easy, I understand you court, then what did we do here, first of all we checked, then what will we do? On the left side of the root, we will again call the request, on the left side of the root, okay, then on the right side of its root, we will call it on the right side, then we will call the value of the root, we will see whether it is zero and its left hand owner. Is it on the right, what is the tap? If it is getting fulfilled in both the cases, then what will we do in that condition, will we give it a return tap, which will be its previous route, what will happen on its left, will your tap be fine or will it also be on the right side? So if it happens in the case of this function, see what happens to you, see, let me tell you first what are you doing here you are checking whether this is not my tap, it is not a tap, then first you call left. Okay, then you will see that this is not a tap, so it will call towards its left first. Look, if this is also not a tap, then it will call towards its left. Okay, then you will see this. This, this will call towards its left, so when this If you call towards your left then what will you get in this condition that whatever is on its left side is null, then what we have returned in the condition is to return the value of the root i.e. return the value of the root i.e. return the value of the root i.e. what is null in its nation. Only turn will happen, from here it will get null, okay, then when your left recursive call is done, then look at it in the condition, for this particular, you have called left, right, after that, what will you do, you will call right, okay, you will call right. So what will you get in this condition, if the note on the right side is null, then it will return null and give it. Okay, then what will we do, if it is on the left, then you will also call on the right. What we are doing is checking. The value of the root is zero and its left side and right side are also null, so what did it return and see null i.e. what did it return and see null i.e. what did it return and see null i.e. who will get this then the one on its left will get it i.e. this one will get it, okay so this is what i.e. this one will get it, okay so this is what i.e. this one will get it, okay so this is what we have done. We have done it here, okay, so here how will we get the null on the left? Okay, so what will happen in this way is that the left side is also of the root, which is the left side is also null, this is also null and its value is zero. If it is then it will return that who will get the left of the root, then in this condition, what will happen to this root left, it will become null here, it will become null, so in this way, what will we do here? We will sign like this, so here we have taken root left, taken root light, ok so finally this is your code, now current it and submit, see where is Java Luck Plus is from both of them, right? Let me show you in c+, Java Luck Plus is from both of them, right? Let me show you in c+, Java Luck Plus is from both of them, right? Let me show you in c+, okay, here is the code of both, just what happens here, there is an arrow, there is a dot there, okay, I hope you have understood. If you liked the video, then please like, share and subscribe, thank you. You
|
Binary Tree Pruning
|
smallest-rotation-with-highest-score
|
Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_.
A subtree of a node `node` is `node` plus every node that is a descendant of `node`.
**Example 1:**
**Input:** root = \[1,null,0,0,1\]
**Output:** \[1,null,0,null,1\]
**Explanation:**
Only the red nodes satisfy the property "every subtree not containing a 1 ".
The diagram on the right represents the answer.
**Example 2:**
**Input:** root = \[1,0,1,0,0,0,1\]
**Output:** \[1,null,1,null,1\]
**Example 3:**
**Input:** root = \[1,1,0,1,1,0,1,0\]
**Output:** \[1,1,0,1,1,null,1\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 200]`.
* `Node.val` is either `0` or `1`.
| null |
Array,Prefix Sum
|
Hard
| null |
1,189 |
welcome back everyone we're going to be solving Lee code 1189 maximum number of balloons so we're given a string text and we want to use the characters of text to form as many instances of the word balloon as possible we can use each character and text at most once and we want to return the maximum number of instances that can be formed okay so balloon only occurs once in our example one balloon occurs twice in example two Okay so we could simply just Loop through our string and count the occurrences of each letter if it's in balloon and we'll have to divide L and O the occurrences of L and O by two and then we should be able to return just the minimum of you know the bottleneck of the occurrences of b-a-l-o or n occurrences of b-a-l-o or n occurrences of b-a-l-o or n so how do we do this we sh we can do this with a counter so we could um import counter from collections and we'll create that we'll just call it counts we'll say counter of our text so what's that going to give us that is going to give us this counts all right so now we have the frequencies of the characters within our uh text string so what can we do now well we know we're gonna have to divide o and L by two so let's do that we can do that by saying counts not dictionary counts of L is going to be divided by two and counts of what do we have to oh divide by 2 and then we should be able to return the bottleneck now so we can do that with counts of B all right we have to count the number of occurrences of B we'll also have to do it for a l and o and n b a l o n so this should work let's run it find out okay so if you pass all three test cases submit does work so what is the actually let's go back so we could optimize this some more uh but the run time is going to be o of n right We're looping through every uh letter every character in text and creating a counter for it that's going to be o of N and then this is going to be an O of n runtime as well so what is our space complexity is essentially going to be the length of the counter that we're creating right so we can optimize this uh counts that length right because let's say we have a string of I don't know a thousand characters but there's characters in it other than uh the characters that are in balloon so we could um let me just write this down here first it's going to be counts.length it's going to be counts.length it's going to be counts.length for the space complexity so what we could do instead of doing this is um we could import a default dictionary and we will say default dict and it's going to be integer then we can Loop through our text and grab all the characters that are in balloon so for character in text if C is in uh you know the balloon characters be a l o and n what are we going to do we are going to increment counts of character by one and then we'll still have to divide the uh occurrences of L and O by two um but we should this should also work so we'll run this pass all three test cases and it does work so now this so This does it's still the same space complexity but it's always going to be the length of balloon in this case instead of the length of our input string so that'll do it for lead code 1189 maximum number of balloons and I hope to see you in the next one
|
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
|
1,903 |
hello guys and welcome back to lead Logics this is the largest odd number in a string problem it is a lead code easy and the number for this is 1 1903 so in this problem we are given with a string num and this string nums represent a large integer and in the problem we have to return the largest value odd integer from the string nums that is a nonempty substring of the nums and if there are no odd elements in the string we have to return empty string so as you all must be knowing substring is a contigous sequence of characters so let's see what the question is asking through examples suppose we have example one num equal to 52 so in this the largest possible odd number is five because only two elements two characters are there so if you remove the odd one we have only five now let's come to the other input it is 2 46 so in this there is no odd element we have to return empty string and in the last example the current string itself has is uh odd so we can return the entire string because this will be the largest uh number which is possible so yeah so how we are going to solve this let's see so we are going to iterate through the string from the right to the left and if the last digit is odd we are going to return the entire string as it is because it is the already the largest odd number and if the L last digit is even we are going to keep moving until an odd digit is found and we'll return that substring of the uh from the beginning to the string where we found the first OD digit so let's see through dryon so for the sample input one 52 we are going to check the last digit is it odd no it is not odd so we will move the index to the left so we get the current substring as five is the last digit odd yes it is return now let's see for an example 3546 so initially the current substring is 3546 large digit is 6 is it odd no move the right index to the left 1 Point left so the current substring becomes 354 last digit four is it odd no move left then we have a current sub substring as 35 last digit is five yes it is five uh is it odd yes it is odd return 35 so this is how we are going to solve now let's come to the code section but before that do like the video share it with your friends and subscribe to the channel if you're new to the channel so let's start with the coding section so first of all we'll check for the current string if it is odd we can return it simply so for that we need to convert num. Care at num dot length minus one so this is the last character of the current string and we have converted it into the int so let's see if mod 2 equal to 1 we can simply return and the num otherwise we are going to define a right pointer since we know that if we reach the statement this means the last uh element is not uh odd it is even so we need to do a length minus one here so while I is greater than equal to Z and N equal to num do care at I and if n mod 2 equal to 1 we return the num do substring 0 to I + to I + to I + 1 because we are doing this I + 1 because we are doing this I + 1 because we are doing this I + 1 because the last um in the substring function the last index which we are given is not included that's why we have to do I ++ or I + 1 then we are going to remove ++ or I + 1 then we are going to remove ++ or I + 1 then we are going to remove the decrement the pointer because if it is odd we are going to decrement and here we can return empty string because if there had been an answer it would be returned by here if there is no answer it will be returned by here so let's see if it runs for the sample test cases this is nums passes for the sample test cases let Run for the hidden test cases as well passes with a good time complexity and good memory complexity so the time complexity for this solution is O of N and the space complexity is O of one and time complexity is O of n because we are iterating over the all the characters of the string and the space complexity is over fun because we are not using any extra space so this was my solution if you want to check the C++ Python and you want to check the C++ Python and you want to check the C++ Python and JavaScript code you can go in the solutions panel and check this solution this is my solution you can read the explanation here also the intuition approach see the Java code C++ pi python approach see the Java code C++ pi python approach see the Java code C++ pi python JavaScript and yes do upload the solution thank you for watching the video have a nice day I hope you liked it shared it with to your friends and subscribe to the channel thank you
|
Largest Odd Number in String
|
design-most-recently-used-queue
|
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** num = "52 "
**Output:** "5 "
**Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number.
**Example 2:**
**Input:** num = "4206 "
**Output:** " "
**Explanation:** There are no odd numbers in "4206 ".
**Example 3:**
**Input:** num = "35427 "
**Output:** "35427 "
**Explanation:** "35427 " is already an odd number.
**Constraints:**
* `1 <= num.length <= 105`
* `num` only consists of digits and does not contain any leading zeros.
|
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end.
|
Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set
|
Medium
|
146
|
1,953 |
Hello hello everyone welcome back to my channel in today's video vishal decode 1953 mitti maximum number of seats for which you can work for electrification zara and projects number from CO2 and minus one india government teacher and miles to that person microlight in most number of issues of This Product Has And Rule Clear But Every Day You Will Emerge Only One Must All Of Birth Chart And You Must Work Every Video Key Notification Quick Pride And Water E Can Not Want To Schools From 10am Project For To-Do List Don In Speaker Project For To-Do List Don In Speaker Project For To-Do List Don In Speaker To Take A Break And Only To The Best Of The Best All The Only Song DJ Ka Record About When Chilli Stop Working And You May Not Completely Products And Dead The Question Middling Liters Maximum Number Of Which You Will Appear Different So You Will Be Able To Deposit Without Letting Must Subscribe Tube Examples 123 Basically Midway 10 Days Without Sleeping And Also Look How Fast These Examples Are Fennel 521 Basically A This Input Is 52122 This You Can Quickly Destroy Susarla Department Will Have To Take Default In Every Alternate Now Screen Awards And Tourism Place 50 Gap Between Please Pay To This Subscribe I Soy Sauce But You Can Do It's Rightful Place Arrest Everything In This Man And Gives It Should Avoid Plus To Result 2018 Right The Two Means Deposit You Can Place Of Government Senior World School Of The Type To That Is This What Do You 200ns Cancer Will Be From This 1234 5 Se Zid Is subscribe The Channel Please subscribe this 12345 6 And Subscribe To A Ride That Sougdian Serious Latest Lets Pray Samaddar Latest Right To The General Is Right Basically So Right A That You Have To Fielder For Basic What Apps Between The Lines And Of The Largest Protect The Wick And Please Largest Project For Example Previous K Sequence Side Effects You Can Give Everything In Between Subscribe Busy Schedule at every year to the element subscribe button subscribe plus one side a solitary place largest plus one elements in that case that agar banswada pansad tarf waste things all the soldier was later status of all the elements system according to cement subscribe a cup sodho maximum aa Aa this time tire can have body black time ko whatsapp the match one day chief - musaddas whatsapp the match one day chief - musaddas whatsapp the match one day chief - musaddas will be time submit tenth board will be sum accept next flight flash lights of medicine my say maxis great dane before app max a plus one day the didn't Utilize and plunder beautiful in the case top tube light on my school will only be able to utilize them accept maths that into place one by interview white time set max plus expect treatment plus one which can feel it never give a clear upsc ride this is the Condition and plight subscribe and subscribe the Light a hai ya so laddu record ki bhaad wale area including roshan point and a my research liye remind school sunshine sum plus grade to my show android will also FD account appointment below latest album axis that driver Maximum Actions Of A Sexy Call Country mx100 Is MS Word Also Max White Stone Android And How To Calculate Some Expectation Maths Subject Maths Buddhism - Alex Ride Se 1000 Maths Buddhism - Alex Ride Se 1000 Maths Buddhism - Alex Ride Se 1000 Map Elements Crystal Time Set Max Plus One New Delhi Only Bay 222 Time Set Max M2 One Plus one night aa 200 ko kya indicate a long 22222 plus one other wise can do everything which can be screen and to the song total complete can utilize the selectors see would loose this seat by doing just saw a yes or no to bishnoi and Explicitly is the most intense university access force so that ripe were office of additional dhanshyam investment officer types long in the best method major lettuce observe the law of right knowledge and right to you a specific run escort in c what is function time including ten Hobbies Hidden Objects of Dice of This Nation Plus the Like Button Share and subscribe the Channel for More Video Subscribe to Channel Subscribe to Programming Entries Subscribe to Channel to Subscribe Now to Receive New
|
Maximum Number of Weeks for Which You Can Work
|
finding-mk-average
|
There are `n` projects numbered from `0` to `n - 1`. You are given an integer array `milestones` where each `milestones[i]` denotes the number of milestones the `ith` project has.
You can work on the projects following these two rules:
* Every week, you will finish **exactly one** milestone of **one** project. You **must** work every week.
* You **cannot** work on two milestones from the same project for two **consecutive** weeks.
Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will **stop working**. Note that you may not be able to finish every project's milestones due to these constraints.
Return _the **maximum** number of weeks you would be able to work on the projects without violating the rules mentioned above_.
**Example 1:**
**Input:** milestones = \[1,2,3\]
**Output:** 6
**Explanation:** One possible scenario is:
- During the 1st week, you will work on a milestone of project 0.
- During the 2nd week, you will work on a milestone of project 2.
- During the 3rd week, you will work on a milestone of project 1.
- During the 4th week, you will work on a milestone of project 2.
- During the 5th week, you will work on a milestone of project 1.
- During the 6th week, you will work on a milestone of project 2.
The total number of weeks is 6.
**Example 2:**
**Input:** milestones = \[5,2,1\]
**Output:** 7
**Explanation:** One possible scenario is:
- During the 1st week, you will work on a milestone of project 0.
- During the 2nd week, you will work on a milestone of project 1.
- During the 3rd week, you will work on a milestone of project 0.
- During the 4th week, you will work on a milestone of project 1.
- During the 5th week, you will work on a milestone of project 0.
- During the 6th week, you will work on a milestone of project 2.
- During the 7th week, you will work on a milestone of project 0.
The total number of weeks is 7.
Note that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules.
Thus, one milestone in project 0 will remain unfinished.
**Constraints:**
* `n == milestones.length`
* `1 <= n <= 105`
* `1 <= milestones[i] <= 109`
|
At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements.
|
Design,Queue,Heap (Priority Queue),Ordered Set
|
Hard
|
295,789,2207
|
1,010 |
hey everybody this is larry this is day eight of the december league daily challenge hit the like button hit the subscribe button drumming on discord let me know what you think about today's problem pairs of songs with total duration they were divisible by 60. um so if you're new to this channel just want to remind you that i usually solve this live uh this is the first time i've seen this prompt or at least recently um and i even do the explanations live so it's a little bit slow feel free to watch this on a faster speed or skip ahead um okay so you're given this song a list of songs where um the duration that's time sub i we turn the dom zone where the total duration is divided by 60. for me we want okay so yeah so the naive way of thinking about it right is going to be you know uh for i in range oops of n let's say n is equal to the length of the time um for j is in range sub n and then if you know time sub i oops plus time sub j mod uh 60 is equal to zero i mean i need some parentheses somewhere count add cap and then we turn cow or something like that right i mean it's not quite right i know but uh because i also have to okay oops um something like that right but it's not gonna be right just to be clear i just wanted this for illustration and you know you see me crank it out in about like half a second or whatever but um half a minute rather uh but yeah but the thing is that at so what is the complexity right this is gonna be n square uh you see that n is uh 60 000 which n squared is gonna be way too slow right so that's not good so the way to think about it is okay um i call this prefix some dynamic programming but you can also just keep it keeping track uh it's not necessary dynamic programming depending on who you ask but i do that's the way that i think about it but um for this one then you basically go uh well it's not prefix sum it's just prefix dynamic programming sorry um but yeah you just process the number one at a time and then you try to find um things that would make it true right what i mean by that is that okay let's say you have the number dirty and we know that we want to count uh some of the two things so that's derivative divisible by 60 right so dirty what makes it do is what pairs with 30 to make it divisible by 60. well it's another dirty right uh or 90 or 1 6 no 150 uh and so forth right but basically the mod of the opposite will add to 60. same thing with 20 right what's the opposite or you know uh in this case it'll be 40 it'll be 100 it'll be 1 4 160. so basically 40 plus some multiple of 60 right uh same thing here then it'll be 20 and so forth or 30 whoops i can do math uh for 150 and that's basically the general idea that we can go off uh by keeping track of the numbers that we've seen that has these properties and then adding to the sum as we go from left to right okay so now um and as long as we're able to do that look up in good time which with a dictionary or hash table we would be uh we should be able to do this in good time okay cool so basically now uh let's just say for i don't know this is time it's kind of weird it should be times right now uh for time in times uh oh we have a i use a collection.counter base collection.counter base collection.counter base uh and what is a collection.counter uh and what is a collection.counter uh and what is a collection.counter right collections.counter right collections.counter right collections.counter it's basically a dictionary that maps uh that's a key value of anything and a value of an int so basically just count stuff for you um so basically here we want to reduce each number by mod 60 right because over 60 doesn't really matter or if you have two numbers a plus b mod 60 is equal to a mod 60 plus b mod 60 well this hoping mod 60 right so keeping track of that um we if a number is greater than 60 or negative i guess actually but now it cannot be negative uh then we don't really have to care about extra we just have to care about um the number that you know minus 60 because as we said again if it's dirty we only need well okay that's a easy example but if this is 20 only need 40 or 100 or 160 and so forth which is 40 plus i times 60 so if you mod 60 you still get 40 and they're inside the same uh what we would call the equivalent class uh or equivalence class huh yeah so they're in the same class so you could group them together so that's what we're gonna do uh time mod 60 and we basically just no you know uh increment this right or you know let's say yeah so basically this will give us the counter and as we go left to right we keep track of the number of times that our mod 60. and now we just have to keep track of the total pairs uh and then the total pairs is equal to what does it equal to right well as we said again let's say we have 20 we're gonna we're going to look for 40. and with that we're 40 we're going for 20 with 30 will look at dirty so you get the idea there which is that you're looking for 60 minus the time mod 60. so let's do that um uh is this right well it's a it's mostly right except for if time is zero or time mod 60 is equal to zero because then this would return 60. so we have to do one more mod 60. um oops this is not total but this is uh let's just call them reverse i don't know look up target let's go to target and then total is the sum of this of target and that should be pretty much it uh it so this is actually something that's um let me talk about this in a second let me also check the other thing cool so what is the complexity right well we look at each time and times oh uh or one we do over one work per uh time and because this o of n times is going to be over n time complexity uh and in terms of space because we use a hash table it's also going to be linear space uh which is all about so i would say this is these kind of problems have become uh more and more common as i would say for the interview and competitive programming definitely about i would say 10 15 years ago you don't really see these kind of problems uh and the reason is because for c plus and maybe even java those kind of languages um it's uncommon to use hash tables in this way um because there's no reliable uh reliable libraries back then i mean i know that as stl but it wasn't that performant appeal they would use it in competitive for a while um until a little bit later on maybe this is more than 10 years ago now maybe this is 20 years ago but so these kind of uh dynamic programming or ico dynamic program problems or just remembering the past problems uh it doesn't really come up that much back then so now but now it comes up a lot because people just expect you to use the libraries for you know hash tables and stuff like that so definitely get familiar with it um it's pretty cool once you get used to it uh there's a lot of problems a lot of variations on these things so definitely up solve them more um cool that's all i have for this problem i'm gonna take a quick look at the hint to see if i have anything okay yeah okay well that is just the answer it's not really a hint but okay cool that's why i have this problem let me know what you think uh and i will see y'all tomorrow bye-bye
|
Pairs of Songs With Total Durations Divisible by 60
|
powerful-integers
|
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds.
Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`.
**Example 1:**
**Input:** time = \[30,20,150,100,40\]
**Output:** 3
**Explanation:** Three pairs have a total duration divisible by 60:
(time\[0\] = 30, time\[2\] = 150): total duration 180
(time\[1\] = 20, time\[3\] = 100): total duration 120
(time\[1\] = 20, time\[4\] = 40): total duration 60
**Example 2:**
**Input:** time = \[60,60,60\]
**Output:** 3
**Explanation:** All three pairs have a total duration of 120, which is divisible by 60.
**Constraints:**
* `1 <= time.length <= 6 * 104`
* `1 <= time[i] <= 500`
| null |
Hash Table,Math
|
Medium
| null |
212 |
Hey gas welcome back, what have you given us in my channel, here you have given us a board of M * N, which has what board of M * N, which has what board of M * N, which has what characters are there, okay and what else you have given here, you have given us a list of stings in which some The words are ok, what do we have to do on this board, whatever we see, we have given you a list of words, if this is the word you are forming here, whatever word you are forming, what do you have to do with it. The answer is to return ageless. Okay, so look here P is it. So here you are getting the post O A T is okay so in the answer I output is your OTH. Okay then your P is P. Is it not in this ? Is it Han? So it is ? Is it Han? So it is ? Is it Han? So it is in our answer. Rain is rain. Can you form it here? You can form it not from this board. If you can do it, then run is not upkar in the output. So that means whatever word you can form here. What you have to do is you have to return the unlist. Okay, so how can we solve this problem? Now the question is what is our problem? Now how can we solve it? Look basically what you are doing here. You are looking for the word 'Pe', ' what you are doing here. You are looking for the word 'Pe', ' what you are doing here. You are looking for the word 'Pe', ' We ca n't make 'Pad', 'Can't make ' n't make 'Pad', 'Can't make ' n't make 'Pad', 'Can't make ' P', 'Nim', ' P', 'Nim', ' P', 'Nim', ' It rain', 'Inko', we can't make ' It rain', 'Inko', we can't make ' It rain', 'Inko', we can't make ' Right'. Now basically the search is simple in this. Right'. Now basically the search is simple in this. Right'. Now basically the search is simple in this. Look, whenever you have the word set off, okay, then what can you do there? Okay, if you want to store it, okay, if you want to sign the prefix of a string, then solve this problem by changing its data status in DFS. Okay, I have made a video of TRAI, now watch the video to understand what is TRAI data status, how do we implement it, right, if you have understood then this problem will be quite easy for you, okay I am here. I will not tell you, I will tell you in the break, but you try how we implement it, please go and watch that video, I have uploaded it earlier. Okay, so what will we do here, which is given in our words, we have given the words in it. What will we do, we will store it in try, what will we do, we will store it in tree, watch that video, okay, look, you will have one root in your note, what will be in your note, you will have one word which will store the word, the second will be your flag variable which will be true false. Will store true or false and the third one will be yours, it will be of 26, okay, so what we will do here is that we have given our word, in this word, we will arrange all of them here, so how will we do it, so let's do the cover first. So if we do the word, then the root note here will be its size 26, okay, what will be the index, it will be from zero to 25, okay, so what will be the index of O minus A, what you will get here, if you do that minus A, then it will be on the index. What you have to do is to create a new note, so what will happen here, what will the new note point to, this index with O will point to it and a new note will be created, okay here too, what will be there in a new note, what will I do, okay that. Look, for sure there will be A in front, then note will be formed, okay, then what will become of you, T will become, then note will be right, then your H will be formed, then note will be okay, so now this is the word which will be here, it will be true, it means that this word should be finished. We have already stalled it here. Okay, so when you search that 80th, if at the end you get true, in the note you get flag, date mains is present right, this is what it means, then it is true. Okay, so then what do we do, what else do we have to store, we have to do P, we have to do AT, we have to do Ren, okay then what is the second one, what will happen in the word here, what will happen to our is pointing from here a. Let's go to If not, then we will go back from here, okay, then we will go in the same direction, if we go in the same direction, then we will see, is there a present on this note, is there a present, who is pointing to this note, okay, present. Now we can go from here to here, we can go here, we will go right here, so is A present on this note, what is not present, T% is on this note, what is not present, T% is on this note, what is not present, T% is on this note, so we will go back here, then we will go in this direction again like this What is present in T? We can move here, we can move here also, but since we have come from here, we will visit here, otherwise where will we visit now? Can we move towards A? What is this note? Do a point. What is it not pointing to? So we cannot go in this direction. We will go back. We cannot go in this direction also because it is not pointing to the eye. This note is that it is not pointing to the eye. If you point then you won't find it even here. When they look here, they are pointing. Okay, what are you doing here? Pointing is done. Now you will see here that we have got the flag. We have got this word of Date Mains and which word is it? So what will we do in the list, we will store the word, OK, this is done, we have seen it, right after that, what will happen to you, where will the reference be from, the process from What will we do from here, we will see A. We will see here, is A present, is it not there, then it is okay, there will be no need to look for it, then we will come to this index, is A present, is it not on the root, okay let it be N What is the present and not the end? Will not look at this also. Right then will look for I. What is the present? The note which is the ball of A, is this note representing T, is it pointing to T? No, it is pointing to A, so T will go here, when it goes here from this right, then A will not be found, it will go back again. Even if you look in the direction, you will not get it will go back, right, if you come here in the mines, it will not come here we have already seen, not right here, if you go up, then that too is present here. You don't get A anywhere. If you don't get A then why should you look at us? You won't get it here. Okay, so let it be here. Then you will come to this index. If you come to T, then you will come to T. Root note. Is anyone from A doing a point? What is he not doing? Let's see this here also. This has not happened yet. Let's see from here. We will see from A. No one from A is doing a point. Then here we will see whether anyone from A is doing. What is Han doing this, he is doing it, okay, now A can go in this direction, we can go in this diagram, we will get this rice, so N, so from here N, is anyone doing this, is N getting point deducted or not? If it is pointing to A then even in this reaction you will not get A. You will go back. If you do not get A in this direction also then it will be in negative. Here A will go. Okay, negative meaning will be found in positive which is greater than this. Right, you will go greater from this column. No then you will go back to A then like this samjhaoge A so here this note is pointing to A Han is pointing Okay we can go to here now we will go to this note A okay we will go to this note A now here We'll see what rate T is, we can go here, but we wo n't get A in this right because what it's doing is just pointing to T. Okay, it's pointing to safety, so it's in the direction. Only you can get it, if you go in this type, you will have to come back, you will go and then you will have to come back, you are okay but if I you go, you will get T, got it, now got T, now we see that here is our word it. And the flag is true, when the flag is true then we understand that we have got this word right, so what will we do, we will store it here, okay, after doing this, now you will do DFS here, okay, I will also show you the code part. Okay, then we will give you the code, then let us listen to you how we have done it, what to do first is to try the implementation, if you already know, I have made a video, please go and watch that video, only then you will understand it better, okay, so I have made a separate video, watch it here, what will we do, we will implement the tree data stitcher, okay, this is how we implemented it, how we have inserted it, how we do the insertion, how we search, I have told you all these things, please go. Look look, this is the part, okay, what should be ours in try, this is your child, 26, which will be the arrow, yours is okay, it will be of no type, the child here will have 26 sides, there will be a flag, okay, it will be false, there will be a string level in the initial. This is your final string, you can see it, so we have taken the string here, okay and we have created this punch function, we have created this function so that we can do it here, insert fungus which will create it as try it structure. To implement the insert that we need, for the insert that we have done, we will do this function in it, okay, so what do we have to do in it, how are we doing it, okay, so please go and see, then we will do this. Will implement OK, now see manly this part here, you video, second, understand only what we have given in the video, OK, now we come to the DFS part and here we are telling you that we are going to cut it. What we are doing is that we have taken a set so that we cannot duplicate a word again and again, that is why I have taken a set. Okay, this is the result and what we have done in it, what have we done to each word, the date which is ours. The data structure has been stored in it. Whose insert function is this? What have you done in it? Look, the insert function is here, it is not me, it is not yours, what you are trying to do, what is the implementation here, implement it in this type. Will give you ok after inserting it then what will you get finally right now what will you do now you will call DFS when you implement difference call what will you do see we also have to keep in mind that what we are defending we when a When we have visited the word one character, do not do it again and again, so what we have done here, we have taken one m tu of size mn2n, one visit of size, okay, what will we do now with the name visit here. You will loop that so we can see what we will do for H K Okay then DFS we will call in which we will send the board that has given its board that I and K root of the cutter What is yours This is your tree Noting the root The note is ok here, we have cleared it here, we have called it here, we have sent it in the parameters, the route note is ok, result, what will happen in the result, your answer will be in the set and we have visited this. Here i ≥ both sides or k is greater. If the ≥ both sides or k is greater. If the ≥ both sides or k is greater. If the board is equal to u.side then in that case board is equal to u.side then in that case board is equal to u.side then in that case we will return right because we cannot go to it. When it is out of bounds then we will go to it otherwise we will return. Okay, now what do we do on the node? What do we do on the node? We are doing note get note board. Okay, so we will see which is our character, is there any node on the eye, is it okay? Is there any note on the character on the eye? What is this Get Not Joe, what are you doing here, Child F - A, he is giving you a note, Child F - A, he is giving you a note, Child F - A, he is giving you a note, if there is a note here on this chapter, he will give you a note, you will get a respect vice tap, okay, so what will you do here? This will give on the note that this is someone from the character, so this is what we are doing, this is what is true, as if O comes on, we are looking for O, look, is someone pointing, is Han O pointing, you ahead. Looking ahead, if the right is not pointing us, then we will return at the same time, then in each case, what was there, if you did not get any, then you are moving ahead, what is yours here, it will give you. Note get note key if there is any note then it will not be there respect vice will get tap here ok so we will check here if it is already visited or there is tap in it then we will return at the same time ok respect vice we What we will do is see that if this is your base condition, if you have gone to the end, okay note this is what is yours, you have reached here, you have come till here, then what will happen in this end, what will you get the flag here. You will get true if this is your end. Look here in this function. This is the function that is turning the flag here, that is, when you have gone to the last place, you will have got all the characters here, then you will be in the last place. What will be true? If it is true for you, then what is there in it that you have got that word, you have got the right, then what will we do in the result, the string which is on the stairs, what did we take here, another treaty? If we had a steering, what are we storing in it? Whatever word is here, whatever word is here in Word, I have kept it from SDR, if we have written the word here, then word equals, understand the level, what will we do if we get the word here. In the result, we will store our which string is ok, we have done OK and what should we do with the visit, this is our base condition and we will mark the visit as true, then we will do DFS in which of the four directions, so this is your i plus van k. Plus we will mine the van eye in the van direction and when we are back tracking what we will do is mark the visit as false again. Okay so this will be your difference calling. Okay so this is the difference part and that is the try part. Isn't it just extra in the previous video that I have made, this string level was not there in it, we have just inserted the string STR because we need it and not which word is which word, we have just achieved it, in the last if here We have reached till now, we have got it, so this is covered, how will you know that you have stored it in this friend, he will come to know, okay, this is P. If you have reached till now, then what is the word that is P? You will come to know that this is the only extra thing that has been done to it. Okay, first of all, please go and watch that video. We have stored the result in the set. So, you will get the result in the set. Then what do you do, insert it in the vector because your return type. Vector is here by turning the log factor. If it is ok then this was your solution. I hope you have understood. If you liked the video then please like, share and subscribe. Thank you.
|
Word Search II
|
word-search-ii
|
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_.
Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
**Example 1:**
**Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\]
**Output:** \[ "eat ", "oath "\]
**Example 2:**
**Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\]
**Output:** \[\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 12`
* `board[i][j]` is a lowercase English letter.
* `1 <= words.length <= 3 * 104`
* `1 <= words[i].length <= 10`
* `words[i]` consists of lowercase English letters.
* All the strings of `words` are unique.
|
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
|
Array,String,Backtracking,Trie,Matrix
|
Hard
|
79,1022,1433
|
260 |
hey guys welcome back to another video and today we're going to be solving the lead code question single number three so in this question we're given an array of numbers nums in which exactly two elements appear only once and all of the other elements appear exactly twice so when you find the two elements which appear once and you return that all right so it's pretty simple so what we're going to do is we're gonna maintain a count of how many times we come across a number and we're going to do this with the dictionary sub-county do this with the dictionary sub-county do this with the dictionary sub-county and we're gonna initialize a empty dictionary so now we're gonna iterate through all of our numbers so for numb and nums and what we're going to do is if num is not in our account then in that case we're going to add it to our dictionaries of count and we're gonna add the number and we're gonna give it a value of 1 so it has count of 1 the first time we come across it so else if num is already inside of our dictionary then we're just going to add a count of 1 to that so countin on plus equals 1 and then after we go through all the elements inside of the numbers array then we're gonna return the key value for T comma value in all of the items in our dictionary so count dot items and we're and now we need to check if the value and we're only going to return it when the value is equal to 1 so if value is equal to 1 so we're going to return the key whenever the value in our dictionary is equal to what so let's submit our answer all right see our submission did get accepted and finally do let me know if you have a better solution to solve this and don't forget to Like and subscribe if this video helped you thank you
|
Single Number III
|
single-number-iii
|
Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in **any order**.
You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.
**Example 1:**
**Input:** nums = \[1,2,1,3,2,5\]
**Output:** \[3,5\]
**Explanation: ** \[5, 3\] is also a valid answer.
**Example 2:**
**Input:** nums = \[-1,0\]
**Output:** \[-1,0\]
**Example 3:**
**Input:** nums = \[0,1\]
**Output:** \[1,0\]
**Constraints:**
* `2 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each integer in `nums` will appear twice, only two integers will appear once.
| null |
Array,Bit Manipulation
|
Medium
|
136,137
|
70 |
Hello friends today I'm going to solve liquid problem number 70 climbing stairs in this problem we are given the value n which is the number of stairs in the staircase and we are given that each time we could either climb um one step or two steps and we need to find how many ways and how many distinct ways can we climb to the top of that staircase so let's see how we could solve this problem so suppose we have a staircase where the number of steps stairs e n is equals to five well this is tier number one number two staircase three four and five so that's that now the number of ways we could reach this top staircase the top of the staircase where the number of stair steps is five so how many different ways can we reach step five to reach step 5 we need to reach step 4 right to switch step four we need to reach step three to reach three we need to reach for two and two knee to reach two we need to reach one and to reach one we need to start from the ground we are starting from the ground so how many ways can we reach one well basically we can reach one only in one way because we can only take one step from the ground to reach one because if it takes two steps we are going to reach the staircase number two so we are taking one step so that's only one way we could reach step one now what about step two in how many ways can we reach step two we could write step two from Step One by taking only one step or we could read step two from floor by taking two steps right so that will be equals to two different ways now what about three we could reach three from one by taking one step and we could reach three from Step number one by taking two steps so from 2 if we take one step um what's happening is we could reach step number two in two ways so we reached here in two ways by either taking one step on each of the steps or by taking two steps at a time right so once we reach here we from two to three we can reach by taking one step so how many ways are there basically it's two ways from step two because one way is this way and then I was one step the other one is two steps to step two and then one step to three so that's two steps the number of ways to reach uh step number two um plus now how many ways can we reach 3 from step one it is two ways right uh it's only one way because we can only take two steps to reach step number three from step one directly from one we are not talking about uh indirectly where you could from one to you could step on two and two three because we have already taken that into account while we are trying to reach step three from two so when uh directly from one we could reach uh by taking two steps and we could reach one in one step uh one way right so that will be equals to total of three different ways uh now if you may be considering in how many ways can we reach 3 from the ground well basically directly we need directly from Step 0 to step three we cannot reach it because you can either take one step and if you take one step you are gonna reach Two Step number one if you take two steps you are gonna reach to step number two for you to reach step 3 you need three steps and you're not allowed to take three steps because it's given here each time you can either take climb one or two steps so um we could reach three from one in one way and from step two in two different ways what about three what about step four uh so to reach step four we can reach it from three by taking one step and while uh stepping from three we could actually reach three in three ways right so that would mean that we could reach four from three in three different ways and we could reach 4 from 2 in by taking two steps and that would be in two different ways because we can reach two in two different ways so this will be a total of five now what about five that would be from one by one step and the number of ways is five uh five not one I'm sorry from four a by taking one step and from three by taking two steps which is three different ways so five plus three equals to it now if you would carefully look we are actually creating a Fibonacci Sequence starting from 0 1 2 3 which is equals to one plus two five which is equals to two plus three eight which is equals to three plus five Fibonacci sequence is where basically to find the next element we uh find the value of the previous two elements so to find the next element what would this be we find the previous two elements and then we add these two elements so this would be equals to 13 5 plus 8 30. so now we know how to approach the problem let's try to solve the problem so first of all I'll be taking uh doing the recursive method and then the iterative method for the recursive method what we need first of all we need to base cases so if n is less than equals to two we are going to return n because here to reach step number one you only need one step similarly for two you need two sips you could actually do it for three hours because for three you also need three steps right or you could just um perform the recursive operations so that depends on you so I'm just gonna do less than equals to two now to find the next to find the value of n I'm gonna do recursive call and minus one plus M minus 2. so if n is equals to 3 then I need the value for n minus 1 which is 2 and 4. uh one so let's try to run the code and see okay mm-hmm okay so what's wrong here my favorite course type exited what's our test cases okay so as you see our test case for five it's failing let's try it for three foreign here return and cool it's working for this case three and three border three let's change one of them to five what about when the value is equals to 20. all right when the value is 20 what about then cool it's working for that let's check for the maximum value of n which is 45 it seems to take a lot of time well it's time limit exited so we need to optimize our Solutions how could we do that if you look here let me just show you here to find uh the number of ways to reach step 5 what we need the value to reach step 4 and step three right to reach step four what do we need the values to reach step 3 and to reach step two so actually we are doing recalculating the values for 3 as well we need the value to reach Step 2 and step 1. and uh if we have n equals to 6 then we are actually doing five and four so each time we are doing repetitive uh call for the same element so we are finding the number of ways to reach step 4 here as well and here as well similarly for three also we are doing it twice for and so on so in order to avoid the repetitive call repetitive calculation what we could do is we could save the value from one of the calls in our array so let's use an array here I'm going to create a global array of the size which is the maximum size of the n and then each time what I'm gonna do is I'm gonna calculate the value and store the value in our DP and return the value of n from here so what I'm doing here is if n is suppose if n is equals to 4 then I need the value for 3 and 2. so it makes a recursive call for 3 and when it makes a recursive call for three it what it does it needs the value for 2 and value for one and it makes a recursive for call for two and we know that add value for 2 is returned from here so um Returns the value of 2 it Returns the value for 1 which is equals to 1 and it saves in the array the value of three now for uh four what we do is it takes the values okay right so if because we have already now calculated the value for 3 right so if it is in DP then return the value for the that one because in the next iteration suppose I needed the value for 5 then I could just find the value for 3 here and return it without having to calculate again the value for 2 and value for one and so on so now let's try to submit this and see do we get time error well we did not get time limit exceeded error now let's try to solve these using iterative method so we will still need our array to store the values now I'm just going to Define some of the base cases that we did for the array for the recursive function as well so dpf1 will be equals to 1 and dpf2 will be equals to 2. now while you could use a for loop as well so I'm gonna use a for loop I equals to 3 I starting from 3 because we already have one and two so I starting from three eyes less 10 equals to n I plus and then what I'm we are uh we'll be calculating the value for DPI I minus 1 plus DP of I minus 2 and then finally we are going to return the valve for DPN because that will be stored in our last element in the array and the size could be n and let's try to run our code great let's submit it cool so the time complexity for this iterative solution is off and because we have one for Loop and the space complexity is also of n because we are using an array similar is for the recursive function where the time complexity is also of N and the space complexity is O of n hope you liked it
|
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
|
451 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem sort characters by frequency we're given a string s and we want to sort it in decreasing order based on the frequency of the characters and the frequency is of course the number of times a character appears in the input string so for example here with the string tree we see T shows up once R shows up once but e shows up twice so if you were to take these numbers and sort them in decreasing order you'd get 2 1 now there's kind of a tie between these two and we know even though the numbers are the same the characters that they represent will not be the same so we'll have a t here maybe an R here and an e over here but this itself is not the final solution because if e shows up twice we want e to show up twice in the output string so we need two e and then a t and an r or two e and r and T so that's pretty much the entire problem I mean you might not know how to code this up just yet but we pretty much have solved it we can now solve this problem on pen and paper pretty easily so what exactly did I do in each of these steps let's sort of dissect it so the first step was basically to count the occurrences of every single character we can do that pretty easily with a hashmap so that'll be just big of and just counting that and putting it in a hash map also big of and memory as well so what was the next step we kind of actually skipped a step at least in the drawing because this part was so simple but let's try to dissect it we had a pretty simple example here but even this simple example tells us a lot because obviously we want any character that shows up a single time to be grouped together these should show up next to each other now the individual order of those elements doesn't matter but they should be together we should not have something like where we have two in the middle and then have a one on the left and then a one on the right that would not be valid we want them to be grouped together so to form that grouping itself we can use another hashmap now that we have counted the occurrences of every single character where like that first map would be taking a character mapping it to the count we now want to create another hashmap which is going to do sort of the opposite we're going to take the count and map it to the character but not just a single character a list of characters because that's what our grouping is in this example we would have one map to two characters a list of two characters that are T and R we'd have another group where two is mapped to just a single character a list of one character just the e but this mapping will also tell us a lot just to clarify this hash map just tells us the grouping this does not tell us how to order the grouping so in this hashmap how do we know that the two is the first element how do we know there isn't a character that shows up three times we don't know for sure well this is where we can kind of approach it in two different ways we can take the key set of the hashmap the keys in that case would be the numbers and then sort that now that's going to be n log n because the max number of keys is not going to be exactly equal to N I don't think that's even possible but it's going to be proportionate to n this is a perfectly valid solution but the time complexity would be n log n if this problem is starting to look like the algorithm bucket sort to you that's because it can actually be solved with bucket sort if you're not familiar with this I do go over it I think in my DSA for beginners course it's not like a super crazy difficult algorithm I'll show you how we can apply it here intr additional bucket sort the trivial version is let's say we have a number one and we know it shows up let's say five times I'm just picking a random number we also have a number two it shows up three times we have a number three it shows up one time we can now take this array and now that we have a mapping like a number maps to the count we can take this and sort it and I guess I can show you like what the original input might have looked like it would have 51 so it could look like this let's say we put some twos here I put a three then I put a two and then I put two on So in this we have five ones three twos and a single three and if we took this and we created this array or hashmap we could do that in constant time and then we can sort the input because we can now go through the keys of these buckets in sorted order we can put one five times by reading this value then we get to two put two three times and then we get to three put it once so this is normal bucket sort the reason it works is because we have this input set we know it's between one and three now that same guarantee is not true here so this is what our hashmap would look like in this example it actually does work we could have created this with an array of size two or a hashmap but it could be possible we might have actually had something that's more sparsely populated we might have had the key 4 and we might have had the key 10 and a bunch of other keys and we skip bunch of keys as well so it looks at first like it can't work but can you tell me something about this key set is it going to be bounded by anything well of course it's going to need to be greater than zero so let's say the key of this hashmap is definitely greater than zero what is it going to be less than what's the max possible value the key could be well it would have to be the most frequent character what could the most frequent character be like what could the fre frequency of it be probably the size of the input string right like this so n is the upper bound now what we can do is be clever we can iterate over the key set of this hashmap in sorted order for I starting at 1 all the way up until n so now we have a big O of n time Loop which will allow us to iterate over this hashmap and we might find that some of these Keys some of these candidate Keys might not exist in the hashmap that's fine we'll skip them but once we get to one that is valid so for this example when we get to one we're going to then go through each individual character within that list we're going to say okay T then we're going to say R then we're going to go to the next list we found e here but we know we have to add it twice because the count was two so then we put e twice so that's how we would do this and I just noticed I kind of did it backwards cuz they wanted us to start with the most frequent character so when I talked about that Loop let's say we're actually starting at n and then working our way down to zero sorry about that but everything else is correct the output would just be something like this instead so this way we can solve the problem o of n time and O of n space let's code it up so the first thing we want to do is count the frequency of each character we can do that with a hashmap just by iterating over every character in s in Python you can take a shortcut by creating a counter sometimes I don't use the counter because for really easy problems it just feels like cheating but even if we use it in this case we're still going to need to iterate over a hashmap anyway so I don't feel like I'm cheating in this case so this will map every character to the count now we want to put them into buckets so what I'm going to do is create another hash map I'm just going to call it buckets if you wanted to you probably could actually here alternatively declare a list but you'd have to allocate memory because you'd have to make the list of size n so you might have to allocate extra memory then you actually end up needing that's why I am in this case doing a hashmap if you know how hash Maps work if you've taken my DSA for beginner course even hash Maps actually do allocate extra memory as well so here I'm creating a default dict because I want every frequency to map to a list so the frequency of a character is going to map to a list of those characters so next let's actually iterate over the first hashmap so we can populate the second one so let's say for character count in count. items this is just a convenient way to get both the key and the value at the same time with that we want to say for this bucket with this particular count let's add this character because the order of those characters doesn't matter as long as they have the same count okay now it's time to build our result I could build it with a string so if we wanted to do that we would do it like this for I in range in reverse order remember so we're starting with the largest length and then working our way down to zero but not including zero because there probably isn't a single character that occurs zero times if it did we wouldn't have added it here in the first place and we want to decrement by one each time basically we're going in reverse order so now we have a bucket with this so for the bucket with this count we want to go through every character in that bucket so for C in this I could say result add to this string the character but we want this character to occur this many times so in Python you can actually take a character or a string and multiply it by a number which will do pretty much what you would expect so if this is two it'll duplicate this string twice and like concatenate it and then with that we're going to add it to the result and then we could out here return the result the way string manipulation Works strings are actually immutable so every time we do this we're actually creating a brand new string which is technically inefficient even though when you actually run the code it doesn't make that much of a difference so a slightly better way to do this in Python is to actually make this a list and then here we can instead of adding to the string which would basically create a new string we can append to this list and after appending we don't want to return a list of course we want to return a string so to do that we can join all of the strings together and that is generally more efficient so we can do this we want to join all the strings in this list and the delimiter between them is going to be an empty string basically we just want to concatenate all of them together so that's the entire code let's run it to make sure that it works as you can see it does and it is pretty efficient at least in terms of Big O time complexity if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
|
Sort Characters By Frequency
|
sort-characters-by-frequency
|
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string.
Return _the sorted string_. If there are multiple answers, return _any of them_.
**Example 1:**
**Input:** s = "tree "
**Output:** "eert "
**Explanation:** 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer.
**Example 2:**
**Input:** s = "cccaaa "
**Output:** "aaaccc "
**Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers.
Note that "cacaca " is incorrect, as the same characters must be together.
**Example 3:**
**Input:** s = "Aabb "
**Output:** "bbAa "
**Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect.
Note that 'A' and 'a' are treated as two different characters.
**Constraints:**
* `1 <= s.length <= 5 * 105`
* `s` consists of uppercase and lowercase English letters and digits.
| null |
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
|
Medium
|
347,387,1741
|
374 |
Hello Everyone, So the problem we will solve today is again the problem of binary search and this problem is gas number higher and lower. Okay, now let us look at the problem statement here. We are playing a guessing game. We have given the gas game. Dum game is aaj follow I pick number from van tu n means whatever is this computer it will pick any number from van to end ok now I take some x number in it you have tu gas d number vich I picked means like this in childhood we used to play like let's go, I think of a number in my mind, then you guess which number it will be, then this computer is also playing the same game that I have picked X number. Now friend, this is you and it has told you that it is yours, you think what is this Friend, I have guessed the number, is it equal to the number you had picked? So friend, look at the computer. Now I did not tell you that the number you have told the computer is equal to the number picked by it. Is it bigger than that or is it smaller than that Okay, you call the API, we called this function, which means three possible results, friend, when you called the one which is already free defined, then it brought you three things. If it is Mines Van, then it gives the answer, it means that this computer will give you the answer in such a way that if you told it the P number further, then it told you from three triangles or if you told Mines Van, then what is the meaning of Mines Van? That the number you have picked means that the number you have gased is bigger than the number that the computer has predicted, that means you have gased a bigger number or it has told you zero that the number you have gased means you have won the game, you are right. You have gased the number otherwise it will stop you, what does it mean that the number you have gased is smaller than the number that has been picked, okay it can give three possible results, so man, this is a very strange game. So okay return D number date I picked so what you have to do is tell the number which he picked Okay so this is what is our problem statement now you will say binary search how is binary search done right here. These three conditions are mentioned here where the number which you have picked and how to do it, if that number is bigger than the picked number, then what you have to do, then you will move to the left side, otherwise you will move to the right side, otherwise the same. This will be your answer, that's why there is research here. Now let's see how. Look, there is one number out of 10 numbers which our computer might have picked, so let's reduce one by one. We put the start here and the end. We put it here very intuitively, we will reduce it because we know three conditions, whatever we will receive in the API call, by calling the API, we will get mines van, it means that the number we are gassing is the one we have paid. What is meant by number is the number which has been picked by the computer, if the number is bigger than that, then see where the middle will go, it will be ours here, okay now here I am, we are there, we asked here, look, I have the number, I replied that there is a van. Meaning, the number you have chosen is smaller, that number means this number is smaller than that, so what have you done, you guys have taken the start here, you guys are okay, you have taken the start here, now what have you done now? Here again if you put binary search then where will your med be found, ours will be found here, okay now you asked API again then API can give you three types of answers so man lo what did it give you mines? Van given means just do assam, I am here, I am explaining how we are doing binary search and why are we here, so just add that she is giving mines van here, character, she is you, she can give anything. What you have done at is bigger than this Asked like this, brother, the number I have guested is six, so tell me what is its status, he gave you zero, that means what is your answer is six here, it is okay, so see, according to these API calls, we are our star. And the meaning of ' we are our star. And the meaning of ' we are our star. And the meaning of ' travelling' in us is removing it, travelling' in us is removing it, travelling' in us is removing it, like here when we are on five, the API told us that no, I had sucked the big number, so if you search in the big, then you can discard this many. Are you at all and then you are searching in the next one only, that is why we have put binary search here, then you must have understood that now that we see its code, what will we do here now? I will take brick and equal on the van, where will we take and pay, okay and I will make a made outer here and one inch aansor equal, you will keep the mines on the van, okay now I will look here until my Start less give equal tu end is ok medical will be our start plus and minus start divided by tu this will be now I will bring the response here which is which of ours will this gas get meaning which will be our number and we have given the API Opened that friend, we have chosen this number, you give the response level, then you can respond, our response can be zero, otherwise what can be our response and what can we do from here. We will do it, we will break it, okay if our response is equal to mines, that means we have gased a big number, then what do we do, we will go to the left side and check, then we will make and equal, you made mines van, and if our response is equal, I have done it. We will check on the right side because we have given the number which gas is the smaller number and in the last we will return the answer, it is ok here, now we will run it and see that the correct answer is ours, it is ok here, see how much. Easily we did binary search here and whatever number we had to search, that is, whatever number was picked up by the computer, we took that number and took it. If you have understood the problem, if you liked the video, then please. Like the video, share it and subscribe the channel. Thank you so much.
|
Guess Number Higher or Lower
|
guess-number-higher-or-lower
|
We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API `int guess(int num)`, which returns three possible results:
* `-1`: Your guess is higher than the number I picked (i.e. `num > pick`).
* `1`: Your guess is lower than the number I picked (i.e. `num < pick`).
* `0`: your guess is equal to the number I picked (i.e. `num == pick`).
Return _the number that I picked_.
**Example 1:**
**Input:** n = 10, pick = 6
**Output:** 6
**Example 2:**
**Input:** n = 1, pick = 1
**Output:** 1
**Example 3:**
**Input:** n = 2, pick = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 231 - 1`
* `1 <= pick <= n`
| null |
Binary Search,Interactive
|
Easy
|
278,375,658
|
1,961 |
hey everybody this is larry this is me going with q1 of the weekly contest 253 on neetco check if string is a prefix of array so this one i kind of look at the complexity and then didn't really think about it uh that much um basically the idea is that i just did brute force i did what they told you by adding the word and if it is not the beginning then we return force and if it is equal to a string then we return true if we cannot create um generate the entire as we return force um but that's basically if the complexes is a little bit messy we look at each word um you can say that you know um for example if word is a hundred uh if they're 20 words of 100 length you know this these are kind of expensive you could do the complexes that way but in the worst case it is going to be linear sorry n squared time where n is the number of characters in s not related to words so yeah um the reason is because here this concatenation can get very big but that said even then it's probably not that bad uh that's just like a very lazy upper bound and because that is a lazy upper bound and n in this case is less than a thousand um n squared is going to be fast enough so that's basically the idea here i kind of i don't know this one was kind of reading for me so during the contest i just did it um yeah i just kind of did it whatever uh let me know what you think you can watch you know uh yeah during the contest when i was gonna say i don't know i just kind of stopped i got distracted a little bit during the contest uh what i did was just kind of get it out correctly as soon as it's correct whatever and it's fast enough so that's basically the idea even though it's not optimal you can actually be a little bit smarter by doing it each character time in that case it is linear time um and then just check to make sure that you end in a work boundary so you can do this in linear time i did not do that so but it isn't easy so you have to do you know you have to balance doing it quickly which i did in two minutes which is not too quickly compared to these top people but you know um that's all i have let me know what you think and you can watch me stop it live during the contest next uploading is kind of a little bit sad okay hmm okay this is way weird but um weird yeah thanks for watching hit the like button hit the subscribe button join me on discord let me know what you think about this problem and the explanation and so forth in the comments or in my discord uh if you do contest you know come hang out in the discord and just you know talk nerd to me anyway hope y'all have a great weekend and stay good stay healthy the good mental health i'll see you later bye
|
Check If String Is a Prefix of Array
|
maximum-ice-cream-bars
|
Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`.
Return `true` _if_ `s` _is a **prefix string** of_ `words`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** s = "iloveleetcode ", words = \[ "i ", "love ", "leetcode ", "apples "\]
**Output:** true
**Explanation:**
s can be made by concatenating "i ", "love ", and "leetcode " together.
**Example 2:**
**Input:** s = "iloveleetcode ", words = \[ "apples ", "i ", "love ", "leetcode "\]
**Output:** false
**Explanation:**
It is impossible to make s using a prefix of arr.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 20`
* `1 <= s.length <= 1000`
* `words[i]` and `s` consist of only lowercase English letters.
|
It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first.
|
Array,Greedy,Sorting
|
Medium
| null |
91 |
hey everybody this is Larry this is day oh I guess day one of the um October Lego day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem and yeah let's get this started we have a I don't know if you can see it here because I think my face is blocking it over 913 day streak so we'll be doing this all month probably maybe we'll see maybe you get to witness the anniversary who knows anyway today's Farm is 91 decode rays message contains a to z number of mappings and then just to count right huh interesting because now it's a medium I feel like when I first learned this it was probably like a hard type thing but uh yeah I don't know anyway so I did come with a number of ways to do it um given that n is equal to 100 you could probably even be very lazy but the way that I'm gonna do it is going to be doing it top down we could recursively um and yeah I think that's the way I'm gonna do it and let's go right so n is equal length of s uh oops I like my computer by accident it won't burn until I enable that one maybe I press something else okay um oh yeah just count uh maybe Index right so then now we're getting the suffix if index is equal to n we return one otherwise if index is greater than n we return zero this means that we go over something like that then we don't count okay other than that then if s of index is equal to um oh it's from 1 to 26 so there's no zeros right so we have to do some maths here oh like not math but we have to just be exhaustive I think that's basically the way that would think about it's just literally enumerate every case right so basically if this is equal to one what does that mean if this is equal to zero what does this mean right we turn zero I think that's pretty much it but there's no uh I don't think there's any mappings there and if index is equal to one then what happens well we can uh let's just have a total here maybe we'll write a different neighborhood but first of all total is equal to count of index plus one right because now this is an a right so this is just putting an A and then now we go if s of index plus one um and of course we have to kind of so now this is uh was it six wait oh no oh for um I guess it doesn't matter that actually I forgot that uh for one that and you don't you know this is basically always true so then basically just when that first one is greater than n then total count of index plus two right so basically um just a double uh double digit number that starts at one right okay and then now let's do another one yes if index is you go to two right what happens well Windex plus one again this is if this is a B I think right yeah and then if index plus one less than n and s of index plus one it has to be in this case now it has to be between um zero and six and of course it's always going to be bigger than or you go to zero so we could just remove this then now we add count of index plus two yeah in my mind I keep on thinking about the Wild Card variation but there isn't one right so yeah okay now else in the other cases that means that this number is not zero one or two so this is three to nine and in that case we just added two index plus one and that's pretty much it really um as you can see here there's really not much magic per se I don't know if I'm describing today very well I have a little bit of a soft vote so my apologies of not talking too much but yeah this is gonna be too slow obviously but at least it gets the inputs correct I never know what to click to disappear this in the new UI still getting used to the new UI so what is complexity here right of course there's some branching so that means that it's going to get exponential unless we do something called memorization and in here you can memorize because for every if you give the same input for this function you'll always get the same output and in that world that means that you can memorize and yeah um yeah so then here now well what are the all the in that case what is all the what are all the possible inputs of Index right well index can be from zero to n or n plus one I guess if you really want to look at this bit maybe yeah um so what about the O of N and in that case we that means that this o of n number of inputs and each one will take all of one time so this is going to be o of n times uh per input together and that's pretty much it except without we have to do the memorization so the way that I do it as you know um I'm gonna actually change this a little bit um just so that is slightly easier to memorize I mean I know that doesn't change anyway but yeah now I'm gonna do has cash is you go to um false times n plus one maybe cash is you go to none times n or n plus one again this autocomplete is still bugging me someone told me that I could click on just to turn it off but as you can see I have to uh somehow subscribe to this to turn it off uh let me know if there's a way that you think I can turn it off maybe they did it I don't know if they did it by accident but it'll be funny that you know you have to pay to remove autocomplete but uh yeah I feel like they tried this in the past and I made the same comment but oh well okay yeah so then now all we have to do is just a simple thing right if has cash of index then we return cash of index otherwise yeah has cash of indexes you go to true and cash of indexes you go to total and that's pretty much the idea really and of course we should run a big case uh I guess 100 I mean 100 is going to be big enough that you know I just it's gotten big enough to time out so yeah just clearly going out of balance is not intentional but I'll answer I didn't realize that was one of the constraints actually so I messed that up a little bit but still that means that so that means that we can do how many like 30 something how much is that uh that's 9 10 so yeah foreign actually but um but yeah uh okay that looks good enough and this is relatively fast so let's give it a submit again the new UI is really weird I actually like the old submission UI but yeah but today we have a 914 day streak get a little shiny coin um yeah that's pretty much all I have linear time linear space let me know what you think stay good stay healthy to good mental health and if you're doing the contest tomorrow or in my time it's like 12 hours or something but it is tomorrow then good luck I'll probably do it but we'll see anyway bye
|
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
|
123 |
okay let's take a look at lead code 123 best time to buy and sell stock three and then if you can so i'm going to show you how to do this in a general way so that you can also knock out uh best time to buy and stella stock for so it's the exact same code so i'm not gonna actually show you how to i'm not actually gonna go through four but uh just know the difference between these two problems is that uh part three you can only use up to two transactions um that means you can only buy and sell twice and then for this part four you can buy and sell k times so there's no difference in the code so let me just show you how to do it in a very simple way using recursive dfs plus memo i will say a disclaimer is not the fastest method but i think this is the most intuitive easy to understand and you'll never have any issues with time limit exceeded or anything this works perfectly fine um yeah so let's take a look at how to do this so first of all we're given the prices of the stock at each given day and then so they're telling us that we must so if we have zero shares of the stock we can't sell anything so we can't go into the negatives for a number of shares so we can't short the stock or anything we have to own the stock in order to sell it so basically the way we'll enforce that is basically we'll have a variable called holding so if this is set to false that means we're not holding anything we don't have any shares of it if it's true then we will have shares of it so this is a very classic take or don't take type of dp problem that means it's kind of like knapsack kind of like zero or one we either include it or we don't include it and so you can kind of see that this is pretty much just like a dfs where we explore all the options um i wouldn't necessarily call it backtracking because we're not going back and like uh rescinding something we did earlier but um it is kind of like dfs because we're exploring all the different options and if you saw my previous two videos um student attendance record two and also um i can't remember the other one the previous two videos that i did were dp and i used a recursive dfs plus memo as well so you should have a pretty good idea how to do this after watching those two videos so we'll just keep track of three variables we'll keep track of the index we'll keep track of the transactions we have left which starts at two always right because it says we have two at most and then we also have a holding variable which keeps track of whether or not we own a stock so at each stage at each turn at each index we can either do nothing or we can make a transaction right so here we started out at the zeroth index we have two possible transactions remaining and we don't hold anything we're not holding any stock going to the left is doing nothing right because we're still we still don't own anything and going to the right we will buy something and so here you can see that i marked holding as true right so the one means that they are there's we're on index one and the two means that we have two transactions left so this transactions left won't decrement until we actually sell it so if we buy something that's not considered a transaction you won't decrement the transactions until you've sold the stock so you must have bought and sold the stock to be considered a full transaction so it's pretty straightforward you really just go down the line go down index by index and just try both options each time right so also you know for going to the right which is making a transaction you have to make the correct corresponding transaction depending on whether you're holding or not if you're holding is false that means you don't own any stock right so you can only buy if you're holding is true then that means you own the stock and you have to sell it right it says you can't engage in multiple transactions immediately you can't buy five in a row and then sell all five the same you can only buy one sell one so um yeah so your transaction so if you don't do anything that's pretty straightforward if you do decide to make a transaction it'll be determined by whether or not you're holding a stock or not so yeah oh shoot sorry so it's as straightforward as that pretty much you'll just you know you'll have a base case where if you reach the end of the array then obviously you should you know stop iterating if you um if you uh if you've if your transactions have gone down to zero then obviously you should break out um and at the end of each recursive iteration each recursive call you'll just return which option was better right you'll return the max of these two options you know was doing nothing better or was making a transaction better so that's kind of what you'll be returning at each intermediate recursive call and let me kind of show you the code try not to memorize it try to reason through it and yeah so basically we have a backtrack method here function here and this is where we're calling it so we're gonna just return the answer to backtrack right so like i said the starting condition is we have uh we're starting on index zero we have two transactions left and we're not holding anything and then we come into the backtrack and then you know these are the two base conditions if our index is equal to the length then we should obviously stop and if the k is down to zero that means we have zero transactions left so we should also return zero and yeah so pretty much this line right here is doing nothing right because our k value doesn't change and our holding true or false doesn't change either so then here this is the condition these are the conditions where i do decide to make a transaction and like i said earlier the transaction you make is dependent on whether or not you're holding a stock or not if you are holding something then you can only sell right so this is the logic for selling so we'll just if we're selling then obviously we'll get some money back right so we'll add the money at the current index as well as return the best result um from this backtrack i guess i should call it dfs but whatever i'll change that um and then else so if we're not holding then we have to buy so buying will put us in the negatives for the price right because we have to pay money to buy this stock so we're going to do negative prices plus the answer of this dp right here and then at the end of each recursive call we'll just return which was the better option the max of either doing nothing or doing something and you can see that i've used memorization here so this is essentially the same thing as uh you know this could be the same thing as me putting cash equals default dict int and then having you know cache of index k holding equals max of do something whatever return cache of index k holding right and then you just have the if index okay holding in cash return cash of index k holding yep so these are the these two are the exact same right so we can just uh see how that does might be pretty slow yeah so the cache is even more powerful you can do this um it's pretty optimized in python and it allows you to get rid of those conditions right here you don't have to actually check for it manually it'll uh it'll do that for you so let's take a look at if we use the cache the built-in funk tools cache the built-in funk tools cache the built-in funk tools cache should be pretty good all right so yeah you can apply the exact same logic to part four right because we can just instead of two we can pass in the whatever k value they give us right they pass in a k to us so we can just pass in the k instead of the two and that is it hope you guys enjoyed hope you guys learned something give me feedback and thanks for watching
|
Best Time to Buy and Sell Stock III
|
best-time-to-buy-and-sell-stock-iii
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete **at most two transactions**.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[3,3,5,0,0,3,1,4\]
**Output:** 6
**Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
**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.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** In this case, no transaction is done, i.e. max profit = 0.
**Constraints:**
* `1 <= prices.length <= 105`
* `0 <= prices[i] <= 105`
| null |
Array,Dynamic Programming
|
Hard
|
121,122,188,689
|
236 |
hey everybody this is larry this is day 26 uh no free coins of the lego day challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom lowest common ancestor of a binary tree lca so this one it's going to be a medium so it probably doesn't need it but there is something that if you want to observe core uh binary lifting uh definitely check that out but it basically allows you to pre-process the basically allows you to pre-process the basically allows you to pre-process the structure um in a uh pre-processed structure in a good way uh pre-processed structure in a good way uh pre-processed structure in a good way and there's also just really it's called um i have a name for it but it's just like an there's a linear time uh proc pre-processing uh proc pre-processing uh proc pre-processing uh constant time uh query algorithm uh i've i don't that's a name but it's by like a couple of professors and in uh walkers and stony brook or something like this uh but anyway okay but i guess that this is just like do it once maybe yeah so you did one so you have to do it and i think that's pretty much it so what is um do you have to do an over one space or anything like this now so the idea here is there a couple ways you can do it do that i'm going to do it is just by walking up the tree uh like in conceptually the way that you would want to do it is by walking up the tree but i don't think you are given the parent of the tree or of the node right so you have to do something a little bit funky uh what is n is 10 2 or 10 to the fifth so yeah um yeah i mean we but i mean i think it's going to be linear time anyway just because i think in the worst case you can imagine like two linked lists connecting at a spot but i think the first thing that we should do that i will do is by finding p and finding q and then we'll walk up to three and how do i walk up to three um yeah uh there are a couple of ways that you could play around with some optimizations for sure but i'm just gonna write it as you know as possible by having a function so we have a fine function that basically gives me that for a node we want to for now find or find the path from the root to this node right so in this case yeah um and in this helper i would have something like call path and then we'll return path at the end and then we'll even have a basically a depth first search or something like this to find the node right so yeah so let me do a different search of the root and maybe i'll call this target maybe this is a little bit better right and then you go if node that value or if node is none well then we return i don't think that should happen unless we're giving zero nodes but then yeah uh actually that's not true yeah depends how i want to write it but yeah um and then we go if no dot value is equal to target and they're unique right yeah they are unique so in this case we're not looking for the value anyway we're looking for the note itself so that should be good so if this is the case then we can how do we want to do it um let's just maybe i can do so i'm kind of just a little bit hacky the way that i'm doing it so okay let's just do this then uh it's not the cleanest whatever but it'll be okay then yeah then we return path otherwise this is a little bit awkward actually let me think i mean this is just syntax in any case it's not that big of a deal but okay maybe the way that i would write it is just using a global thing so yeah so yeah uh found is equal to say none and then we just do this thing and then we go we turn down right and if it's not you know we return to none it's returns not just target then found is you go to a copy of the path and then we return otherwise yeah otherwise if on the recursion i would also just check if round is not none then we return just for an early termination it's a minor optimization really it's still going to be linear in the worst case anyway so yeah and then this is uh yeah path what we want to do is you want to append node.left and then this want to append node.left and then this want to append node.left and then this is post dot pop and then do the same thing but for the right and then yeah and now we now look for the path p is to go to find of p right and then path q is equal to fine of q so then that means that now if you have the paths then the lowest one will just be the one where you know you keep going right so yeah so i do so i is equal to min of say length of path p and length of path q and you could write this both ways and this one is a little bit slower in that in theory you can express the p instead in terms of q because now you're given the path p you could search for where um where it is in q but it just requires more code so that's why i didn't do it yet um this is an i this is say m from some reason at max right if path of p i is not equal to path for p or q i then we return the la uh the note before this right so i minus one and this should go one anyway so yeah otherwise we return none maybe you know that doesn't make any sense because it is well maybe one of them is not found or something but that doesn't yeah uh oh you have to do none local fail why do we that's weird all right let's print out the path real quick maybe i'm just not finding it correctly this is kind of hard to read to be honest but this is just like printing everything but see maybe we can write this a little bit uh someone like this so now we're shadowing so we have to be careful just okay why is it not um this is so annoying even debugging i am i think you see me getting old right before your eyes okay so this is five one so we're looking for five and one did i mess this up so we append we pop oh we don't append the root so that's probably why so okay well that's one of the reasons why i don't know that's the only reason why um okay so three and five three and one so okay so that way i also get the wrong one now five and one yeah three and five and so it was returned the right thing three five two oh okay so basically yeah i mean this is kind of right but then here is what we want is actually the last number match not the yeah the last number matched or last note matched so yeah okay there we go uh sloppiness on my point it's probably things that i probably could have thought about but i don't know maybe i'm just being a little bit off lately maybe i need a break to be honest because i've been kind of um i think one of the anti patterns i've been doing is that i've been kind of lazy so i've been letting these testing handle the thinking for me but when i'm missing a little bit on the tests uh that's when things go wrong um and also i need to be better about reading but that's another story anyway let's give it a quick submit hopefully this is good and not two yikes um well this is maybe faster than last time what did i do last time but yeah um this is going to be linear time linear space and that is or you could also say maybe depth of the tree as the space but that is also going to be as good as it gets because that is the size of the out well it's not the size of it but you have to look at every node once right so um to find the nodes i'm curious what i did last time and why it's slower it seems like i did the same thing but i just wrote it in a cleaner way because i'm not creating new lists all the time and also i thought about writing it this way to today to be honest um or the true enforcer tuple by dart it's a little bit messy so i don't know how i feel about it but anyway the idea is mostly the same though so yeah um that's what i have for today so let me know what you think uh is this does everything show up on screen i guess so okay yeah uh let me know what you think stay good stay healthy to good mental health i'll see you later and take care bye
|
Lowest Common Ancestor of a Binary Tree
|
lowest-common-ancestor-of-a-binary-tree
|
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)."
**Example 1:**
**Input:** root = \[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` will exist in the tree.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
235,1190,1354,1780,1790,1816,2217
|
88 |
welcome to january's eco challenge today's problem is merge sorted array given two sorted integer arrays merge nums two into nums one as one sorted array the number of elements initialized in nums one and nums two are m and n respectively you may assume that numbers one has enough space to hold the additional elements from numbers too basically we can see with numbers one we'll have a bunch of spaces here marked by zeros and these are going to account for the elements inside of nums2 we want to insert those into nums 1. it's a little bit different from a linked list we want to do this in place and use a regular list so to do that what we could do is you still use the same approach as merging two linked lists we'll have two pointers to say i and j indicate to us where we are at inside of numbers one numbers two and we're going to check to see which one's less and whichever one's less we want to update that in nums one right but that's a problem right because um if we update nums one then we're going to lose some information there so we're going to have to store nums 1 somewhere as a temporary list so i and j are going to be the pointers and k is going to indicate to us where we are at in nums 1. so all these will be 0. now the algorithm is pretty much the same we say while i is less than m and j is less than n we want to check to see uh which one is smaller so first thing to do is to store nums one somewhere temp as a temporary array uh what i'm going to do though is make it a copy because i don't want to do by reference otherwise it'll update right so here we'll say if let's see here uh i should say temp i is less than nums to j then we are going to update numbers one with we use k to indicate to us where we are in numbers one and we'll make that equal to temp i then we increase our i otherwise we're going to do it the other way we'll say numbers one k is equal to nums two j and we'll increase our j finally make sure to increase our k pointer to continue on our nums 1. now whatever's left either numser or numbers 2 we want to add that to the rest of the to the array right so uh we can just do the same thing while i is less than m uh if this is true we are going to take num i'm sorry k and equal to temp i increase i equals one and k let's go to one hold the same thing here j is less than n numbers one k is equal to nums to j and increase k now we don't need to return anything because we're going to be doing this in place so let's make sure this works uh looks like that's working and submit that okay so this works of end time complexity we do use some extra memory for this temp variable or temp list are there any other ways well um one way that actually works which surprises me is we could just delete the numbers inside of nums to begin with and extend it with nums 2 then sort it we could do something like that to do that you would have to do it in place so what you can do is say delete nums i from m on delete all that then we could extend our nums with whatever's in nums 2 and then we can just sort it in place here this would also work and it looks a lot cleaner but as far as i understand sorting it would take n log n time so this is actually slower technically but for whatever reason when you look at the details it actually is faster that might be something to do with how the function sorts maybe that's just a better algorithm inside there but this is kind of dependent on like a lot of the under the hood stuff so probably the other answer is more explanatory inside of interviews anyway it's nice to have an easier question after like two really hard ones so hope that helps thanks for watching my channel and remember do not trust me i know nothing
|
Merge Sorted Array
|
merge-sorted-array
|
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
|
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
|
Array,Two Pointers,Sorting
|
Easy
|
21,1019,1028
|
1,822 |
hello guys welcome back today we are going to understand this quality question right uh 8 18 22 sign of the product of an array so we have the we have uh there is a function we have given sine of function X that will return uh one if it is positive minus 1 if it is negative and 0 if it is equal to 0 so we have given an integer nums and we have to uh find the product of all the values in the array right so uh we'll do the all the product of the given value in the array nums and we'll return that function if we'll find the which will return the product whatever the product will come up from the nums element that will pass into the sign of this number let's suppose we have given number nums right this is the array integer side and if you put into this value it will give you some value like one why because this is the product of all the values is coming out 144 and it will give you uh What uh 144 is just a positive number so it is saying this is a positive number if this is X is a positive number return as one if it is negative number is done a minus one I visiting if it is negative number return minus 1 if it is a positive number return positive if it is 0 put 0 right like this so this is the thing right we have right so if you do this uh multiply the product it should become some number right like this we are getting three uh examples we have right so if you will do the product of all these numbers we are getting what 144 right why we are getting uh let me tell you why okay so I'm coming back to here let me show this is another example that I was talking about okay so I'm talking about this one I have uploaded this video uh you can see yeah okay so let's suppose we have given this example okay so to understand this example if we'll do the multiply right ah why it is coming 144 right so first how many negative numbers we have minus one we have here minus one we have minus one total four minus and we know that if there is a minus 1 into minus 1 right it will become plus right so four times if we'll do minus 1 it will become what positive number so the total sum of the positive number of the minus if it is even number of negative numbers so it will become the result will be in the positive correct and if there is a odd number of uh negative right negative the number will all be negative so that we have to take care of right another thing yeah that this is the first rule will take so second rule will take what if we have uh zero in the uh multiply if it is ah if it is 0 in Array right in Array value will become what zero right if there is a odd minus and this that's why right so what we will see here will uh if you do the multiply of this number we will get what 144 so it is saying that if sine function will take X right so if x is positive it will give 1 if it is 0 it will give zero if this is minus 1 right or minus value it will give minus 1 right like this we have to do I think you got if not let's understand here so now what we will do we will create one uh function right here we have the uh we have actually this function array sign and we will pass this value right here so we have to return in such a way uh like uh the value will if there is a number of negative numbers we'll decide the result and that result we will put into the function that function will return the uh you can say result right if there is 0 minus 1 or positive value right that we will say so we have to concentrate on Computing the number of negative numbers that we have in these numbers array so because we only need the sign of the product of the values right so if the number of negative number if the negative number is even the final product will be positive numbers right and because when you get two negative numbers cancel each other uh out to the once the positive uh number will get bodies right so if the number of negative number is odd the result will be negative number and if there is a 0 in the nums right we will return 0 directly because uh the product will always be 0 right so I think you understood let's suppose uh we are going to create here uh this one right uh what we can say the function right so how will develop the function right so first of all we'll create a you can say count number of uh negative number right number of negative okay how will find the negative sign right to find the negative sum negative number right however what we will do will in slide with the zero just for example and we'll take at integer okay now what we should do we have uh this num side so on this nums we'll make a loop right so to find the make the loop right what we should do we will take integer n and let's start from here okay so one by one number will come and we'll do the uh you can say multiply right so if our and the element at uh array I layer suppose it is coming is zero okay so at that time what we should do will return what 0 because if any number is coming as a 0 will return 0 right if not if n is less than 0 means it will be minus side it means we have to return What minus right this here just for example but we have to find here how many uh negative numbers we have right we can do here directly but the question is there is two negative means it should become what it should become ah you can say the number right so what I'll do I'll provide here like this but I'll do plus next time it is coming 0 the first zero is if there is the num array is containing only one uh minus one so it will the value will be What minus one right because this is 0 right so it will return what ah one minus 1 right 1 minus and if there is 2 then it will become what plus that's why we will take like this right but this will not decide the result right this decide who will decide the result after this for Loop how to will after completing this for Loop we have the number of negative counts right so if the negative counts we have right if we'll do the modulo right and we'll do two right so what will happen will take if it is 0 means what this is some negative number is sum so we'll return 1. if not we'll return What minus 1. correct if it is divide 0 means this is sum if not it is my is its negative number right odd number is the result will go negative so the function will take based on this value and it will return you the result right let's submit this one got to happen why it is not coming or wrong answer um 0 1 y first of all I have what I have taken we have taken what uh we'll start with negative number is zero if we'll come here if num is equal to 0 will return 0 right if uh n is less than 0 will return uh number of count we will do plus correct and once this is done right this for Loop is done I'll come to here will divide by 2 if it is equal to 0 say We'll return 1 if not we'll return minus 1. it should work if it is equal to zero okay let me divide now we divide by 2 and if we divide by modulus no reminder will come only from here only right or tab pen no sorry it will not return we will not return there actually okay it should work now yeah actually I'm returning at night we should not return that one thank you guys thank you for watching this video If you like this video please hit subscribe this channel right so you will get more video like this okay let's understand now complexity we are taking we have n number of clicks our n number of elements we have into the array it means the length of uh array is num side it means uh the time complexity will convert TC will come of n because we are moving or the for loop with all the elements side that will come and we are not taking Extra Spaces right so TC sorry space complexity will become of one thank you guys thank you for watching this video
|
Sign of the Product of an Array
|
longest-palindromic-subsequence-ii
|
There is a function `signFunc(x)` that returns:
* `1` if `x` is positive.
* `-1` if `x` is negative.
* `0` if `x` is equal to `0`.
You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`.
Return `signFunc(product)`.
**Example 1:**
**Input:** nums = \[-1,-2,-3,-4,3,2,1\]
**Output:** 1
**Explanation:** The product of all values in the array is 144, and signFunc(144) = 1
**Example 2:**
**Input:** nums = \[1,5,0,2,-3\]
**Output:** 0
**Explanation:** The product of all values in the array is 0, and signFunc(0) = 0
**Example 3:**
**Input:** nums = \[-1,1,-1,1,-1\]
**Output:** -1
**Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1
**Constraints:**
* `1 <= nums.length <= 1000`
* `-100 <= nums[i] <= 100`
|
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
|
String,Dynamic Programming
|
Medium
|
516
|
92 |
hello everyone so in this video we are going to solve a question of fleet code that is reverse linked list2 so let's start with the problem statement given the head of a secret linked list and two integers left and right where left is less than equal to right reverse the nodes of the list from position left to position right and return the reverse list right so basically in this question we have given a linked list and two positions that is left one and right one and in for this position we need to reverse the linked list right we need to reverse the linked list from left position to the right position and return the reverse linked list right so let's see the first example so in the first example we have 1 then we have 2 right then we have 3 then we have 4 then we have 5 so basically we have given 5 nodes here right so for these five nodes what we need to do is let's say we have given l is equal to that is the left one is equal to two and right is equal to four right so we need to reverse this from the left position to right position right this we need to do so let's see we are just need to reverse this part here right so let's quickly see how can we perform this reverse operation here right so to perform this reverse operation we will be using some pointers right so we can easily reduce the time complexity as well as space complexity by this approach that's why we are using pointers here right because these are the constant pointers so let's do this so for these pointers let's say we need to rewritten the linked list right we need to written the reverse linked list so there might be the possibility that this first node will also be reversed so there might be the new node here right so in this condition we need some reverse memory or the temporary memory which will be keeping a point at the first node right we need something so for this we will be placing a dummy node here right so let's say we kept our dummy node as 0 here to keep this to keep any of the node or we can say any of the next node of the dummy node is the head of the linked list right so whenever we will be returning a linked list from here we will be returning the dummy next right because the mean x will always be containing the head of the node right it will always be pointing to the head of the linked list right after reversing or performing all the operations right this might go somewhere some other position but the head of the necklace of the ori of the reversed linked list will always be pointing to the dummy next right so let's see we have kept a dummy node here right so this is the first step we have kept the dummy node and pointed this dummy node to the head of the linked list right so this is the first step now let's see the second step now the second step is we need to reverse this part right we need to reverse this part so to reverse this part we are keeping two pointers here right so since we need to reverse this from two so let's see we kept a current pointer here right let's say we kept a current pointer here all right this is current pointer and the second pointer also we need to take is the previous one previous is basically the previous point from the current one right because this previous will always be fixed here right previous will always be fixed here and current will always be fixed right these two will be fixed and we will be taking a temporary pointer to manipulate the value because we need to shift this three and four in between of this one and two right we need to shift this somehow in between of one and two because we need to reverse the string from two to three so this two will go to end of the sub string and this three and four will come before two right so let's see how we are doing this right so till now we have kept this previous and current pointer now you must be wondering how we kept this pointer right here we have just placed but how can we do it logically right so there is a very simple logic for this right there is a very simple logic since this is the second node from the original linked list but in this case we have taken a extra node right so this is basically the l plus one eighth node right this is the l plus one is node it means the previous one is the lth node right it means the previous one is the ls mode so what we can do we can just do iteration l times right since it is a lth node so we can do l time iteration to point this previous node from the dummy node right let's say we put uh we point the previous node to dummy node initially and we will just iterate to previous next each time till l positions right so for this is the second position from the dummy node so we kept previous year and the previous next will always be the current one right because the current before is always the previous so previous next is always the current right so till now we have kept this previous and current point right now the next step and the very crucial step for this is we need to reverse this part right we need to reverse this part somehow so let's see how can we reverse this part right so there is a very simple approach for this so let's say we keep a temporary pointer here right let's say we keep a temporary portfolio so let me write the steps side by side right so let's take the first step is we kept a temporary pointer that will be equal to the current one or we can say that will be equal to previous next right this is the first step we perform now the second step let's see the second step is we need to point this previous next right we need to point this previous next to current next right somehow so what we can do is we can find this previous next let's say we write previous next is equal to current next right this is the second step now why we have done this because we are just performing the iterations right we are just performing the iteration and how many times we are performing we are just performing this l minus or we can say r minus l times because we are just performing this r minus l times because we are currently at this node and we have to perform this still here right so what is our r is 4 and l is 2 so 4 minus 2 is equal to 2 so we need to perform this to the next two nodes from the c right from c we need to perform this two times right so we will be performing this to r minus l times right so this is clear i guess so let's see the third step so in the second step we just perform previous next to current next right and in the next iteration we might be changing this to three to four right or we can say previous next to four in the next iteration but in this iteration you only need to do this three right because in the iteration we will just point this c to one right then one two four right this is the iterations going on right so let's see the third step so we just change the previous next from here to here current next right now the next step let's see the next step is current next right current next this is current next right this is current next now this current next will be pointing to current next right this is current next and this is current next right so this will be pointing to current next right so this will be removed from here right this one will be removed from here and this will be pointing to current next right so this will be current next is equal to current this will be current next and this is current next all right so these are the three steps and the only remaining step is right the only remaining steps is you must be observing this is the this one right this is this one so for this what we need to do is we need to point this three to two right because for by performing this reverse this string will be reversed from one three two and four right and in the next iteration this will reverse to one 4 3 and 2 right so that would be the reverse string so for this what we can do is we can just find this is current next or we can say this is basically the previous next height this is previous next this is the previous next and this is next so this is previous next so the fourth step would be previous next at previous next will be equal to temporary one right will be equal to temporary right so you must have observed that why we have kept this temporary because the positions might have been changed that's why we kept this temporary so that we can easily point at the end right so we have just removed this from here so the updated linked list would be one now this is 3 now this is 2 now this is 4 and now this is 5 right and now in the next iteration we will just reverse the positions so now this 4 will come here and the updated or the final reverse linked list would be 1 4 3 2 and 5 right this steps these steps will be iterating two times right so in the first iteration we will get this one and the second iteration we will get this one right so i hope the approach is clear to you if you still have any doubt in this approach feel free to comment it down i will try to explain it again let's move to the coding part so in the coding part let's first take the dummy pointer so this is equal to list node dummy right and let's initialize the value like say this is the dummy right we have taken this dummy so dummy is equal to new list node 0 right and also take two more pointers the previous one and the current one right and the previous is initially pointing to dummy right we have already discussed this previous is pointing to dummy and this previous will be updated till l times right so let's write the same here previous it's initially pointing to dummy and this one current will be empty right so now let's update the position of the previous one right so to update the position of the previous one let's run the follow for end i is equal to zero i should be less than left and i plus right and let's update the position so previous is equal to previous next right so it will just move the previous still l minus one at the node right so let's see now this current is always the previous next right so let's write the same here this current is equal to previous next right i hope this is fine so now let's try it for in i is equal to zero like we need to reverse the central part right this part from left to right at this part from left to right so for this lesson the for loop from 0 to r minus l at r minus f so let's write the same here i is equal to 0 i should be less than right minus left and i plus right now let's write these four statements here right we are just writing as it is so let me write it here let's write list node temporary is equal to previous next right and this what are these condition this is previous next is equal to current right we just move this previous next to current so let's write the same here previous next is equal to current next and this current next is equal to current next and at the end we did previous next is equal to this one like temporary one and we have just already discussed all the four statements in the explanation part right so at the end just return dummy next right you already discussed why we are returning dummy next right because dummy next will always be containing the head of the reverse linked list right so let's now quickly submit this or try to run this on the sample test cases oops we are getting an error here let me check um this is not finding the previous null point yeah we forget to point the dummy next to head because this nummy node is initially pointing to the head of the linked list then only we can traverse the previous pointer till the other position right so this should be dummy next equal to head right and also let's check it again um this should be left minus one because we are just iterating till left minus one right this is the left one so this should be left minus one right so i hope this should work fine now let's try to run this again yes working fine so let's have to submit this yeah it's working fine so the time complexity we already discussed is we go of n because we are traversing through all the n nodes only once and space complexity is becau of one that is constant because we are not using any extra space here all right so that is it for this video i hope the approach and solution is clear to you if you still have any doubt in this question feel free to comment it down please like this video and subscribe to our channel i will see you in the next video
|
Reverse Linked List II
|
reverse-linked-list-ii
|
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass?
| null |
Linked List
|
Medium
|
206
|
35 |
hello guys in this video we will be looking at another application of binary search through problem number 35 search insert position in this problem we're given a sorted array of distinct integers which means no repeats and their target value and we need to return the index if the target is found and if not we will return the index of the position where would we would place the target value at all right let's look at a few examples so in this scenario and in this problem we will still apply our binary search technique to solve it so as before we would set low to zero and high to length of list minus one so in this case it will be three and we will calculate our middle which would equal low plus High 3 divided by 2 which equals one so we check one and since 1 which is three is less than five which is our Target value we would set low to Middle plus one which would make low 2. so it would recalculate middle to be low plus High divided by 2 which equals two and since two is five which equals our middle value which equals our Target we would return middle and be done with the problem now we need to consider a few the scenario where the return our Target value is not within our array and to do so let us first look at two of I would call Extreme examples of inserting values at the beginning and the ending of the list and I will show how we can use binary search to be able to solve both scenarios so in this scenario our Target value is one which is not within our list and we know that the interposition or our final answer given would be zero so if we once again deploy binary search setting low to zero and high in this case I believe to six and then we would keep returning middle value which would in the end decrease our high since the target value is the lowest value or even lower smaller than the lowest value of our list so high with continued decrease all the way to since our while loop is still while high is larger or equal to low so the final case we have to consider is if both let me use a different color high and low and in this case middle equals zero so with if everything equals zero at this point our Target value is still smaller than the middle value so by our code Pi would continue to decrease and if High decreases then our while loop will no longer function as high would be smaller than low and we will break out of the loop and in this case the value of our lowest value 0 is the correct answer for our Target and now let us look and what would happen if the target value is larger than the largest value in the list and our return value in this case would be seven so seven would be our correct answer so we would once again deploy binary search doing the same thing here but in this case our low value would continually go up until we reach 6 which equals our high value which equals our middle value and even in this scenario the value given is which is eight is still smaller than our Target value and so in this case since it's smaller we would have to add we'll have to change our low variable to Middle plus one which in this case and that oops sorry which in this case invalidates our while loop and we would return middle plus one which in this case is seven and we will still have the correct answer so let us do one more example so in this case we would use binary search again with low being zero and the high being I believe in this case is five middle would equal to 5 divided by two which equals two and two in this case 0 1 2 is 5 and since 5 is larger than two high would equal to 2 minus one which in this case we would recalculate middle to one divided by two which is zero similar case here with Middle testing out zero and we would find that in this case the middle value is smaller than our Target value so low would equal to Middle plus one which equals one in this case and we would recalculate middle taking a different color middle would be one plus one two divided by two equals one and since in this case three is larger than our Target value we would have to decrease high but in this case since high is already one by decreasing High we break out of the while loop and returning middle on the returning Low by when we break out of our while loop which is one we will still get our correct answer which is the position we would place our Target value which is here in index one all right now that you know how to use binary search to solve this problem let us call out our solution now code out our solution in Java first we will initialize our variables with low and high so int low and in the high with high equals nums Dot length lot length minus one and then we will start our while loop so in the wild will be while high is larger or equals to low and in the small Loop we will first initialize our middle variable being equal to High plus low divide by two we don't need a double divide here unlike python and don't forget the semicolon and if nums middle is larger than Target if nums metal is larger than our Target and then we would change our high value to Middle -1 semicolon and else if nums middle -1 semicolon and else if nums middle -1 semicolon and else if nums middle oops misspelled metal now this middle is now smaller than Target so Target is bigger then we will set our new low variable to Middle plus one then oops semicolon and then the final scenario which we can consider is that else if they're equal then we will return middle and if the while loop fails to give us the correct solution being that the target value is not within our array we will return low which is the position upon which we would insert our value for call the semicolon all right let's try one more time yes all right thank you so much for watching guys please like comment and subscribe and as the cool kids would say until we code again
|
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,791 |
welcome back friends today we are going to solve record problems 1791 find center of star graph there is a undirected star graph consisting of any nodes labeled from 1 to n a star graph is a graph where there is one central node and exactly n minus 1 edges that are connected the center node with every other node you are given a 2d integer at the edges where each edges i is from ui to here indicates that there is an edge between the node ui and vr return the center of the given star graph so as you can see this is the one example they have given us and you can see 2 is the same as you know visually we can see it here so let's just take this same example here and we will discuss how we can solve this problem so uh n is actually given his number of nodes in the graph right so in this case n is four right there are total four nodes one two three four so what we are going to do is we are going to iterate through the edges that they have given us so they have given us these edges so we will iterate through the edges and we will create a hash mark from that right so for example hash map will have a key and value pair right so let's just have one our uh hash map here for example okay so let's say there is a h one two so one two we will say there is the entry uh so one is one of the node that we found in this one two and three so we would mark it as a one and two is also one of the one two right so floats and destination we will mark as one as a count right here so that's how we will uh do it and we will take another edge here so one two we are gonna so one two will have done now let's check two to three so two to three is another edge so we will again read it uh from and two value from the edge so front is let's say two right so we will increment the count of two here because two is already there so we will make it two here and three is not there so we will add entry of c1 here right okay so after that we are uh we have to consider this last h which is the two to four again we will check if entry for the node 2 is there when we find the entry we will increment it by one so it becomes three four there is no entry so we will add one more entry here for the fourth so after we are so now we are done with all the edges right so we will we have our hash map ready now so we will iterate through the hash map and we will check if any entry has a value one less than the number of nodes which is number of nodes is four here so we are checking for the value which is four minus one which is three right so three entry we would check into the hash mark and we will find this entry because two has so let's just quickly discuss this implementation here so as uh you know as i mentioned we will create a map here so we define the hash map here of integer comma integer and n is not given to us directly so we just took n as zero number of nodes and as we iterate through the edges here we will keep track of the maximum number of uh you know we find actually during iteration so maximum is four so we will get nh4 here so this is nothing but we are just reading it each edge here and we are getting a command to from this array e01 and then we are just either making an entry into the map a new entry here if it's not there or we will just update the enter here by one note so we will do it for both from and so there are two cases here right from node and two node so we have to do it for both the cases and at this end of the loop here we are actually populated our hash mask and we will iterate the hash map here and we will just check you know if the value that we get for the node in the hatch map if it is equal to n minus 1 then that is our answer that is the center of the graph r and we will just return the r here so i took the two examples they have given us here so these are the first two examples and i created one another example one three comma two three so for example in this last example as you can see three is the center of the graph because it is connected from both one and two so let us just quickly run this code so the code is working fine so it's giving the correct answer so let's just submit the code yeah so the code got accepted so um this is how we can find you know the center of star graph so here uh we are actually just like iterating one through all these edges and we are just creating the hash map so uh you know like uh you can say that it's just like order of 10 because we are iterating and creating the hashmap from that edges so that's the solution for this problem if you like this video click on the like button and subscribe to my channel i often play i often uh put videos regarding you know java day to interview questions and leapfrog solutions so if you are related to this uh stuff you know subscribe to the channel so you won't miss any further thanks for watching
|
Find Center of Star Graph
|
richest-customer-wealth
|
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph.
**Example 1:**
**Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\]
**Output:** 2
**Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
**Example 2:**
**Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\]
**Output:** 1
**Constraints:**
* `3 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* The given `edges` represent a valid star graph.
|
Calculate the wealth of each customer Find the maximum element in array.
|
Array,Matrix
|
Easy
| null |
459 |
Hello guys welcome to code basis our question of today is repeated something pattern we read the question is saying given in this string check refrigerated can be constructed by taking suffering of patent pending multiple copies of substance to weather you may zoom given String consist of lower case English letters and friends will not exceed the road that something is telling you that keep us and in were we how to subscribe from that we do not paint our multiple times on our own so that the whole spring collect Once the mix is done, let's understand that we have mix is done, let's understand that we have mix is done, let's understand that we have given an example, the input is one day only, we have to subscribe, do it multiple times in ourselves so that it is more interesting in this, we can see how this which we ourselves If we do, then this is why the original hates him or not, now if you see the school, will he take Bigg Boss, will he not be able to give us two jaals and if we take even one, then it will be the same. The answer will be no, only one thing can be made in this, so we have to find at least such a person who will paint at least twice, total twice and gift as if I had cash, now we see them as husbands in this. ABCD four ABCs are given, so here we can consider ABC as one of the lions. If we paint the body again and again, then everyone will come to the meeting and we can also consider ABC as all of us, which we can consider in ourselves. If we paint one more time, I will get the final posting, so once we saw the approach of Miss, how will we propose this question, so they have given us this trick, easy, now what do we do, let's go and try, we will do that much loop. Even when the high is caused due to the intense thoughts, you have zoomed in, this is all the screen, we will check, this is the most till here, she can make the rest of our screen that we will take back the disease, she can cut it, so what have we done. Singh is a single theater so that means the length of the screen has stopped now we started traveling on the remaining screen from single and only so we saw on this also you are strangers so I saw whether this chief who is equal is Means it is equal to testing, if not then we will stop the policy from here itself. Now this cannot be our fitting that set my posting open. Now what did we do? We moved our loop forward. So now we saw that this is However, now it has come up, I have no longer seen whether it is AB juice print made, can it be our such Sachin, system paint among ourselves and so our inputs Indore, so what have we left to do, cutting a string of travels on the remaining spring which It is a string of two lengths, it is made like a string, so whatever travels we will do in the remaining meetings, we will do it with senses only, we will see that this is also ours, this is our apk file, during this time the system is equal, so yes, the answer is here. But it is true, now we have seen that this is also equal to these two land systems, so here also the answer is correct, which is when my entire shooting is over and the answer was still coming true, so it was return true. If you give then the answer will be through, we will fold it like this, now we give another example where the length of these postings is made, now when it is interesting, then we will give the answer to it will be Delhi Polls, it will be for you because we have to repeat our skin once in the athlete list. It means that if you set a basting then you will come to the minimum balance, then this answer was wrong. Now let us see the answer example only and see if this is here since you will come here, then the length of the prince is one. Jonathan is doing a fit now we have done stale make up travels now we have seen here is it a moment or not you have returned the answer call from here now we have come to AB and string Whatever is there is ready, now we have to see what spring is left, AB, this and ours can be made from ABC, although it cannot be made, but let's see, now if we break this length of Vishnu, then we are left with A 22 land system in the district also. We will compare it with its original substring. You saw that you AB, it is well, so here our answer will be hit, the loop will proceed further, whatever trick is left with you, we have one which is all right, it is absolutely amazing. So if it is not there then I will fold the return from here. Now let us keep one thing in mind that whenever Dwivedi Something was made, we will consider it only if it is our length like its 1234 is the increment of Puri Something, the length of posting is five. Have we ever cancer this vegetable when this factor is the length of this string means we ca n't just consider the tool N C U here see that we will paint the setting of two lens multiple times a to each other so that Look at the answer, will she leave till here or will she give one lesson? If you see the answer only in multiples, then you and Piper PA-28 are not multiples, Piper PA-28 are not multiples, Piper PA-28 are not multiples, so we cannot computer the length of such a string which is called multivitamin appointment. If we do then the length of the string has not yet been made, similarly in this case we can never consider the MP3 length of this film that when we can make CNC bells, sorry for and we cannot consider that we will consider shaking Bheem on the four lane. So the answer to be spoken will be either eight or butter, it will never be six, that is why when we are considering the screen as a contender, now we have to keep in mind that it should be a multiple. The Sun is the only confirmation of the length of our entire screen. Now let's see the system portal. Tomorrow morning first of all we set up our acting variable. This is good for testing. In which we will start our current contender. Contender means our substring is the content of creating Jaipur district. Now we will roll it in our Let's put a loop on the original spring that it will run till I plus divide. This is it. We can set the minimum like if our loop will not run till driver two then one point of ours will become Sachin and the children will become meeting. This one is this one. I am gifting you this one, Sachin has become a child, Sting has two lenses, so sometimes all this print, sometimes all this will not be able to complete the feeling, so we will run our look message till Bible two and we will repeat it once in the video. So we have to divide by two, so now what do we do, we clean the my current content and add in it, now the bank which has become my canteen, if we understand from the example, then our front neck has now become this which is a contender. We will check whether the length of my tablet is getting completely divided. It has come from England. Only if it is getting completely divided, today we will paint. If it is not getting divided then the Luta loop will continue like this. Now you We have explained why it is important to have a divide, so now what do we do, we pass the stuffing of our children to a function and in the same function, we will fill the stuffing of our current contender string which is the most English. Let's send s.st. Hey, this is send s.st. Hey, this is send s.st. Hey, this is my daughter's meeting. The content present in it is ready. Now if we get two returns from this function, then it means the stuffing of our daughter, she has been made from Mari Current Contender, full help. Current and Compare has been appointed multiple times, only then we have the rest of the topics also prepared, so if it is so, then I will edit it, now half of the people will keep going on completely and even once, if such a thing is found in the hour, then my entire spring is complete. If it does then it will return to the main function inside the loop and if it does not happen then I have to return to pause. Now outside the loop, we can see the function from this. In this, our child's spelling is and our Content is paying guest friend, now what have I done, we have put a loop on our children, we will increment from the present, we will increment like this dot length is equal to that why we are incrementing the statement only, see this, to support this we have this Current string C, we had it has become current and this girl C, we had to see it, now we put the loop, so first of all, we checked AB with these, it was set in 2 days, ours was here, now this is ours. When we do climb plus, ours will go here but already we have compared this middle with this one, so our one that comes from here should go till here, so we have I plus seat world does not length which was So did the accident so that a character which is there is not there so we do this and subscribe is from high to edit length loot is now what are the things now let me explain that our come now we have eyes we had here also high here But it was there and we got the length of Austin Chattu, your currency has become this Bala, it has become till the land, that is, till the AB, it has become pure too, registration spring from 9th May, here too, we added this Karan Singh with our contender, there was a contender with him. If we compare, if the canteen created by us is not equal to mere contender, then we will return it. If even one case is passed then we will return it to us, then our canteen will never be able to become a contender for creation and if even one If the for sister is not done within the time log then Indian will return true that now if the submit from here is untrue then this one will go to a spray bottle and if it is through then the entire answer will be returned through, so this was the code, now we will run it. Let's see if there is a compiler and see, yes sorry, there will be an instant paste receiver, then I will ignore, check that there is no cross and there is no meaning, run it, your answer is passing on the custom test, just submit. Yes, yesterday morning I have roasted Puran Se. I hope if you liked this video then thank you.
|
Repeated Substring Pattern
|
repeated-substring-pattern
|
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
**Example 1:**
**Input:** s = "abab "
**Output:** true
**Explanation:** It is the substring "ab " twice.
**Example 2:**
**Input:** s = "aba "
**Output:** false
**Example 3:**
**Input:** s = "abcabcabcabc "
**Output:** true
**Explanation:** It is the substring "abc " four times or the substring "abcabc " twice.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
| null |
String,String Matching
|
Easy
|
28,686
|
951 |
one two three hello guys welcome to another video today we're going to look at another little problem flip equivalent binary trees um I picked this one because it's recently asked by Google and it's a medium questioned not going to bang on my head too hard I think so let's get started for a binary tree T we can define a flip operation as follows choose any node and swap little left and right child sub trees okay a binary tree axis flip equivalent to a binary about this is typical Google thing right this very characteristic googily questioned a kind of invent or introduced a lot of new ideas or definitions for you to work line to in binary tree why if and only if we can make X equal to Y after some number of flip operations okay write a function that determines whether to bunratty are binary trees are flip equivalent and the trees are given point root nodes okay with one root a and here's an example here we see two and three got a flip and this 7/8 is all soft whipped what and this 7/8 is all soft whipped what and this 7/8 is all soft whipped what one so each trade well the note here are sometimes it contains some use of all information so each tree will add up those 100 notes it's good to know but sometimes like at most a hundred those 100 is not a very big number we can sometimes we can use like a count sort kind of thing no but let's see if that's kind of useful for this question each value in each tree will be a unique editor so that will be a very important thing and so the value in a root of subtree can actually work as a key or identifier you name it like whatever you call it I mean it's a unique identifier for the subtree so it should be easy right and I'm thinking about using recursion here to make things readable and read less so if bridge 1 and this return trip that should be the easiest case and well I should say probably we can have something more clever and dammit turn out not so clever right not so clever well I really want to cut it out but I'm talking I kind of it as usual Oh sometimes your brain wonder to another realm without you even notice it one but that should do the trick and if they are both non returning true and as only one of them even only give I mean one and only one of them is none other it is not return false okay now we are we gonna sing that both route 1 and Row 2 are not empty trees sir we can say v1 rolls to route 1 dot well and we two poles to right and oopsie what am i doing right ha whatever as a note wine is from tre wine and note 2 is from tree - so for now and note 2 is from tree - so for now and note 2 is from tree - so for now initialize them as the root notes and then do the recursion right wait a second if I'm doing recursion I don't need to do the loop Oh anyways I'm gonna undo all the changes okay here so if a v1 there's a mismatch return false right away and else that they are of the same value then we'll need to get the keys of the for sub trees right so it's going to be lift wine right one F two right two equals two roots one dot left root so doc what and copy/paste and change the number so and copy/paste and change the number so and copy/paste and change the number so now let's check the values right huh here's the catch how can we do it all together okay flip equivalent self 22 pass the self here anyways let's just do it anyways and probably not well okay let's give it a try then self taught flip equivalent left one of two and r1 r2 so this is like unflappable or it's gonna be a long line of code right so left one wait a second yes r2 and r1 left - exactly so this is a kind of a left - exactly so this is a kind of a left - exactly so this is a kind of a flip then I will say trick okay and I'll otherwise return false well it's kind of a weird that I forget if I should pass the self here or here but let's run the code and see what's happening okay we've got the result we want forwarded example test case and for a second test case I've probably want bit deeper level right so 8mm the way they do it as pre-order traversal so it's about our to just appended at the very end if I want some extra values I hope so for seven I add one nine in the mold I think they should do it right an extra value and also we want a mismatch something like this run the code yeah we got a pass on our own local tests Wow oh wow this is the first time I see leading a hundred percent probably no one's writing it in Python perhaps let me check well a couple of people here couple of submissions I'm on the top oh yeah what are the other guys doing over engineering they are over engineering okay nevermind so this is gonna be the end of the video let's go back to the question and give it a final look it's quite straightforward right so first of all on this is a pre-order the game part is this is a pre-order the game part is this is a pre-order the game part is kind of a pre-order but we don't have to kind of a pre-order but we don't have to kind of a pre-order but we don't have to think too much of it because we're not going to handle the input we're not going to parse the input has already parsed for us and on so a bit of a trick here just use recursion right don't over engineer don't think too much on the on this step so if inflict is a mismatch mismatched I mean sorry if at this level has not flipped and its equivalent it works or its flipped and it's equivalent and here I'm not actually going too deep because the value here well the runtime if we don't have the constraint here and let's say saying the unique integer this may not be the optimum solution I think because it's wasting a lot of run-run time to go wasting a lot of run-run time to go wasting a lot of run-run time to go deeper on until they find it's not the same shape right it's gonna depend on these criteria this constraint is saying they're of the same shape but the kinds of every mismatch or the an equivalency is discovered doing like most of them are discovered by this step by this constraint saying that the key doesn't match and there's a instant on returning on that without going any deeper on what I'm thinking if we don't have that unique integer let's put the follow-up unique integer let's put the follow-up unique integer let's put the follow-up question like we don't have this constraint saying we the values are unique then well it's better off to let's say store the value of the size even the size like store they try to store try to reuse the shape of the tree instead of doing it every time maybe it's so like flippin unflagged it could be just waiting a lot of trouble here but no guarantees it could cut everyone's run short on average but yeah that's it for this question I'm kind of surprised that I just beat a hundred out of a hundred percent mm-hmm hundred out of a hundred percent mm-hmm hundred out of a hundred percent mm-hmm in both memory and rent I cool I'm happy I'm a happy man bye
|
Flip Equivalent Binary Trees
|
partition-array-into-disjoint-intervals
|
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees.
A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations.
Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise.
**Example 1:**
**Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\]
**Output:** true
**Explanation:** We flipped at nodes with values 1, 3, and 5.
**Example 2:**
**Input:** root1 = \[\], root2 = \[\]
**Output:** true
**Example 3:**
**Input:** root1 = \[\], root2 = \[1\]
**Output:** false
**Constraints:**
* The number of nodes in each tree is in the range `[0, 100]`.
* Each tree will have **unique node values** in the range `[0, 99]`.
| null |
Array
|
Medium
|
2138
|
18 |
welcome to about the training record solution if you want the best marketing interview experience in north america feel free to check us out at and if you want to receive the latest tech interview news feel free to subscribe to our wechat here and if you have any questions feel free to send us email at about training at email at about training at email at about training at so today we're going to talk about another sum related question so now is foursome essentially giving your array of integers find the four integers that sum to the target number and then in the uh qual triplets so it should be a non-descending order so it should be a non-descending order so it should be a non-descending order and there and uh you want all the solutions so that means there could be duplicates in the array in the final solution um so at this point i think we should be very clear like for the k sum problem we could solve it by using sort and then two pointers we could reduce one dimensional so that means um k sum problem we could solve it into o and k minus one type of complexity and uh that's just should be our something keep in mind and without further ado uh so this four sum problem just like how we solve three sum so we'll have a fixed first number second number and then for the rest of two numbers we'll apply two sum to it or you could think about the another way is recursively like the first four sum you could fix one and then apply three sum and for three sum you'll fix one apply two sum and two sum without work kind of a recursion basic line return line okay so here we go you so this is if we fix two numbers and now we have two left we can use two sum and new target so the code structure actually looks very similar to the previous question you can tune into the previous video and take a look so first we want the smallest number is i and after this because there could be still numbers in between right so what we want to do is we'll have a we need to have a for loop for this and size and we want to skip the duplicate values so after this sum is less than this target means we need to increase the number so here there might be duplicates but since it's not in the solution set so we don't really care we just do another calculation should be fine so now after this we exit the inner loop so i might be duplicated right so what we can do here is now ij we want to increase j and this is outer for loop so before we enter here i could also be duplicate and finally more return results okay so if we so this will be your own one two three like one cube complexity and uh if you run one example we run one example fix two numbers we're getting two so we think it should look correct target is zero so first when we sort so target is zero so first when we sort this right so the target is zero we first of this two and then we're trying to find if there's three so two less than that we want more two one two three so this will be one solution right this one yeah and then we can it's the same thing i think this looks correct the algorithm even if you have a duplicate in the array order to skip the duplicate one all right thanks for watching this is all in cube just remember k sum k minus 1 complexity oh one thing i want to mention is there seems to be another kind of train of thinking is um to kind of keep a hashmap key is the pair sum and the value is like two pairs right so you can go into this array for every two pair so you can have a sum so this will be on square essentially will have a hash map of a value and then all the key pairs you can try to dedupe them however and then you look through this array again so for each of the key pair you can just directly look at this hash map to see if there's another thing another value is there you can just directly get it out and then you can define your quad called triplets so that they can you know you can implement the equals and then hash code method so that you know you can detail those however there could be one problem it's very hard to dedupe is um where when you are currently at this value right and then for example you're kind of at the zero and then you already there's already a zero equals to zero but this zero is your original zero so then you will end up having three zeros in there while you only have two zeros so i guess by that what i really means is if you have a like a zero solution so now your map having a zero key is zero and then value is zero so now when you write your first zero you will think oh let me find a pair equal to zero so now you have zeros of zero which is wrong you don't have three zeros so it's very hard to do just to use this method will be fine thanks bye
|
4Sum
|
4sum
|
Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that:
* `0 <= a, b, c, d < n`
* `a`, `b`, `c`, and `d` are **distinct**.
* `nums[a] + nums[b] + nums[c] + nums[d] == target`
You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,0,-1,0,-2,2\], target = 0
**Output:** \[\[-2,-1,1,2\],\[-2,0,0,2\],\[-1,0,0,1\]\]
**Example 2:**
**Input:** nums = \[2,2,2,2,2\], target = 8
**Output:** \[\[2,2,2,2\]\]
**Constraints:**
* `1 <= nums.length <= 200`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
| null |
Array,Two Pointers,Sorting
|
Medium
|
1,15,454,2122
|
342 |
hey this is Topher with a lonely Dash and today we're going over lead code question 342 power of four which states 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 = 4 to exists an integer X such that n = 4 to exists an integer X such that n = 4 to the x X power and these are the important ones integer X and integer 4 in order to solve this problem so they gave us three examples uh for example we if they give us n equals 16 we know 16 is a power of four because 4 to the 2 power is in fact and I'm going to double check this just for my own brain uh okay four to the 2 power is in fact 16 five cannot be because there is no power of four that will get us to five and there is no power oh there is a power of four that will get us to one four to the zeroeth power will give us one right and the trick is that power zero is an integer two is an integer there's no integer so that power has to be an integer that will get us five so that's what we're really working with here is trying to figure out what that x value is X such that 4 to the x equals n so how are we going to do that and for me it comes down to mathematics so let's use a very simple example okay so four uh let's say 4 the 3 power uh is equal to 64 right and this I want you to rethink this as thinking 4 to the x is equal to n right because they're going to be giving us n and in this case is 16 and in this case is 64 so 4 to the 3 is equal to 64 and we're going to think logarithmically right logarithmically so we can rewrite write this right here this can all be Rewritten as the log of Base what is it log of Base 4 of 64 is equal to three and we're going to be thinking over here okay well that's really log uh base 4 of n is equal to X cuz we're really looking for that X okay uh and that can even be Rewritten a little bit more down to log base 10 because we're going to be programming and I like to have everything in log base 10 so in our case log base 64 over log sorry log base 10 64 divided by log base 10 4 is equal to 3 and again this is just going to be log coming over here log of 64 is our n divid log of 4 is equal to X okay and really this is as far as we need to go because we're going to be taking this equation CU we don't really need to know what x is we don't care what x is the only thing we care about is whether X is an integer or not because we're returning true or false based on the fact that it exists as an integer right so in our case when we're kind of writing out what we need to do we're going to say hey okay is log of n divided by our log of 4 is this an integer and the way we're going to do that at least for our purposes today is we're going to take this and we're going to modul it by one and we're going to say hey if this ends up equaling zero then we know that our X will be an integer now there are other languages you say hey is if log of n ID 4 is an integer if it is an integer then return true otherwise return false but for me this basic mathematics of using um using a modulo of one is the perfect solution because it'll work in every language no matter what you're typing in and so this is really all of the math that we're going to be using to solve this we're going to say hey uh is our log of n over the log of four uh an integer and you're golden but there's one other thing that we need to consider and I'm going to say that um in our edge cases so let's move on and see if there are any edge cases okay so for edge cases and it's not really an edge case I just want to make everybody aware when we're thinking mathematically that the N can never actually be negative right because four to any power is never going to give us a negative n right so we can at the very beginning since we know n looking at our constraints could possibly be anywhere from -2 to 31st up to 0 that we anywhere from -2 to 31st up to 0 that we anywhere from -2 to 31st up to 0 that we should take care of that first if we can just say hey is n less than zero great we're going to return false um while not an edge case it's just something to consider right off the bat so let's keep that in mind and move on to some pseudo code okay so keeping uh in mind what we just talked about for our edge cases and though it's not really an edge case we can deal with it first so if n is less than or equal to zero right then we know that it's going to have to be return false um because there's not really uh an x value uh an exponent value that will give us the integer that we need to find n otherwise this is really simple very short uh we're going to return uh WEA I have no idea if that's the right weather I'm really bad at choosing weathers whether the log of n right divided by the log of four is an integer and that's it that's all of the pseudo code work we really need for this question so let's copy let's paste it and let's get going here we are in the JavaScript work area of the lead code website and the first thing we need to say hey is if n is less than or equal to zero then we are going to return false because there is no exponent of four that can give us um a negative n so to speak so that's first and foremost what we got to get out of the way next we to return whether the log of n / the log of four is an the log of n / the log of four is an the log of n / the log of four is an integer and that's return is going to give us a true or false result and for us we're going to use our math on log base 10 so return whether math. logbase 10 of n which we were provided right divided by math. log base 10 of 4 um we're going to take that we need to determine whether this is an integer lots of different ways of doing it but if we just take it and we modulo it by one and we're looking for the answer to be zero if this number that we get modul by one comes out with zero then this will return true meaning that the it was in fact an integer if it does not come out to be zero then it is not an integer and therefore this will come out to be false so that's it that should be all of the code I'm going to hit submit and see how we did oh my goodness okay so uh didn't come out as great as I was hoping for runtime but 80% in memory hoping for runtime but 80% in memory hoping for runtime but 80% in memory is pretty darn good I'm just going to hit submit again and see how we do um without the commenting in there okay it's getting a little bit better you just never know with this website but for me when we're dealing with any kind of exponential mathematics I always want to sit there and think hey can logs help me out and in this case logs really help me out um it's you know you could easily make this a oneline code if you want but I think it's very simple and straightforward The Only Exception is the question power of two which if you watch uh our video on the power of two we actually use binary search in order to solve that and get much better results than I think pretty much anybody else um so uh for the case today if I'm going to be solving a lead code question 342 power of 4 I would use the simple and straightforward math good luck out there
|
Power of Four
|
power-of-four
|
Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_.
An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`.
**Example 1:**
**Input:** n = 16
**Output:** true
**Example 2:**
**Input:** n = 5
**Output:** false
**Example 3:**
**Input:** n = 1
**Output:** true
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion?
| null |
Math,Bit Manipulation,Recursion
|
Easy
|
231,326
|
1,071 |
back with another video the stoner coder today we'll be doing leap code question 1071 greatest common divisors of strings make sure you guys hit that like button and always subscribe for more amazing content so let's do it for two strings s and t we say t device s if and only if s equals t plus dot plus t for example T is concatenated with itself one or more times so what this means let's see given two strings str1 and str2 return the larger string X such that x divided both into str1 and str2 example one str1 is equal to a b c string two is equal to ABC and now we know that since uh string two is the least length right this can only be the greatest common device right here of three characters so ABC as you can see it repeats itself right here A B C and A B C so that's why our output is ABC for example two string one is a b string sorry string one is a b and string two is a b thus the output will be a b since that's the largest uh unique advisor for example three str1 is equal to Elite and str2 is equal to code and since there's no common divisor between any of them uh we know that there is no output so for this what I want to do first is I want to get a length for both string 1 and string two and how we do this we just do Len one is equal to the Len of str1 and we do the same thing for volunteer Len of St R2 now here um I want to go into a for Loop that ranges uh basically it goes through um each character of each string so what I want to do is do four l in range now I want to get the minimum of length one or length two so we can do a min when one comma blend two and I will this is our starting point right I wanted to go to zero and I wanted it to decrement once per Loop so we can write that as hashtag start comma and come on to jump now I want to check if this advisor basically at that point so what I want to do is um make a new function called is divisor we'll initiate that a little later but let's call it is divisor l I wanted to return str1 cut at l so I gotta use regular brackets for this Dash there we go so what we can do here um throughout our other function up here so let's define it we're going to Define this function inside our main function so def is divisor just like usual I'm gonna pass in parameter l and we're gonna do the first we want to check if Len one modulus l or lend two modulus l um we want to return false if that's the case so we got our initial check statement so that what we want to do is create two variables so let's call it um let's say F1 is equal to Len one and this is a division operator but it floors it since it's two slashes let's call it F2 it's equal to one two oh now I want to return Str one uh inside cut off at L times the modifier which is F1 basically what this does is it checks where to cut off in the main string and we want to return whether or not this is true or false so let's say str1 and str1 we'll do the same thing again times the F2 model fire is equal to Str en now let's see if I got all my syntax right as tier one looks right this looks right um well yep that's right looks right to me but now we want to check our last condition right here so if nothing happens here I just want to return an empty string let's see that return empty spring return should work let's try to run it hmm oh I forgot the colon right here let me just make sure I didn't forget calling anywhere else looks rather try to run it now perfect as you can see it passed all three test cases so make sure you guys like And subscribe make sure y'all get Blaze before you do your lead code uh but check back in for tomorrow for the next video thank you guys so much for watching
|
Greatest Common Divisor of Strings
|
binary-prefix-divisible-by-5
|
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters.
|
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
|
Array
|
Easy
| null |
1,572 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem Matrix diagonal sum even though this is an easy one it can be a little tricky to code it up in a pretty like concise way so I'm really going to break down my thought process for you in this problem and by the end of the video I really want you to feel like you could have solved this problem by yourself so we're given a square Matrix and we want to return the sum of the diagonals so just to blow this up a little we can see here we have this diagonal I guess this is called the primary diagonal and we also have the secondary diagonal and at this point a naive thing to do would be to just jump into the code and try to think about what variables we're going to do how we're going to be iterating through like the grid are we just going to iterate over the entire grid maybe that would be N squared that's not a bad thought to have though and honestly if you can just jump into the code and solve this problem that's not a bad idea but if you can't I definitely recommend just looking at the picture and actually thinking about the problem don't just stare at it and do nothing the first step is a pretty easy one let's just try to see what would the total be for this example it's pretty simple let's just go value by value we would start here that's one plus the next value we're going down and to the right now we have five and then we continue down here to nine and then we're pretty much done we're out of bounds we can't really go any further so we noticed some observations immediately this diagonal is of length three and at this position we're starting at zero and then we're going to the next position which is one next position which is two and just keep going like that until we go out of bounds which we will know we went out of bounds because really we're only iterating n times where n is one of the dimensions of the square Matrix so pretty straightforward there this pretty much tells me that we can calculate this by creating a loop a for Loop or a while loop where we have maybe I as the index and to access like each value we just say Matrix at index I and the second index is also going to be index I so pretty simple there now let's go to the secondary diagonal I guess we could start over here or we could start over here which one do you think is better are there any trade-offs we could better are there any trade-offs we could better are there any trade-offs we could make well immediately I would personally rather start over here because yes these two positions do have a different column but they actually have the exact same row and the next value is also going to have the same Row the next value here is also going to have the same row so I'd rather start from over here so we're starting here all the way at the right and as we go to the next position we're kind of doing a similar thing where we started at row I and then we go to row I plus one but what about the column it's obviously we're doing the opposite here right column is two but for the next value over here now the column is being decremented so that's something we'll have to keep in mind and then we'll get to the last value 7 and let's assume we added them up as we were doing it so plus three plus five plus seven we got a total of 30 but when we look at the solution the actual output is 25 which just reminds us that we double counted this value over here this five we double counted it so that's just something we have to remember it's probably something you know when you first read the problem but sometimes it can slip your mind so once we do all of this we have to subtract this value or just not add it in the first place in my opinion it's easier to subtract it after the fact because this is obviously always going to be in the middle right when these two lines intersect it's going to be usually in the middle so how can we kind of calculate that is it possible for us to exactly calculate that middle value I just cleaned this up a little bit but obviously it's the halfway point right we take the halfway point of this demand mention which will give us this because if you take 2 and divide it by 2 you get 1 and we take the halfway point of this you take two divide it by two you get one and I think we wouldn't actually use the two value we would use the length of the Matrix the length of this is obviously three divided by two will also round down to one well assuming we are rounding down so obviously that's what we would want to do but this only seems to work in the odd case right if our Dimension is odd because our Dimension is currently of length three does this also work for even Dimensions like four let's test it out so I just drew a four by four Matrix over here now I'm going to draw a line going from the top right going down so obviously these are the four cells that's going to visit let's try the other diagonal now starting from here where here then here and then here did you notice something you probably did if you have eyes that these two lines don't enter intersect each other when the grid is of an even Dimension I don't know that because I'm smart I know that because I have decent problem solving skills because I spent a lot of time building up these habits so now we realize that we'll be iterating like this and if the grid is odd length we're going to find the middle value and subtract it from our total was 30 we're going to minus five then we get 25 and clearly that is the result that they were expecting and I'm gonna end up solving this problem with just a single Loop that's going to iterate n times and we didn't really need any extra memory so the time complexity is going to be Big O of n memory complexity is going to be constant so now let's code this up so we know we're calculating the sum so I'm going to create a variable for that result and then we're just going to start iterating through the array we know we're probably going to need the index so I'm going to say for I in range the length of this Matrix and then we want to Total stuff up so let's start with the primary diagonal how do we get that was the straightforward part it's always going to be at index I and then we just take that and add it to the result now what about the secondary diagonal well let's start with what we know it's always going to be in the same row as the primary diagonal so we're going to start at index I for the row what about the column we know initially it's going to be the length of Matrix minus one we know that's what it's initially going to be and next time it's going to be -1 be and next time it's going to be -1 be and next time it's going to be -1 again and minus 1 again do you know a way we can repeatedly do a minus one operation well with a loop that's what Loops are for can we use this Loop or do we have to create a second Loop to do this we can actually use this Loop because what we can say here is length of Matrix -1 can say here is length of Matrix -1 can say here is length of Matrix -1 minus I because I is already being incremented but we want to use it in a negative way so we subtract that value so this is going to be the index of the column of the secondary diagonal not the row okay and now finally we are ready to go ahead and return our result but we know that we might have to subtract from it now we could do that in like an if statement up over here and that's perfectly fine but the way I like to code I like to personally use a lot of ternary operators when like it's possible and it makes sense and I think in this case it does because we might want to subtract by zero or we might want to subtract by this value The Matrix value all the way in the middle so n divided by 2 and N divided by 2 here the reason I'm doing double slashes is because in Python by default it does decimal division so I want to do integer division here but in other languages I think most languages by default do integer division where we round down that's what we want to do here but we only want to subtract this value if n modded by 2 is positive is one if n is odd in other words otherwise we are going to subtract zero and that is all of the code now let's run it to make sure that it works well I just failed an easy problem did you catch my mistake I tried using n as the length of the Matrix before I actually created that variable so let's do that up here I'm going to say n is going to be equal to the length of the Matrix and since we already used uh the length of the Matrix down here I'm just going to replace that with n to make this a bit more concise and then rerun this and now it does work I personally wouldn't pay attention to this runtime I don't know how you can speed it up but if you found this helpful please like And subscribe if you're preparing for coding interviews check out neat code.io I just released a check out neat code.io I just released a check out neat code.io I just released a new review feature that I'm going to be actively working on so I would love your feedback on that and I'll see you soon
|
Matrix Diagonal Sum
|
subrectangle-queries
|
Given a square matrix `mat`, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
**Example 1:**
**Input:** mat = \[\[**1**,2,**3**\],
\[4,**5**,6\],
\[**7**,8,**9**\]\]
**Output:** 25
**Explanation:** Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat\[1\]\[1\] = 5 is counted only once.
**Example 2:**
**Input:** mat = \[\[**1**,1,1,**1**\],
\[1,**1**,**1**,1\],
\[1,**1**,**1**,1\],
\[**1**,1,1,**1**\]\]
**Output:** 8
**Example 3:**
**Input:** mat = \[\[**5**\]\]
**Output:** 5
**Constraints:**
* `n == mat.length == mat[i].length`
* `1 <= n <= 100`
* `1 <= mat[i][j] <= 100`
|
Use brute force to update a rectangle and, response to the queries in O(1).
|
Array,Design,Matrix
|
Medium
| null |
337 |
hey everybody this is larry this is me doing day five yeah day five of the league code daily challenge hit the like button to subscribe one join me on discord come have a chat um today's forum is how is wobbler3 uh we did the other um was it housewife two maybe uh we did another one a couple of days ago so let's see the divas are finding the only one way called okay um okay so i mean i think the way that i would think about this in general is that um yeah just recursively but try to look at my video or watch the video from a couple of days ago um we go over the logic there um and since we did it recursively i think that would have a really very um uh a very intuitive sense as to um the way that will solve this because you can think about the way that i think about it is that for a problem like this um first you know you have that you have a tree right but first think about it if you have an array right uh whistler webinar race and now we're thinking about reviving the linked list right because a linked list is kind of like a tree in a way um it's a degenerated form of a tree so definitely think about it that way and then once you kind of you know now you have to array or link this version which you know you can convert from an array to a linked list way easily and now think about that recursion and then think about how that applies to a tree um in this case um yeah we'll see how that goes and we'll just do it recursively let's see we might need to do a memorization and there are a couple ways to memorize but you know we'll get to that problem when we get there so we just kind of the way that i would think about it is just thinking about asking myself the question that i want to know for each node right um and here we go so then now we have uh go house of nodes say now this is our recursive function we're gonna call it with uh with the root maybe but we'll see if that's true um so okay so if node is none then we just return zero um right um let's see so then maybe here we now i'm just thinking full of well um if you do the away implementation you have this idea of being able to skip ahead and here in theory you can be able to skip ahead and that you do like i don't know that left or no doubt left that well or something like that but maybe something that we can think about in a more precise way it's just whether the previous was used right um and this is like parent used maybe because you're only going down from the root so yeah so then here now we go okay it now we with these recursive problems uh just try to be as maybe brute force as you can maybe that's the way that would uh go about um thinking about it um in that just enumerate all the cases as much as you can so that it encompasses every case that you can right so okay so the pound is not used and sometimes there's overlap but you know let that future use figure that out right let's just break it down giving them this um uh input cases or number cases but even if there are um animation cases or whatever like even if you break it down and there's some overlaps you know worry about it later anyway if the parent is not used that means that we can use this node right so that means and so that means that using this node it's going to give us um you know we could go to the what does that mean that means that after we use the node we go to node.left um parent is the node we go to node.left um parent is the node we go to node.left um parent is used because we used it or go that house know that right and also true um and that and of course we take the max of these two right because that's recursive um we take the max of these two either we go left or we go wait let me see uh oh okay actually sorry i didn't know you could i don't know if you're going one path or you can go and tie okay so actually i was wrong about this one because you can go to them independently um of course you just go both so recursively you do this right so actually i was thinking about like a one path situation but in this case you are able to go both so you would go both if you're allowed to so this is the current score plus using this house of course it's going to give you um know that value i know that route right so yeah so let's just say this is best um and this is if we want to use this house um okay maybe just score using house right um and then we do another one we go if we do not want to use this house then in this case we just go you know let's go in that using house um then we just skip this house down left our parent is not used plus go dot house of no doubt right false pound is not used and of course we don't add to know that value because we're not using the house and then here we can just return the answer of max of either school using house or score not using house that's pretty much it for the parent not used and now the other case obviously is that if the pound is used then what do we do well there's no score using house because the parent is used if the payment is used you cannot use this house we don't even do this uh in this case then we do get that we cannot use this house and we don't use this house then we just have this thing right so we can just actually you know click up your face and then just return this here i think this would be good enough um and then now we start off with the root of go house um let's just say so there are two cases right from the root the beginning case so you could go from the root where we no actually i think that's okay so first because this root doesn't contain a parent so we can do frost and that should be good enough um there may be some so yeah there's some memorization here is that true yeah there's some memorization that we can use here um but let's just kind of run it to see if we get anything reasonable if this is wrong obviously we'll just you know we need to fix it before we even think about memorization so yeah so this looks good but of course we're doing duplicate things i'm too lazy to really print that maybe i can get still a big note because there are a lot of notes here um i don't know if i'm gonna just make this a faux tree so that it's easier to kind of do what i'm doing which is spam this uh input out see if this gives me a time limit exceed i actually don't know if this gives me a time limit exceeded ideally we'll have a um okay ideally we have uh much of a chord um we have a linked list but this is actually a tree so it's actually maybe more like we're actually creating log n of this but this is not the worst case because there could be the worst case is a linked list where um okay so this is too many nodes because so this is not the worst case way because if you don't cash probably the worst case is n squared and given that n is 10 to the fourth it may be yucky uh maybe even exponential but in any case uh so maybe i don't i cannot construct a i don't but i am going to bound the uh okay so maybe it is i mean you can see that this is 400 milliseconds so let's think about that in terms of okay can we improve of it yeah and we're going because this is probably going to be either n square or even exponential in a way um not gonna go over the complexity that much because we're gonna do add memorization so let's add a members memorization um there are a couple of ways you can do this i'm going to do this in a very naive way and hope that this is fast enough if not we'll play around different ways um to be honest this is not the way that i would do it during a contest but this is just illustration um so we just have a cache lookup is you go to a dictionary and then here we go if uh you know we put in a tuple if this is in cash then we just return the cash containing this tuple um and otherwise we cache it and then we turn it so here we do and here we also cache this right so we call that before i think it took 400 milliseconds for 70 milliseconds so let's see if this is much faster so this is 65 so we're already immediately faster um though there are some caveats about how to do this um but you know it's immediately faster so let's go over to complexity real quick now that we memorized um notice that node can be one of um any nodes which means that this can be up to 10 to the fourth so it's o of n where n is the number of nodes right and there's any nodes in the list uh of course parent used can be true false so that means this is 2 this means that the number of possible inputs is o of n times 2 which is all of n of course and of course each chord will take over one time so each input takes o of one times so this is going to be o of n total time and yeah and each input takes over one space because you know that's the number of entry in cash so over and total space uh that's all i have for this one but before that let me submit uh apparently i've done it twice before so hopefully i do a little bit better okay so i did you know i do reasonable um reasonably let's look at i'm curious what i did last time um but i should have a video for it i suppose um yeah so i actually it seems like i did mostly oh huh that time i did break it up into two cases um that's fine so this is actually another way of doing it um it's kind of similar to how we do the stock thing um where you know um so yeah so we did it in two different ways let me make this little uh let me know what you think about these two techniques um watch so if you do have questions about this solution which i'm not gonna go over that deeply please watch that solution because actually i like that solution as well i like this solution rather so i probably like that video and how i explained it so go check that out um but that's all i have for tonight um day five done uh one that's like 20 or something 16 something like that uh that's all i have stay good stay healthy to good mental health have a great rest of the weekend um i'll see you later bye
|
House Robber III
|
house-robber-iii
|
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`.
Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**.
Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_.
**Example 1:**
**Input:** root = \[3,2,3,null,3,null,1\]
**Output:** 7
**Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
**Example 2:**
**Input:** root = \[3,4,5,1,3,null,1\]
**Output:** 9
**Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 104`
| null |
Dynamic Programming,Tree,Depth-First Search,Binary Tree
|
Medium
|
198,213
|
142 |
hi and welcome to prototype we'll be solving the problem for lead code 142 lengthless cycle 2. this is another problem delete code 75 study plan let's get to it so given the head of a linked list return the node where the cycle begins if there is no cycle return null there is a cycle in a linked list if there is some node in the list that can be reached Again by continuously following the next pointer internally the position argument is used to denote the index of the node that Tails next pointer is connected to it is zero indexed at the position or argument is zero indexed it is -1 if there is no zero indexed it is -1 if there is no zero indexed it is -1 if there is no cycle note that position is not passed as a parameter and there is another restriction do not modify the linked list okay if you watch my Elite code 141 linkless cycle one video then you'll know that there's at least three ways to solve this the first would be to modify the linked list and have a visited property so we can Traverse the whole link list if we reach the end the pointer the current node reference will become null and in that case we know that there's no cycle otherwise we will eventually reach the a node that has been modified to have the property visited and it will show once we reach that node then we could just return that node we can't use that trick in this question because there's a restriction that says do not modify the linked list another way is to again Traverse the whole node add each reference to a set or some other memo some other storage device and if we see that the reference has already been added then we can again break out of the loop and then just return the node let's do that one first so we can say const memo is equal to a new set we will need a pointer to our reference to our current node that we're at we initialize It To The Head and then we'll have a trusty while loop and the well condition will be that Cur is not null and also one more because there are Cycles in this linked list or potentially anyway that the memo that we have not already seen the note so memo has uh occur in this case does not have occur and each iteration of the loop will be traversing down the linked list I would do that we assign current.next occur do that we assign current.next occur do that we assign current.next occur what are we doing at each node we're adding it to the memo and um we can just return Cur let's run it okay it passes we can submit all right accepted uh apparently it beats 97 percent even as uh probably slightly slower implementation so this is a linear time complexity because we will Traverse every single node and then Traverse one more node to get back to the start of the cycle and we'll also be using linear space since we'll be adding a reference to the memo is there a better way of course there is how do we do that we can use the fast two pointer so the fast pointer and the slow pointer method or referred to as Floyd's algorithm and if you again Watch the video for a 141 linkless cycle one then you'll see the explanation for this but what we'll be doing we have a while loop the while loop depends on the fast because fast is the one that will become null first because it traverses faster than the slow pointer right and then we will be incrementing fast by traversing down two nodes per iteration and then slow traverses only one node per iteration if slow is ever equal to fast then we can break out of the loop we know that there is a cycle so if fast is a falsy value so if fast is null then we know that there is no cycle we can return null okay and uh let's just go through this with example one so we start with slow and fast at three slow becomes two fast becomes zero now slow becomes zero in the second iteration and fast becomes two uh we do one more because slow is at zero and fast at two they're not equal yet slow becomes minus four and then fast becomes minus four the overlap they're the same reference and so we break out of the loop but notice that we're not at the start of the cycle we're somewhere after the start of this cycle at least in this example here how do we travel or how do we find the start of the cycle well it turns out that there's a mathematical identity and that is that the distance between the start of the linked list and the start of the cycle is equal to the distance between the start of the cycle and the meeting point what does that mean well what it does mean is that we can just Traverse with another pointer and we'll initialize it to head and so while slow and slow too are not null if slow is equal to Slow 2 then we can return either slower Slow 2 doesn't matter and both slow and slow 2 will Traverse only one node at a time so what's going on here again in this example we're slow and fast ends at -4 example we're slow and fast ends at -4 example we're slow and fast ends at -4 Slow 2 starts at the head which is three they both Traverse only one node minus four goes to two three goes to two um and we've reached uh a point where the references will both refer to the same node we and we can simply return that node again this is the result of a mathematical identity so if you'd like to look into that certainly it's up there on in Google otherwise you can just kind of remember that this is the algorithm to use okay now we're missing one other thing and that is in the instance where we have a linked list with only one node this can fail so we can just add a condition at the top we can say if head dot next it doesn't exist from just return null we can also do this another way uh this for instance but this is more self-explanatory I think okay let's run self-explanatory I think okay let's run self-explanatory I think okay let's run it looks like there's one typo here okay we'll wait for it to fail run it one more time there we go submit there we go come on bro there we go and uh turns out this time we're only 34.96 percent but that's uh we're only 34.96 percent but that's uh we're only 34.96 percent but that's uh that's lead code for you okay so that was two different ways to solve this problem the second way we'll use constant space since we've only used three references and in fact we could just stick with two uh we're done with the fast pointer once we break out of this Loop so we could just initi re-initialize fast to the head but I re-initialize fast to the head but I re-initialize fast to the head but I think it makes more sense to explicitly have a third variable okay so this is the solution to linked list cycle two Elite code question 142 subscribe to see more we will be doing the rest of the leak code 75 study plan questions in short order thank you and see you next time
|
Linked List Cycle II
|
linked-list-cycle-ii
|
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**.
**Do not modify** the linked list.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** tail connects to node index 1
**Explanation:** There is a cycle in the linked list, where tail connects to the second node.
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** tail connects to node index 0
**Explanation:** There is a cycle in the linked list, where tail connects to the first node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** no cycle
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Medium
|
141,287
|
1,903 |
Hello Friends Hindi Section Be Appointed Discuss Another Simple List Co Problem Largest And Number In Friend Give Strength Which Is Representing Anti A The Interior Can Be Small Or Large Different Sunday Infatuated With Interesting Format The Amazing From All Video Egg Final Responsible Member Of The And Share Subscribe and Subscribe Example in Its Only Possible Largest Number of Years Will Take Medicine This is Not Have a Single String in This is Example Look at These Important Documents of Lord Lytton It Back Subscribe Must Subscribe Very Simple WhatsApp Thinking Will Start Thinking in All Directions And Always Decide Page Number 90 Number Distinct Last Digit Pawai Internet But Not All You Can Visit From Right To Left Last Farewell Is And Digit Latest 2017 Digit Ignore It's N X Digit Forces Ignore 10 Not Visit R Movement For Age It Subscribe Index Position This Is The largest please give an example of how can they give correct or not to request will help you will see values for its value is valued 5th values for its value is valued 5th values for its value is valued 5th piece party ad ft um 850 and strong notice hair's value 512 MB its value for money subscribe this Video plz subscribe Video family values for oo jhal hai subscribe Video family values for oo jhal hai subscribe Video family values for oo jhal hai ki the character phanda current index hai let 's check sharp and digit a all 's check sharp and digit a all 's check sharp and digit a all district and detective this and number one digit person simply amazed to withdraw cases number ki a divine end and digit ten little current index And Returned Back Eden Garden Extraction Complete The Missions Obscene Not Exist In The Return Of The Day Interruption With Coding Letter Code Have Already Written Friend To Ability Year Making A Call To The Largest And Member Function By Passing Multiple Input Ca Final Year Printing Result On The answer is that they can see the results which AIDS Expector Hospitalized Video Thanks for watching please do the video and subscribe the Channel Thank you
|
Largest Odd Number in String
|
design-most-recently-used-queue
|
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** num = "52 "
**Output:** "5 "
**Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number.
**Example 2:**
**Input:** num = "4206 "
**Output:** " "
**Explanation:** There are no odd numbers in "4206 ".
**Example 3:**
**Input:** num = "35427 "
**Output:** "35427 "
**Explanation:** "35427 " is already an odd number.
**Constraints:**
* `1 <= num.length <= 105`
* `num` only consists of digits and does not contain any leading zeros.
|
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end.
|
Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set
|
Medium
|
146
|
918 |
Hello friends today I'm going to solve liquid problem number 918 maximum some circular sub array so in this problem we are given a circular integer area Norms of length and we need to return a maximum possible sum of Norm empty sub array of knobs and what's a circular array basically a circular array means uh you start from the zeroth index you move on until the last index and then the next element after the last index is the zero index so basically it means that um if nums I plus 1 modulus and is equals to zero then that is the first element so basically the next element of norms I is this value and a sub array must con okay now that we know we understand our question let's see how we could solve this problem so we are given this array let me just write it down here and we need to find the maximum song so what's your intuition while you try to solve this problem well what do you do is uh we start from the first and then we see that in the first case our maximum so far is like minus infinity because we do not have any values or we could just assign the maximum sum as the first element so the maximum will be equals to the first element so this is our maximum now what we need to do is we look at the next element which is minus 2 here and then the sum would be 1 minus 2 right and what's the value it's minus 1 and is the max less than minus 1 no Max is still greater so we won't change it now we have a contiguous sum of -1 we have a contiguous sum of -1 we have a contiguous sum of -1 that is the current sum so far and then what we do next is we take a sum with the next element which is three now once we take the sum with the uh with three what do we get a value 2 right and we know that 2 is less than three so two is less than 3 which means that if we take a contiguous sum up to index to the value is equals to 2 however if we only take this sum so this could also be our contiguous sum with uh one element right so that would be equals to three which of the these two is maximum of course 3 is maximum we need to maximize our solution right that's why we take the maximum value here and then we compare our max value which was equals to 1 with our maximum current sum which is equals to 3 and since 3 is maximum we update our max value 2 p equals to 3. similarly we move on to the next element and then we take our current uh we evaluate our current sum and our current sum e is equals to 3 right so we take 3 minus 2 which is equals to one and one is greater than minus 2 right so 1 becomes our current sum and then 1 is still less than Max our Max is still the max value so we take this as our max value now here we only had to like we only have done uh one iteration and we are not considering these as a circular metric circular one so you have not taken this as solar cooler now let's see another example here so we are given minus five three and a five okay five minus five and five um actually five minus three and five so now in this problem how can we solve this solution how could we solve this problem so we start from the first this is our maximum our Max is equals to five our current sum is also equals to five Now we move to the next element what's the current sum is 5 plus minus 3 which is equals to 2 greater than our previous current sum which was equals to five okay no not with our previous current sum but with the next element that is equals to 3 which one is greater of course 2 is greater right and we compare five with two since five is all already created we do not maximize we do not change anything next we can find our maximum here our current sum and since our current sum was equal to 2 we add plus 5 to it and this gives us 7 and since 7 is greater than 5 so this is our current sum and now uh Max 5 is less than seven right so we update our value 7 here to 7. now um is that our Max sum if we consider this as a circular array will of course not because in circular array if this was our circular area then our maximum would have been equals to 5 plus 5 because in circular area we can write this area as um like we have something like this right five three and five so we start from five we move to 3 we start from 3 to minus three to five and five to five so our Max sum if starting from this index would be equals to 5 plus 5 which is equals to obtained right so what are we actually doing here we are eliminating this value the middle value which is the negative value which is uh the minimum value which leads to the minimum value to uh from our array so far what we did is we were only finding the maxim now we'll also find the math mean so some minimum some uh using the similar method so what we did was um to find the maximum we calculated the current Max and then we updated our Max sum rights in similar way we will calculate our mean current mean and then update our mean sum so I have a few examples here already solved so let's look at these examples first so in this example we have put positive and negative values right and the formula to evaluate current Max is let me just write this down here so we would evaluate these by math simum of current Max so far and 0 plus the value of num at index I and the max sum would be the maximum of current Max or the maximum itself similarly our mean for mean sum and current mean we are just going to take the mean values of each of these and compare it with mean current mean and means sum so this is our current mean and this is I will mean some right and then finally we will also calculate our sum which will be equals to um this is just our sum of the whole area elements now once we have evaluated these using this whole thing using this formula the final result here looks something like this so this is the step by step four iterations of this uh solution and the final result the final value of current Max is equals to 1 maximum is equals to 3 current mean is minus 2 mean sum means minus 2 and sum is equals to zero so the only things that we need here are to compare these three things so e is the sum equals to minus 2 of course not so since it is not equals to minus 2 so what's the case is that our sum Max sum will um the result would either be equals to the maximum of the sum minus the mean sum or and maximum so the max value would be what would we return is since it's not equal the sum is not equals to mean sum so it would be the max of max value of sum minus the mean sum I'm just writing the it in shortcut comma the maximum so this would be our result in this case we return the result which would be equals to 3. now what about this K is 5 minus 3 5 so as we saw we also did the evaluation previously our mean sum our sum is equals to 7 mean sum is equals to minus 3 and Max sum is also equals to 7. now since um mean sum is not equals to the sum so these two sums are not equal so we'll all again do this evaluation here maximum so what's the sum is equals to 7 minus mean sum which is equals to minus 3 and the maximum which is equals to seven and what is the greatest value here well it is equals to 10 right because this evaluates to 10 so 10 is greater than 7 so this becomes our final answer and if you look that's what we are doing we are actually the sum 7 is the sum of this all area so it's contagious sum from this sum we are actually removing these negative values it's the value that is uh actually decreasing the sum so once we remove this we what we get the maximum sum right so that is what we are doing with this formula here and if you look at this array it's all negative and since it's all negative the sum the total sum and the minimum sum of this area both of them are equal and since both of them are equal what we know is the maximum sum would be the element with would only be one single element and that would be the element with the greatest value right since minus 1 is the greatest value and we have that minus one value in our maximum sum so that is what we will return if these two values are equal now that I have explained to you how the algorithm let's try to code our algorithms what do we need is um current mean let's initialize to zero current Max initialize to zero sum initialize to zero and then uh mean okay mean some initialize it to the first element okay and then Max some will also initialize it to the first element of the array okay now we will iterate over each of the element in our nums array once we are iterating what do we evaluate so we calculate our mean sum so I'll just copy paste this whole thing because it will save our time so I'm copy pasting this whole thing here all right so we don't need this index I and then finally we return if sum is equals to mean sum then we return our Max sum right because this would mean that all the elements in our array is negative so we return the maximum else we would return the maximum value between sum minus means sum and the maximum now let's try to run our code create and submit it so the space complexity is constant and time complexity is linear time complexity here
|
Maximum Sum Circular Subarray
|
reachable-nodes-in-subdivided-graph
|
Given a **circular integer array** `nums` of length `n`, return _the maximum possible sum of a non-empty **subarray** of_ `nums`.
A **circular array** means the end of the array connects to the beginning of the array. Formally, the next element of `nums[i]` is `nums[(i + 1) % n]` and the previous element of `nums[i]` is `nums[(i - 1 + n) % n]`.
A **subarray** may only include each element of the fixed buffer `nums` at most once. Formally, for a subarray `nums[i], nums[i + 1], ..., nums[j]`, there does not exist `i <= k1`, `k2 <= j` with `k1 % n == k2 % n`.
**Example 1:**
**Input:** nums = \[1,-2,3,-2\]
**Output:** 3
**Explanation:** Subarray \[3\] has maximum sum 3.
**Example 2:**
**Input:** nums = \[5,-3,5\]
**Output:** 10
**Explanation:** Subarray \[5,5\] has maximum sum 5 + 5 = 10.
**Example 3:**
**Input:** nums = \[-3,-2,-3\]
**Output:** -2
**Explanation:** Subarray \[-2\] has maximum sum -2.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 3 * 104`
* `-3 * 104 <= nums[i] <= 3 * 104`
| null |
Graph,Heap (Priority Queue),Shortest Path
|
Hard
|
2213,2218
|
261 |
hey what's up guys this is shown here so today let's take a look at another classic graph problem here which is numbered 261 graph a valid tree so basically you're given like a number of nodes and a list of edges right so the address has like from not from two students is undirected so there's gonna be so this graph links no 0 and 1 0 and 2 0 1 4 and you need to return a true of force to check if all this if all these edges which this number of nodes can form a valid tree right so for example this one for example here there's a lack of 5 a 5 node right so 0 and 1 right 1 0 and 2 right 2 & 3 & 1 4 and 1 right 1 0 and 2 right 2 & 3 & 1 4 and 1 right 1 0 and 2 right 2 & 3 & 1 4 right and as you can see here so and this is a tree right but how about this one right see this one same thing or 0 1 right 0 1 2 & 3 & 1 is 3 right so and then 1/4 1 2 & 3 & 1 is 3 right so and then 1/4 1 2 & 3 & 1 is 3 right so and then 1/4 here so this is a this is not a tree because we detect as a cycle here right worst a circle right so a tree right so what does the tree means right so a tree you cannot have a circle right if you have a circle and then it's not a tree right and so basically two conditions to form a valid tree from all this original address for this all the nodes first ones you cannot have circles and the second one is you have to link all that out a note right let's say for example if you have like 0 1 and to write 0 1 & 2 and like 0 1 and to write 0 1 & 2 and like 0 1 and to write 0 1 & 2 and then there's like a the 3 & 4 right so then there's like a the 3 & 4 right so then there's like a the 3 & 4 right so this one is that is a tree this one is also a tree but it's not but there are two component there are two it's like it's a forest right so - so like it's a forest right so - so like it's a forest right so - so basically two conditions the first one you cannot have a half circle in the in this subtree second is second one is the other nodes have to be in the same tree so I'm thinking I'm gonna talk about sauce 3 are quite common solutions the first one is gonna be the DFS Traverse right second one is kind of the BFS reverse and third why's that the Union fine okay so mmm so for the first two the DFS and BFS for both of them we need to construct a graph a base on this like based on this I like address basically with those edges we're gonna create like a graph with the keys is the node and the value is the neighbors of that node alright so basically once we have that graph constructed we can just simply start traversing that any from any nodes right in that graph right and in the end let's say we can just start traversing and once we reach traverse we either use of DFS or BFS and in the end once we traverse audit unknowns by using that graph then which in the end will check if we have seen all the nodes right okay cool let's start to talk on you right let's do let's create a graph here first right and then default dict right and then it's gonna be a list so very like standard way of creating a graph right for Ash right in Hodges then which to basically say note 1 right ouch 0 no to edge 1 right so graph node 1 dot at hand and no 2 and since this is an undirected graph we're gonna create two entrance here right so I'd so at this moment we have the graph so oh so now all we need to do is just like to traverse right we find any of the we start from any of the graph here basically or we can just always start basically we just we can pick any number from this end right let's because it doesn't really matter as lines it's a valley the tree it doesn't really matter with which is our start a starting point right it will no matter what edible traverse you can go through all the nodes right let's do a DFS Traverse right so with DFS reverse they're like two ways right there is like the recursive way and there's like a iterative way right let's do a recursive 18 it's the most intuitive way of doing it right so let's create a DFS here DFS know right so it's very standard here so and basically that's do you know and then don't forget since it is like an undirected graph we also need to create like a global variables - - because we like a global variables - - because we like a global variables - - because we don't want to start in this infinite loop right so we have to record which node we had been we had visited before all right so and then in the end which is - a DFS right ef-s let's do a start is - a DFS right ef-s let's do a start is - a DFS right ef-s let's do a start zero right and which add zero right - zero right and which add zero right - zero right and which add zero right - zero - this visited and then we - what zero - this visited and then we - what zero - this visited and then we - what the f at 0 so here what we do which is simply to a for loop right for neighbors right neighbors in the graph right so we find out neighbors off of the current node and then we do an another TF and if right so places which have if the neighbor is not has not been visited right not in visited right then we do another tear at the FS right so before doing the DFS which at is like no to the visited right so in the end once we return which is which traffic if we have visited all the other nodes right return length visited equals to end right okay but if we simply check into this one here it's a so basically remember there's a like we have two conditions right so the first one is this one the first one is the if this tree if this sub at this tree if this like kind of DFS Traverse can visit all the nodes right in this case we checked if you have a Dadaab nodes but remember there's a second condition they cannot be have any it can be any psychosis or circles in this loop right so how do we check if the if this like this graph has a circle right we can simply you know it's two example let's assume that there's like zero one two and three right and forth what am I thinking here and it's three here so take a close look at this so if a tree if it's a valid tree then the edge number has to be equal to the has to equal to the number of the yeah basically like the number of node is 4 here so the edge is always like the number of nodes minus 1 right so let's say if there's a like if there's another edge here right and then we know any if there's a tree that has like the arch the iris object of this graph is more than it's more than the nodes minor minus 1 then we know there has to be a graph a sight a circle in this tree so we can just simply before doing any anything we can just simply do a check here right if and if length right if lengths like of edges right does not equal to n minus 1 right if they're not saying we can simply return with written false so this will like basically this will cover 2 cases right and if this visit has everything but this one is but there's a still a circle and then we know it will fail here right and if there's like two components right say it's 0 1 & 2 right and there's a 3 & say it's 0 1 & 2 right and there's a 3 & say it's 0 1 & 2 right and there's a 3 & a 4 right so in this case right in this case there's no circle but they're not 1 there's not there's it's as a forest it's not a tree right in this case the edges satisfy this condition here so it will go through this like for the DFS here right and let's assuming we start from zero right it's star from zero and then once we finish the sorry once we finish this like DFS loop of zero the visited will only have 0 1 2 right because it will not see it be able to traverse to the other subtree so basically this will be false yeah basically that's how we do the check and it should work - cool so this one works and I'm work - cool so this one works and I'm work - cool so this one works and I'm going to talk about the iterative way of the D at the FS since the recursion is more intuitive but it's kind of sometimes it's kind of like in fear inferior then the Eternity iterative because then the iterative way because DFS will have like this space storage overhead right because every time it was need to store cash or store this like a functions into the memory so sometimes you also you it's pretty it's better to use a dirty way of doing the DFS all right same right I'm gonna so the same thing so instead of doing here doing a DFS here right so we also need to visit it right and then for the DFS it's a stack basically right so we're gonna use a stack it's a Pia put 0 in there right basically while stack right well stack and then every time we pop right we pop the popcorn on the right stack that pop right and then same logic for this DFS right for the current node we do a neighbor right in graph dot note right and if neighbor same check basically that you can just paste with copy and paste that the above code not in visited right and then we just say we just first add this visited right to this neighbor right with this neighbor and then we'd simply like a panda write a pandas neighbor to the stack I start dot append and a pan neighbor right yeah because we are doing this like a stack here so right so we append this one we penned a neighbor this zero here and then the neighbor one and then the neighbor to right but once we finished looping the neighbors will pop this thing out first right basically we'll start from here and then what I did this one's neighbor here that's how we do it because we always pop from the top that's what makes this for loop a while for loop like a DFS because we're not if he's I mean if we're popping from the left and then this is gonna be a breadth-first search okay so then be a breadth-first search okay so then be a breadth-first search okay so then we can just simply remove that right we just remove this one here while stack yeah I think that's the only difference is yeah the other one that yet the recursive way we use a helper functions and this one which use a stack and that should do it yeah cool right and then like I said another way is to add a BFS so it's similar it's just at your own preference it you don't have to use any uh you can choose any of your favor your preferred way of doing it so like I said if we're doing a breadth-first search in this case it breadth-first search in this case it breadth-first search in this case it doesn't really matter right so what we need to use you use a queue here basically right so it's gonna be collections dot TQ right and then say I'm gonna add this 0 to the DQ method here so in here every time right we do a we do not we do a pop left Q pop left basically right that's how we do a breadth-first search we always start breadth-first search we always start breadth-first search we always start from the left right and then yeah and then here same right so it's gonna be the queue but we are instead of but same thing we all but we still up and on the right side but when we pop from the left right and then that's it okay cool yeah so that's the like basic like PFF tier a TFS and then there's this Union sign right okay so how does this Union find can help us find if this like if a graph sorry if this like address can form a tree or not right like I said and for a Union fine rights it's the same thing right so we have a find right well fine method and we have a Union right so this Union fine we still need this check here first right that's always going to be our check but and how this Union fine will help us detect a sir right basically we'll be using our union-find to detect us a circle that's the use of the Union find master here right so how we already telling a circle let's say there's a like zero right and one two three and okay let's give you the four here let's make it circle a little bit bigger and then there's a like a circle so here is a circle right so how does unifying - right so if you so how does unifying - right so if you so how does unifying - right so if you guys remember so the fine right the fine method for each of the X right and unions the x and y so fine we always will give you all the you give you the root nodes of this sub of the subtree right and the Union will basically Union this x and y based on the rank of the root of x and the root of Y right so while we're so basically we will be looping throughout edges for all edges will be like will be a trial Union those two nodes right so while we're Union those two members of it with the Union fine at the beginning we're gonna have a parents no we're gonna have a parent a race here right at the beginning each node each nodes are the parents are or parents or roots note its is itself right so basically we're gonna have like parents no su from 0 until two and minus one right at the beginning each node the parents node is the same as itself and while we're doing the Union right let's say how Union can help us detect a circle let's say we Union 0 and one first right we have 0 and we have one right and then 0 1 they before Union right so basically every time we do a union we find x and y we find out that the root one right root after acts right we do what this one and the roots all right it's gonna be there the root of the white yeah right so I returned into a union we do what we do this which will get this to root ideally before Union this root 1 root 2 this shouldn't be the same right because let's say because I at the beginning each one there is one the root is different but since while we're doing that the Union here rights so let's say we do a zero and one after we do a union the find of one will become 0 right and let's to keep doing it with Union 0 and 1 and then Union 1 and 2 right and then after doing this to find out of 2 will also be 0 right same thing goes let's keep going and let's Union 2 & 3 & 4 right so at this Union 2 & 3 & 4 right so at this Union 2 & 3 & 4 right so at this moment right once we are we have Union all the address and include until 4 here so other 0 1 2 3 4 after find rights final 0 1 2 3 4 will both become but they're all 0 right but then let's try to Union this edge right there gonna be one for right so I find one and find a 4 right so you will get two zeros here right so every time so basically as long as we see our two roots have the same sorry have the same values then we know there has to be a circle right yeah basically that's how we use Union fine to detect the circle okay so let's do a union fight here since we're doing this like if track here I'm gonna leave that at the top there right so we always use that we always need that to make sure that the address satisfy the minimum requirement of the alpha tree right so we so with this check we can save a lot of logic that down the road here okay let's do a fine right so let's define fine and you need I'm not going to use those like very concise way of coding is I'm gonna just write the very classic like union-find template that classic like union-find template that classic like union-find template that can help you guys understand so I'm gonna use this like version of path compression right I think I briefly explained that what is the path of compression in the other videos I'll try to explain later so basically if there's a so first we have to have a parents right here at the beginning each of the parents it's the note itself right and then there's gonna be a ranks right at the beginning each rank all the ranks is zero so if parents right if the parents that acts is not two acts right so basically means we do a recursive call meanwhile we also do a pass compression right and find right and then in the end we just return term parents right so how okay I'll explain this one more time here so basically if the parents does not equal to ax right and then we know we need to keep going why because 0 1 & 2 right why because 4 why because 0 1 & 2 right why because 4 why because 0 1 & 2 right why because 4 0 remember that the lowest initialize the parents right the 0 of parents it is it itself right but one parent is 0 2 parents is 1 so while we're traversing to going up until we reach to 0 this part this the condition will always be false because it winds will I was word 0 here the parents of X is 0 and X is also 0 right because that's what that's when we stop so what is what's the path compression right so from if we find two let's say there's a three here I'd say if we find trying to find this three here or let's try to find two here and so every time right you need to go all the way up to the note then you can find it but then that's will be you're gonna be uh oh and time right - to do a fine here so but we time right - to do a fine here so but we time right - to do a fine here so but we can flat and we can flatten the tree because we know so every time right when we do it we mean first to define the first time so we'll while we're traversing back to the top we'll also be moving other nodes right the to the note itself class always parents notes under the root note right that's how we do the flatten like so after this one is gonna be in one and two and three right and then the neck or so in this case the next time we need to do another fine you don't need to traverse back you can just simply return this like root within a one time so basically the first find up any element of a d any node will be all will always be all in but the second time and then this but starting from second time the time will be open so this seems like this is like aa amortized time complexity so it's gonna be like oh one right cool and okay so let's keep let's finishing this one Union right the Union is gonna be ax and y right so like we said so to UNIX and why first we need to find the root of those two all right and then if our one it's not equals to R to right then we do a Union right let's finish the Union matter here so and if we using our ranks right so the ranks would just help us to do more to improve the time complexity even more right so because we don't want we always want to find out a smaller rank and then we only have those two roots right we have to decide we either merge R 2 to R 1 or R 1 to R to write about how so we're gonna use our ranking system here so we always rank the merge the root with a lower rank to the higher rank so in that case it can help us like reduce the fine overhead in the future okay so we're basically track ranks right if ranks r1 right it's greater than rungs are two right in this case our r2 has a lower rank so which merge sorry are to write to r1 we are with our one right as if ranks are one is smaller and ranks are two right in this case same thing we're going to merge r1 to r2 yeah and else I'll see if they are the same right if they're same doesn't really matter which you can just randomly pick any one to merge to another one in this case let's merge our r2 to r1 right so after this one I'm gonna increase the I think in this case is every time we find that the same ranks we just simply increase the rank by one yeah or there's some other ways right I in the for example if you can every time we went to the rank when you just let's assume there's a like a set right you can use that as the size of the set of this to stop root to determine which let me which run is lower and higher but in this case all we have the number right we have the number and yeah we don't have a array or list concept so basically that's how we are basically every time we see a different the same ranked I because at the beginning zero which is always deal or it's always to a rank Sprott plus this rank are one increased by one simply using this one to simulate this ranking systems right and remember right so since we're using the Union to detect a circle right like I said if it's not the same then we'll do it a normal like Union but ours right what does else means they're the same right then we know there's like a circle right so and so let's just use this Union here I'm simply just returning to enforce here - so basically return false means here - so basically return false means here - so basically return false means okay the Union fails right why it fails because we see a circle means we didn't do the Union because they are the same there's no way there's no need to Union them again right since they're already Union but if they're not which return true here all right so we would simply in the end we're just simply like a loop that the address right is to a Union right if not Union basically if not if right if not Union basically if not Union at zero right an h1 right if it's not Union basically if it's a false and that we know it there is a circle which is written force right basically because we're checking it with a valid the tree or not right so if there's a circle and then we know it's not about it we return false if everything works fine here right then we return true yeah uh oh sorry yeah I missed this : yeah uh oh sorry yeah I missed this : yeah uh oh sorry yeah I missed this : here oh yeah currents all right cool see okay it works all right and yeah so basically that's the other that's all I can think of about this problem here DFS PFS and the last one the union-find DFS PFS and the last one the union-find DFS PFS and the last one the union-find cool I hope you guys enjoyed this video thank you so much for watching the video alright I'll see you guys soon thank you bye
|
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,370 |
hello everyone so in this video let us talk about one more easy problem from lead code the problem name is increasing decreasing string so the problem statement goes like this that you're given a string S as you can see in the input now you have to reorder the string according to the given algorithm now what you'll do is that you will first pick the smallest character from s and append to the result is the final string that you have to form okay now you will first check like you will first choose the very smallest character smallest means that if like the characters are from like you can say like SK order so a b c d all of them are small only and you just have to choose out the very smallest character okay from the whole string and just put it up and in the very first position in the result then choose the second smallest third position so on and keep on doing this process until you have like uh and you will only choose one character okay you will first choose like let's say the smallest then you cannot choose that same character you have to choose the next smallest next position so on and you just have to keep an app and that after that you will choose the largest character and then the smallest so it is like you can just say that I'll tell you the example so that and you just have to form the final string okay I'll tell you how it is formed so as you can see like let's just take this as an example only into a drawing board let's go on to a drawing board what you can observe here is that this is the string that we have now we have to sort this according to the given algorithm you have to first choose the very smallest character from the string that is a then you have to choose the next smallest after this like you can just like larger than a okay let's say larger than a whatever character is there so larger than ASB which will be the larger than b was character see larger than signal so from C you have completed one iteration and then you have to go backward but backward I mean that you have to now choose the maximum of the string so this character I moved here okay you just have to assume that these characters are removed now from the rest of the characters you have to now choose the very maximum capital among the rest of the characters which is C then the smallest of that is B okay you cannot choose the same character again okay even a do it is present you cannot shoot it okay then it is B then again the smallest Dent is a then you have to keep on doing this process again from the rest of the characters to the very smallest that is a then the bigger of that is B because of that is C and again C then B then a and that's the final answer okay that's the only thing that you have to do you have to just keep on like uh forming a string so that you just have to take out how many characters are there from that choose others very smallest then the greater than that greater and the greater than that till you cannot take any greater and then from the greater the smallest again so it's like increasing decreasing type of problem now how can you do SUB step problem it's very simple what you can do is that you have to keep on doing a while loop over this until you have like exhaust all the characters and make a new string that is one of the things that you have to understand now how can you make this string you have to first understand that there should be an order like you have to somehow sort them by sorting I mean that you have to somehow no key like how many years are there how many B's are there because then only you can like if you they ask you to like what I mean by this is let's say they ask you to First append a then the character greater than that so you just have to form an array of frequency array okay so let's say for a how many times a is occurring how many time B is occurring how many times C is occurring how many time D occurring so one till how many times Z is okay this is a straight over this whole string and form the frequency as you can see that a is occurring four times basically four times C is occurring four times D is a king two times and so on now what you can do is that you have to first do a wire Loop until you have so let's say you have to make an array or let's say final string of size 12. so what you can do is that you have to do a while loop and in the first you have to do iteration or from left right and if the character is greater than one you just take that character and append in the final result so there is a okay just decrease the one because you have used one time then B 10 C and there is nothing because all of them magic then you just do a backward traversal over the string so then C B A and you will only append these characters if the character is present inside the array like if the frequency is not zero because if it is 0 which means that you have totally exhausted and put in the fan result okay and that is one you can use just one swap okay going forward going backwards and then you will keep on doing this until you have exhausted all the characters and you have found this thing that's nothing much complicated here as well so let us show the code part now first you have to make a frequency array of all the 26 characters that I've used study you can just shoot 36 to 26 letters it will do all the characters in that inside the string and form the frequency which means that how many times a is occurring B is happening c x again and so on that is uh stored in this frequency now you will do it you will do this while loop over this N means how many characters you have to like n is the length of the string so you have to do a while loop such that total number of characters that I have in the string should be appended in the result that I am forming result is the answer that I've used here okay so first you have to do I travel from left right and then for right left so left right is the Traverse system of 0 to 26 characters from 0 to 26 and if the frequency of that character exists which means that particular character is still not exhausted and result in the result I will take that particular character insert it in the answer that I'm building degrees at frequency from the frequency array as well as from n because now I've used one character so I should not be like this value for only stop when I have exhausted all the characters like uh from the answer uh from the string s to the answer okay that's why this is also required to reduce and then when I move from left right and I have to go from right to left as well that is from just back to uh back to front traversal the same code and this will keep on doing this front to back to front and keep on like taking out characters from this frequency array if it is present appending it in the answer vector and also decreasing this until it becomes uh like n becomes 0 which means that we have used all the characters and just we have a final answer that's it nothing much complicated here as well that's your logic and the good part for this problem if you have any doubts you can mentioned in this comment box of this particular video I will see you in the next video coding and bye
|
Increasing Decreasing String
|
count-number-of-nice-subarrays
|
You are given a string `s`. Reorder the string using the following algorithm:
1. Pick the **smallest** character from `s` and **append** it to the result.
2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3. Repeat step 2 until you cannot pick more characters.
4. Pick the **largest** character from `s` and **append** it to the result.
5. Pick the **largest** character from `s` which is smaller than the last appended character to the result and **append** it.
6. Repeat step 5 until you cannot pick more characters.
7. Repeat the steps from 1 to 6 until you pick all characters from `s`.
In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.
Return _the result string after sorting_ `s` _with this algorithm_.
**Example 1:**
**Input:** s = "aaaabbbbcccc "
**Output:** "abccbaabccba "
**Explanation:** After steps 1, 2 and 3 of the first iteration, result = "abc "
After steps 4, 5 and 6 of the first iteration, result = "abccba "
First iteration is done. Now s = "aabbcc " and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc "
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba "
**Example 2:**
**Input:** s = "rat "
**Output:** "art "
**Explanation:** The word "rat " becomes "art " after re-ordering it with the mentioned algorithm.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters.
|
After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ?
|
Array,Hash Table,Math,Sliding Window
|
Medium
| null |
162 |
welcome to july's leeco challenge today's problem is find peak element a peak element is an element that is strictly greater than its neighbors given an integer array nums find a peak element and return its index if the array contains multiple peaks return the index to any of the peaks you can imagine that the first and last element in our nums is equal to negative infinity so you must write an algorithm that runs in log of n time so essentially we can see that well first off all the numbers are going to be either ascending or descending you can see that here in this constraint and we want to find one of the peaks inside of our number so like the easiest way to do this would just be to do a linear scan right we just go through every single number and as soon as we find that uh it's descending we ascend and then there's a descending point we know we found at least one peak but we want to do this in log event time right we don't want to do linear so the way that you could figure this out uh just given this example say uh say that we did a binary search and we want to just find the middle and see if the next number is ascending or descending here let's get another number here uh negative one uh here we start with the middle right three and we want to check the next one to see is it ascending or descending here we can see that it's descending what that means then is if we find that at this point we're descending a peak must have existed on the left side right say that this was like four though or five uh then if we see that still ascending that must mean the peak still must be on the left side or right side now so there could be multiple peaks here but it doesn't matter which one we select we just want to find one of the peaks right so that's what we'll do we'll just do a binary search to see are we ascending or descending at this point and then check to see that side and continue on until we find one the maximum peaks here so it's a pretty classic problem what we'll do is first have a left and right pointer zero and length of nums minus one we'll say while l is less than r let's calculate the mid which is going to be l plus r divided by two and all we want to check to see is are we ascending or descending at this point so if mid or should say nums mid if this is let's say less than nums mid plus 1 that means we should be checking our uh the right side right so this would just be what l would now equal to mid and i believe we need to add a one here mid plus one otherwise we're going to move our r pointer to the mid here and then we just return the index point which would be the l so let's make sure this works okay it looks like it's working submit it and there we go so that's accepted uh time complexity is gonna be log of n and we use constant space so this is a pretty classic problem um it's basically a modification to our binary search algorithm and it's just it's actually one that i've just learned before from a lecture um i think it'd be pretty hard to come up with on the spot but given that we know that we want to solve it in long given time we must know that there's some sort of binary algorithm going on here right so i believe if you like play around with it you can eventually get it all right thanks for watching my channel remember do not trust me i know nothing
|
Find Peak Element
|
find-peak-element
|
A peak element is an element that is strictly greater than its neighbors.
Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**.
You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in `O(log n)` time.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 2
**Explanation:** 3 is a peak element and your function should return the index number 2.
**Example 2:**
**Input:** nums = \[1,2,1,3,5,6,4\]
**Output:** 5
**Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
**Constraints:**
* `1 <= nums.length <= 1000`
* `-231 <= nums[i] <= 231 - 1`
* `nums[i] != nums[i + 1]` for all valid `i`.
| null |
Array,Binary Search
|
Medium
|
882,2047,2273,2316
|
1,793 |
hello everyone and good morning to all of you this is our nth day of 75 days lead coding Challenge and here is the problem which name is a maximum score of a good sub lead code 179 93 problem so before going forward in this video please make sure that you have liked and subscribed to this channel this will motivate me a lot so if you have liked this then see this video properly and let's do this question by yourself and then see this video because that will be very helpful for all of you so let's see this and understand the problem properly then see the intution for this problem okay let's see this uh let's read the problem the statement so problem is saying that you are given an array of integers nums zero index it is starting from the zero index actually and then integer K the score of a sub I comma J is defined as minimum of nums I to nums J mtip Jus I + a good sub nums I to nums J mtip Jus I + a good sub nums I to nums J mtip Jus I + a good sub is a sub where I is l thanal k is L thanal it means we have to find the we have to return the maximum possible score of a good sub so let's see the problem let's see the example for this that so that we can understand better okay so before going into the problem into the example let's uh discuss about have you done the problem largest rectangular area of histogram if you have done that problem this is same like this problem also if you that if you copy that code and paste that here then also you can also uh do that problem so it is not very hard problem to see rectang left plus one that is same you are doing here actually if you do the that if you know that approach you can do this question by yourself also so I will not discuss that approach I will discuss another approach that will be good for you so let see the example here num is given is between I and J as you can see I is less than equals to K is less than equals to J K is the between I and J and the optimal sub is 1 to5 if you because we have to take the maximum score now that's why we have to uh choose a sub 1 to five if you if I choose 1 to five then it will be minimum of this 1 2 5 multiply 5 - 1 + 1 mean i- J + 1 if we multiply 5 - 1 + 1 mean i- J + 1 if we multiply 5 - 1 + 1 mean i- J + 1 if we multiply then we will got 15 is our answer so it's like a basic simple problem if you understand the problem it is a it is lying between easy to medium level let's see the intution part for this then we can understand better for this let's open Quick Time layer yes so we discuss about the largest rectangle area of histogram so the inion part of that problem is this B made of blocks 1 4 3 7 4 and five Heights if we take a if we consider the four is a minimum element then we can go in left side up to F because we can't go for three because we have no element for three also then we can go five up to five so we can get this area also if we consider the three is a minimal element then we can get this area so this is a rectangular histogram method so we will make left a left index and right index means B if IND s just I will discuss this approach this is a very optimal approach actually I saw I understand this problem from somewhere and this approach is much better than the histogram approach actually because in this approach we are not taking any space big one of space complexity for this so it is a much better approach that's why I understand this approach from somewhere okay if condition is if we will start from K because we have given the K we will start from K and we will go left and right side it seem like this approach histogram but it is quite bit uh simple if I to lo I or n if we get I it means of IUS iseral of j+ then iseral of j+ then iseral of j+ then I so let's D this approach I'll not D because if I D this then uh this video will very long for you D it by yourself and then you will understand it better and make this I have also made this like this you should have also made this I will see this and I will do the code so if you want to do then you have to make this and you have to dry run this then you can make the code let's uh do the code let's open again quick yes let's do the code yes firstly I will Define in n = to nums do size n = to nums do size n = to nums do size perfect yes then I will Define int minimum element mini equals to nums of K because we are starting from K then I will do all the operations from the K as K element in Maxi equals to then I will take two pointers I and J from k i = to from k i = to from k i = to K and is done now I have said you I have told you about this key I may Loop the condition are same I have written that condition in previous slides which you have seen so conditions are decrement J pointer so how will decrement J minus one El if condition if so increment this should be increment because so don't need to this decrement height pointer so how IUS L condition nums of IUS 1 is less than nums of increment J pointer how will increment J plus in otherwise condition satisfy is greater thanal increment I pointer this we are doing this score by using the pointers only that's why this approach is better okay minimum element of Min comma minimum of nums of I comma nums of K num of J sorry maximum of answer perfect many into j i +im this answer let's run this code comp wrong answer why is this wrong answer let's see this code again why it is giving wrong answer J ++ G of let's run this code again and sub yes comp any space we are only using the pointers so we are uh so our space complexity is we go of one here comp yes so that is the better approach I have ever seen for this question so if you find this helpful then please like share and subscribe because if you subscribe that motivates me a lot and if you know another approaches then please comment below and uh please like share and subscribe for this thanks we'll meet in next video so let's do the code by yourself okay by
|
Maximum Score of a Good Subarray
|
minimum-moves-to-make-array-complementary
|
You are given an array of integers `nums` **(0-indexed)** and an integer `k`.
The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`.
Return _the maximum possible **score** of a **good** subarray._
**Example 1:**
**Input:** nums = \[1,4,3,7,4,5\], k = 3
**Output:** 15
**Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15.
**Example 2:**
**Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0
**Output:** 20
**Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 2 * 104`
* `0 <= k < nums.length`
|
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
|
Array,Hash Table,Prefix Sum
|
Medium
| null |
328 |
the good part about a linked list is that it does not have any indices right so you can insert and remove elements at any place unlike an array correct but at the same time the bad part about a linked list is that it does not have any indices so what do you do in such problems where you have to do some operations based on indexes so there is one such problem available on lead code where you have to group all the odd indices and the even indices together so what can we do about it Hello friends welcome back to my Channel first I will explain you the problem statement and we will look at some sample test cases next we will see why the most straightforward approach is not feasible and you cannot solve it using a constant space going forward we will try to come up with an optimal solution and then we will also do a turn of the code so that you can understand and visualize how all of this actually works in action without further Ado let's get started first of all let's make sure that we are understanding the problem statement correctly in this problem you are given a single linked list and you have to group all the nodes with the odd indices and all the nodes with the even indices together and you have to make sure that the relative ordering of all of these nodes should remain the same let us see what do we mean by that so let us look at our first test case I have this sample linked list in front of me and what are the odd indices that is the first note the third node and the fifth note correct and these two are the even indices so for this particular test case for the output what will happen is all the odd indices will get grouped together and then you will attach all of the even indices right so for a test case number one this link is due to your answer correct notice that these values 1 2 and 3 these are not the indices but the values of the nodes in our test case number two once again we have a longer linked list and we have all of these elements right so 2 3 6 and 7. all of these are odd indices correct because they are at one three five and the seventh place and one five and four these are the even indices because they are at 2 4 and the sixth place so for our output what will happen is 2 3 6 and 7 will get grouped together and 1 5 and 4 they will get grouped together notice that the order in which they appear it Remains the Same in the actual output correct so if you got 1 5 and 4 the actual output will also have the same order 1 5 and 4. so for a test case number two this linked list will be your answer right the main catch of this problem is that you are expected to provide a solution where you are not taking any extra space so now if you feel that you have understood this problem statement even better feel free to first try it out on your own otherwise let us type into the solution and look at the most obvious way of solving it so let us say you have this link lift in front of you and the beginning of the linked list is defined by the head node right so the most obvious way to approach this problem could be that you can say that okay I will have one odd head that is gonna store all of my odd indices and I can have one even head this is store all of my even indices so now what you can do is you can get started from the first node this will be the first odd node right so what you can do is just assign this node to your odd head correct so here you will have two and then what you're going to do is you want to move to the next node you know that this is going to be an even node so this time what you're going to do is you will just assign this to your even node right and now what you will do is you will just keep on moving ahead one step at a time once again you will get a odd node so you are going to form your list like this so you can see how you can continue forming your lift once you have hydrated through the entire list both of your lift will start to look something like and then once you have reached the very last pointer that is null what you can do is you can simply take this entire even list and assign it to the next of your odd list correct and then at the very end you can simply return this new head as your answer correct now this is a very straightforward approach and it will work every time and it will indeed give you a correct answer but the only problem with this approach is that you are taking extra space to form both of these two new lists right you are making a new list for all your odd indices and you're making a new list for your even indices then you are attaching it so that is taking up some extra space and that is not desired so if you notice we never take any advantage of the fact that this is a linked list right you could have done all of the same operations if this would have been an array as well right so definitely we need to do something over here what can we do about it once again let us say I have this link lift in front of me and this head note defines the first mode of your link lift so this first note is the odd index correct and the second node will be the even Index right so definitely we can start something over here so what I will simply do is I'm gonna Mark these two nodes so I will call my first note as odd and I will call this second node as my even node correct so this is how our initial setup looks like correct but at the same time you also know that all of these odd nodes and all of these even nodes they will come at alternate spaces correct so if the first node is odd then the third node will be odd then the fifth then the seventh correct so in a way if I look at the pointers what is the next of odd will be even and what will be the next of or dot next that will be another odd node correct so what I'm doing I am doing all dot next and that is landing me at another odd node so if I can change this pointer somehow to point over here then maybe I can proceed in some direction correct so what I'm gonna do is I'm gonna do odd dot next equals to or dot next so basically I am saying that odd dot next that should be equal to odd dot next right so what I just did is I change this pointer odd dot next and I pointed it to or dot next so basically what I'm doing is I'm changing the original structure of the link list if someone tries to do a next on this node they will land at this node correct and that is the next odd node next what do we need to do is we need to move our odd pointer to the next location because that is where the processing will continue correct so what I'm going to do is I will just do odd equals to or dot next so where will this pointer go this pointer will go to or dot next and voila I'm at the next location that I have to process but wait over here we need to do something about our even pointer as well correct so once again what comes to my mind is okay what will be the next note of this even node that will be next dot next correct and that is node with the value 5. so once again I can do something similar I can say even dot next equals to even dot next so what is happening even dot next this should point to even dot next that means even dot next right because I still have this structure intact I have not broken it yet so what I'm doing over here is I am changing this structure I am doing even dot next equals to even dot next right so if someone tries to go to the next of this node they will land directly at 5 right that means I have grouped both of these nodes together and once again what you will do is you have to move your even pointer to the next location so you're just gonna do even dot next and my pointer reaches at the next note that I have to process but do you see a problem over here as soon as I did a even dot next I lost my reference to the first even node correct and you know that in a linked list if you lose the reference to the first note there is no way to go back so you just need to do a very simple thing as soon as you begin your execution you need to store the even head so what I'll just do is I will take this variable even head and I am going to assign it to my first even node right for now if you have to Traverse the even linked list you can just start from the even head and then do a next so once this Loop continues what will happen again once again I'm gonna do r dot next equals to or dot next so right now my odd is pointing at this node correct and I'm going to update this pointer I will say odd dot next equals to or dot next for now the next of three points at six correct and once again I will do odd equals to odd dot next so this pointer will now update and it will land at node width value fix similarly do the same operation for the even node I will say even dot next equals to even dot next so I am updating this value of even.next so I am updating this value of even.next so I am updating this value of even.next and I change it to even dot next correct and then I will do even equals to even dot next so that will update the even pointer to the next node so you see what is happening over here we are modifying the actual structure of a link lift so if someone starts at head what will happen they will start at node 2 then they will go at node 3 then they will go at node fix and then as this program continues I will update this pointer to point at node 7. correct and similarly if someone wants to Traverse the even node what they will do they will start at even head and then do a next and then they will reach 5 they do a next and then they reach four and then ultimately they are gonna reach null correct so you can see that I have separated both of these lists based on just their pointers now the only part left is that you have to attach both of these pointers so what you're gonna do is at the very end of your odd lift just assign the next to your even head correct so now if someone is traveling the list they will reach all the odd nodes and then they are gonna reach all the even nodes right and this is how you have grouped all the odd nodes and the even nodes with their relative ordering in place now let us quickly do a dry run of the code and see how it works in action on the left side of your screen you have the actual code to implement the solution and on the right I once again have a sample linked list that is passed in as an input parameter to the function or even left this complete code and request cases are also available in my GitHub profile you can find the link in the description below moving on with the dry run first of all we check for our edge condition that if head equals to null simply return correct now comes the entire logic what do we do first of all we will assign both of our odd and even pointers because you have to begin somewhere right so all pointer points at the head and even pointer will point at head dot next and the most important thing to do over here is maintain the even head because you saw that we can lose it right so as a next step we maintain the even head as our even pointer right so no matter what operations we do on the even pointer the even head will remain constant at the starting space correct next we will start a while loop that is going to Traverse through this entire list and do the required operations so what do we do over here first of all what we do is we change the pointer for our odd lift so what do we do or dot next that is equal to or dot next so this is gonna point at 3. correct and then I move my odd pointer to the next location and that is 3. similarly what you will do is you will go to the even pointer and then change its pointers so then one dot next that will point at one dot next and that is 5. right so this is how this operation will go on and this while loop will continue the next of 3 will point at 6 and the next of 6 will point at seven similarly for the even conditions the next of 5 will point at 4. so you can see how this odd and even will get populated correct and then when we come out of the loop we just have to do one last step and what is that we have to assign the odd dot next to our even head correct so what will happen is this even head this will get assigned at the very end of your odd list right and to return your answer you will just return the head node because this is where things actually started correct the time complexity of this solution will be order of n where n is the total length of the linked list and the space complexity of this solution is order of 1 because you do not take any extra space and you are just meddling with other pointers 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 problems on linked list and you are asked that okay you need to come up with a solution in a constant space then it is very essential that you have to take advantage of all these pointers because if you're trying to come up with a solution that does not take any advantage of this non-linear data advantage of this non-linear data advantage of this non-linear data structure then certainly you are going in a wrong direction so whenever it comes to linked list always try to tweak your Solutions and tweak your linked list to get to an efficient solution so while going through this video did you face any problems or while solving any such problems have you found any similar problems where you could just come up with an efficient Solution by tweaking the next pointers so tell me all of this in the comment section below and I would love to discuss all of them with you as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what problems do you want me to follow next until then see ya
|
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
|
110 |
this video we're going to look at a legal problem called balanced binary tree so given the binary tree determine if it is a height balance so for this problem the height balance binary tree is defined as a binary tree in which the left subtree and the right shape subtree of every node different in heights by no more than one so you can see we have an example like this right and we're returning true because in this case it's a balanced binary search tree so sorry binary tree um and in this case you can see the left subtree right in this case we're not just checking the root level if the left subtree height is actually balanced it's uh in this case the height of the left sub tree and the height of the right subtree um is no different than one but we also have to check for each and every single subtree right so you can see that for this substrate right here on the right subtree um the height on the left subtree is just one and the height on the right subtree is just one so in this case there is uh the left sub tree's height and the right substrate's height is no different than one so and therefore this subtree right here is balanced but this sub tree has a height of two right and this subtree has a height of one and in this case this left subtree is one the right subtree height is two so the difference between those two is no bigger than one so therefore this subtree right in this case this entire subtree is basically balanced right so therefore we turn true um and then if we have a situation like this where we have a unbalanced binary search of sorry binary tree in this case we check to see if this subtree is balanced this is has a height of one this has a height of one so this therefore this subtree is balanced so it has a height of two this sub tree has a height of one so this is subtract balance right this subtree right here is balanced because in this case their difference is no bigger than one right and so therefore this substrate has a height of three right uh in this case this sub tree has a height of one in this case this subtree is not balanced or in this case the entire tree is not balanced because three minus one the absolute value is actually bigger than one so therefore this sub tree is not balanced binary tree right so in this case uh we return false and of course if the root is null then we're returning true right so in this case how can we be able to solve this problem so to solve this problem what we have to do is we have to start at the base level right so what's the base case in this case the base cases at the very bottom so in this case if the root right if we only have like one node like this we know that this is balanced because the left subtree is null right basically zero has a height of zero the right sub trees has a height of zero and is no bigger than uh in this case the difference is no bigger than uh one so we know it's true right so same thing here basically what we can say is that if this is a leaf node then we know that this is a balanced binary tree right so we return back to the root say the height is one so that this recursion stack or in this case for this node we can be able to compare the children to see if this subtree is balanced right in this case the children on the right subtree zero or has a height of zero and this the height of the left subtree is one so we know we take the absolute value in this case the absolute value is in this case the difference between those two in absolute value is just one so it's no bigger than one so in this case this subtree is basically balanced so we're basically returning the height of this current subtree right in this case the height of this current sub-tree is basically the maximum sub-tree is basically the maximum sub-tree is basically the maximum between those two which is one plus the current node which is two right so in this case once we are here at this current node we basically see the uh the right subtree in this case the right subtree has a height of one right so we know the absolute value of those two right the difference between those two value in absolute value is just one so we know that up to this point is good right we know this is balanced binary tree or binary subtree right so we return the height of this trait back to the root so in this case we know that this is one because in this case this is a leaf node so in this case for this parent level in this case this node right here um we know that the absolute value difference between those two subtrees height is going to be two right so two is actually bigger than one therefore this is not a balanced binary sub uh this is not a binary uh this is not a balanced binary tree so in this case what we have to do is we have to return falls right to the parent stack so that in this case we have to tell the parents that this is a unbalanced right this is the unbalanced binary binaries tree right it doesn't really matter if the height here is four and the height here is three and we know that this is balanced and this binary tree is balanced because we know the height is four here right and the height is four three so the absolute values through is just one but the thing is this binary tree this binary subtree is unbalanced if one binary subtree is one or in this case one subtree is unbalanced then this entire tree is unbalanced so there should be a way that we should have to return back to the roots right the node uh the root node say that this is unbalanced so how can we do that because the function we're returning so we're returning the height of each and every single subtree so we can do is that we can be able to return a negative value symbolize this is the unbalanced tree right if i return negative one or it doesn't really matter if it's integer that minimum value or in this case negative two or anything right we can have a variable to keep track of to uh or a constant variable value represents um unbalanced binaries tree right so if we have a unbalanced binary tree we right away have to return unbalanced binary trade to the root level because if just like i mentioned before if one subtree is unbalanced we have to basically the entire sub tree is in balance where the entire tree is basically unbalanced right so basically this is how we solve the problem and in the code basically what i have here is i have a constant variable called unbalanced and this unbalanced in this case is negative one in this case this function returns a boolean so we basically check to see if the root is null if it's not we return true then we do our dfs right and the goal is that we do our dfs validate each and every single subtree if one subtree is unbalanced we will right away return back to the root saying that this sub tree is unbound right and then the root will return unbalanced right and continue and then in this case we all we have to do at the at this level is that we check to see if the current subtree is unbalanced so if it's returning on balance then that means basically it's false if it doesn't returns on balance which basically means it's balanced right so you can see here we're basically just doing our dfs right we first check to see if it's a leaf node if it is a leaf node we turn one um otherwise what we're going to do is we're going to see if this we're going to do our left subtree we're trying to get a height of our left subtree if our left substrate is unbalanced we return it on balance and we do the same thing for right subtree we get the height of the right subtree if the right subtree is unbalanced we return unbalance then lastly we just check the current tree right we check to see if the current subtree is unbalanced if it is unbalanced we return unbalanced otherwise we are going to return the height of the current sub tree or tree right so this is basically how we solve the problem and you can see this is how we solve the problem uh or the sorry the time complexity in this case is big o of n where n is the number of notes that we have in our tree and the space complexity in this case because we're doing a dfs uh is going to be vague of h where h is basically the height of tree right we're basically going to dfs and the recursion stack is basically the height of the tree okay so there you have it and thank you for watching
|
Balanced Binary Tree
|
balanced-binary-tree
|
Given a binary tree, determine if it is **height-balanced**.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,3,3,null,null,4,4\]
**Output:** false
**Example 3:**
**Input:** root = \[\]
**Output:** true
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
|
104
|
377 |
Hello everyone, welcome to my channel, you have been asked to try it. Well, this question is quite standard, but people often make a mistake in it. It is simple, it is done with the standard method, so read and understand what is happening, okay. So what does it mean, we cannot do it, we can achieve it and this is our answer, so in this I said that people make a mistake, what is it, I will tell you what is the mistake, so first of all we make a tree diagram of it and understand it. How will it happen? So we will write our standard method, we will write our solve function and apply it. Okay, so what do we do in each pick, we move further and target. In this, we have the Chhath of taking one again, meaning we can take one any number of times, then the index will not move further. Okay, so we did not move further, left it at zero and reduced our target which is four minus one. What have we done, then it will continue like this, I will tell this one here, what mistake people make, then again for this there is quality on pick and note, so what will we do to solve this, what will we do for this that here But if we are writing one as one, whenever we pick, what will happen here, if we make it always zero, then what will happen here, it will always be zero, what does it mean that it will always start from zero? So he tried again, this one, how will it be one, two, three, so here we were here, so he will pick from here also, mother, if he does not pick this, what will happen if he solves this? Why did I not understand from the one because here zero was coming every time, so you do not understand that here only zero is coming, then what will not happen, then zero again, you get similarly solved 01 simulator, what if the target is It becomes zero, it is zero, what will we do, we will move to one and band it, if we pick from here, what will we do, return, this is done, okay, so SIM simple pick plus note pick, the answer we will get from here and Whatever answer we get from here, we will add both of them and say that it is okay that we will get only one answer from here, and if we keep moving like this, then what do we have to do, then we will simply make the return zero, we will understand well about the state change, so how about this one? We will store how much is happening in the tabulation, okay, do this step, I will explain it in the court, then it will be understood better, okay, then what will we do in the tabulation, the number of DPs as much as the status is changing. If we create and travel on it, then what will we do? Once we have created one DP for the target, what will we do is, take it, we will start filing from here, it will be done just like this, you will understand better in the code how it will happen. If we have to write its code and what will be the time complexity, then we have the same two options. Okay, so this will be done, so what will happen if this one is done, how much will it be, what will we do if the target becomes zero, then what will we do? What will be reduced, what will happen and what will be the target in this one, what will be the target plus one mines and what will we do here, this will be fully accepted, copy pasted here, its scope will remain only for the name. I made memories by making ODI, here also we had one state, we removed the time so this also got accepted, now what will we do with the DP after this, we told you not with zero, but in DP, zero will always be one meaning. Target if it is going to be zero then we don't have to make it one. What was I - name what should we store it in? We will create it. Okay, how did I sleep in a base? Whenever I is a minus number index, then whenever I give it a greater number, it will be zero. whenever we have to file it
|
Combination Sum IV
|
combination-sum-iv
|
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| null |
Array,Dynamic Programming
|
Medium
|
39
|
1,252 |
Work in this field Ajay Ko That [ That [ That Hello Everyone Hello Friends Welcome to your new video in this video By going to discuss the problem number 125 Subscribe Values in Values in Values in the problem itself problem cross this life is Wearing A is equal to saw machine represents location Padhan location decided to withdraw all of our environment and which is returned of the day agreement to and location in this is ok from what is this problem said we have come in this problem Ramesh example I understand we were told that we have to cross and science classes to increase the world Subscribe to were the first example If we look at ourselves then we are the first to be given to and given to so what do we have to do Make time Subscribe and this will keep us busy right now Then we come to the channel of ABS that a Today Hey will be given which will be like this, its defeat element is the draft problem, meaning two people in every position in every element of this, if we for this then the giver and with that now we will subscribe it position. Whatever number will be given in it, whoever subscribes to it, like if I see that it is coming here that and here you have one like this, then subscribe like this, then our 10 is okay, see, we will number, if we make the inspection problem also one, then first. Column first column that every person has to be increased by one, on the first column we will come to this problem that if we see this, then if we increase this by one then it will break, we will make one of this, so after doing this, our daily intake is 21 2010 ok next us Next thing we have to do is to increase it by ₹ 1 again. Next thing we have to do is to increase it by ₹ 1 again. Next thing we have to do is to increase it by ₹ 1 again. What will we do to increase this one? This one of our gas is number one number 90 pregnant final that this is a matrix, how many more elements are there in it, after accounting and returning it to us? If we see how many elements are there in it and what will we do, we will return 123456789, then it is telling us, now let us do the school quiz question in two ways, which is our normal approach, second, you are my optimized approach in President is going to solve Ramesh Sharma, let's see, first of all, which is ours, definitely subscribe, first of all, we will make our own matrix, if I am rich and more subscribe, we will make it and we will make this cross of it our own, like what will we do? Appointed and within that, we village subscribe that whatever our roll number is, we will give one big to each element of it, we will give one big to its element, so this is Ireland, we will not make it electronic, we will take it, subscribe to its size, like see here. Android pregnant 's nex, what do we have to do inside this, we have to do one more thing inside this, if we look here, we have to do two things, first of all, what do we have to do, apply for us, so what will we do now, so we keep daily and lunch. To do and apply for that then we have to keep by number and after that 2 inches here we need so first of all we will keep ours first of all we will keep then we have to do if we will keep then we will first of all appoint 208 and subscribe your Inside we have to keep the column sorry hero angle stand so what we will do is whatever is the answer then make the answer and keep it on and we will mean to appoint for the school, if our channel is now in the school then subscribe and we will increase it by one If it is ours, then we will cut it. What happened to this village, this is ours, appointed by us, it will continue until all our elements, all our columns are updated everywhere, now as if this is ours. It will be updated, what will we do, where will we get those people, subscribe it, give us our roll number off and inside this, we have to change it, this is our channel by subscribing and incrementing it by one, like this Follow, when ours will end then this is ours, the first one, war complete file, people like us will be found, after that, like ours, this is ours, we will check the ones in our body and inside others, whatever element is ours, then we will make it green on the colors. What will we do, like this is our end here, what will we do after that, we will run a call which will go from this equal to zero till where will the zinc go and we will make it medium and whatever our other people inside this, don't wait and here if our The element, this is our ghagra, if we divide it by percentage, it is not ours at all, then we will make it a village plus and just like we and our society are plundered, if we like the time complexity for it, then what will be its time complexity? It's ours from here to here, it's ours going on, more than that, it's ours, it could be 600 * * maybe this will be our problem and if we appoint subscribe, then we have come to our retail. Above, first of all, what will we do? First of all, we will create our matrix, what size will our matrix be, we will name it as answer and what will be the side of our matrix will be that we will make the cross and the size smooth which is the giver. Senses that will be our trick which is young now we are Rafale where from where to where this 106 youtu.be went ok and we will update it every time what do we have to do inside this we go to straighten our hair Here we will change our role here to Contra Village, here we will add it to Roadshow, here we will change the content column by keeping the process, then we will run it, till where we will run it from Equal to Zero to Ireland, we will subscribe to it, we will appoint We will do it, okay turn it on and what we have to do inside this is call whatever is ours, we will keep that content from one and will increase our column which was our answer act in 8th one coin and whatever ours is zero here. What is this and this is ours? Basically this is what our festival was given was the media in which the accused escaped. If this is done then we have to update the roll number here. What will we do here? Subscribe and like we told the accused here. But we are coming and Sita and here we will run the same which we were running till N and this is ours, this time our daily will change so here we will come here first because the youth and our long pregnancy is just subscribe this For those who keep on writing, like ours will end outside where we are now and we will update you with this and inside this we have a gift of let's go to this liquid pimple 207 that Jewelers Sanjog is our column size which is add and we will 1 And what will we do inside this, if our element if our answer is A, that if we divide it into broken dividers, that is, if that zero is not a moment, that is, this note of Wards is equal to zero, then what will we do inside this? If we have to appoint one name then I will fold it like this. Now as we are finished and we are village now school, I am late and this is ours gathered for the test, now let us submit it and results come. I will post it here. We have different cases, on this then we will tell a solution, this has been done by us, so if we see, this is our 1a that the soil is 1% people, faster solution that the soil is 1% people, faster solution that the soil is 1% people, faster solution than more people, this is our weakness and this is our subscribe to subscribe and subscirbe side and this We will see the mark subscribe to if it is false then what do we have to do in the optimize approach. In the reminder approach, first we will make 21. We will make it by entering and or by making it while crying. Its size will be ours which is turn off the number, how many numbers by calling the number. And this village subscribe accused if we as many as we what to do we have to here that this two and like we are making our phone form to run from where will it run this is our is equal to zero six youth are going to be accessed and every time it Bigger than this, inside this, we inside this, if we see the role number one and as we make it will be ours because as we make it, then if it is this, then we will subscribe to this, inside this, we will first want this position by subscribing. Do yours or were limited size first limit by 0 minute crore of India is a Bakyan element we will always take and along with this to do this subscribe us with it like if it ends then our today's Liuji this create a little space here Let's do it now, what will we do in this village, its two persons will come special, all the songs will come for this, if you have the same thing problem, then I will take its value in inches soon, so what will we do now we will see that our point will join this point. So subscribe this subscribe village two and this is ours which is ours, this experiment is not only given that it is our column, its first element will be found 0 and what will it do to it, will it do its job, it will be with you in the form of doctors. This has become ours, now we will be here in the first position here and will call this here subscribe this, we will not use this in this festival and we will do this, then we will do this and this will also be ours which has become our true. That problem was that this will be our falls, so this will be our column, now what will we do and then we will mix it, this is what we have to do, now what we have to do is now we have to check which ones. value-2 If any which ones. value-2 If any which ones. value-2 If any value means this or that will become longer and I will add here, then how many are ours that we will work on here and for how many days will it last and inside this we will check that if our soul This means we can write subscribe and inside this what we will do is for one of ours so for this one mouthful and that will last for eyes will last more than 120 and will give you a big one and inside this if we have a problem then we will do it like If both of these end then we will get the disease and here how much will we get and how much will we get, how many elements will we have, whose reason will be due to which, if there are such numbers in which we will be, then if its road goes, then what will be our final result? Have to do Quartz Total: How many of these events will do Quartz Total: How many of these events will do Quartz Total: How many of these events will we have? Due to stoppage due to disease, we will have these 236 elements. Similarly, due to row, how many elements will we have due to column: how many elements will we have due to column: how many elements will we have due to column: 0.2 How many elements are there in the column, two each in the column. If there is an 0.2 How many elements are there in the column, two each in the column. If there is an 0.2 How many elements are there in the column, two each in the column. If there is an element then this is zero, this is ours, this is being repeated today, if there were, then how many of ours are being repeated * * repeated * * repeated * * What will we do, the final statement, those who do stunts are ours * * * ours * * * ours * * * How many in one, so how many elements here? And sorry, how many elements are there in a row, then you * And plus, how many elements are there in the column, how many elements will we have how many elements are there in a row, then you * And plus, how many elements are there in the column, how many elements will we have how many elements are there in a row, then you * And plus, how many elements are there in the column, how many elements will we have * * - Those who do this, subscribe to this, so if we have this value, then what does it mean? This means that along with the number to be called, if this is our If we do, then let us be able to understand it better with an example. First of all, let's take an example, it means our number is 900, our number is ours, now we subscribe to it will be something like this, first of all we have become one become one become one that today 08 one Okay, this will be ours from India. Now if we understand this, then first of all, the line for crying is 101. So if I do this, we will mute our role and this is our Ghaghra. Let's update this. This is ours. If we update this in the first Kaliyuga row, what will happen to us, we will increase it by one * we will increase it by one * we will increase it by one * What will happen to us, this way, this is our number, if we update it in 2012, then this is our village. of this is this and if we have to update again then we update and this is our first of reprint this of this is ours which was ours we were ours first was ours Paul will be so successful in this as many times as we called every day Oil and oil, these four are ours, how many similar columns will there be, all, this is ours, now, first of all, if we see the first one, ours, our first, sure, this is just once again, this is our vinegar, this is ours, and ours, if we Delhi. If he sees, wrinkles are not coming, then this third element of Tulsi is not coming, just and only one oil, if we are what we are, then this is what we are, and that too only once, whatever total number of elements we have, how many elements do we have? Must pass and should happen, according to us, if because of the numbers, they should, * should because of the numbers, they should, * should cross how many of these, so what is the plus, what to do, how many diseases do we have in each column in three columns? There are four so 320 ours is exactly 1412 per filter element during the total pass during the element the problem here is the problem is so one side of our which this element as many times as ours this is our account and this is our which twice why again This is happening in ours also and with this it means that if the above mentioned again then we have to subscribe, how many limits will we have to subscribe, how many elements will we have to subscribe, whatever our number of roll into number of Colombia. In minus one to three yes this limit we will see here that without setting which alarm our channel for stop interference as many of these are coming to our place means that war and again * * * - 6a - 6a - 6a quartz element will be No account, do we have note element Red C where 1ghz is fixed, lighter, this is our 12345, so what we are doing here, you are here, how will we calculate the total, first of all we will calculate the total element, it should be due to our There should be reasons for passing and after that, we will find out now what will we do, from what time will be the total, how many elements will there be in them and lastly, after subscribing to it, we will return our answer which will be correct in every case. So let's write to the proper father-in-law again for this, what to do first of all, if we make this type of bullion, then first of all we will make a roll, this is our new one of this size, this is our number and from where is it appointed for subscription. Till and inside this, we are our role in these eyes of a brilliant, he has to connect us with whom, Liuji subscribe, as soon as the village ends, we will meet there, here, what do we have to do, two for loops have to be run, the most First one way, how long will 2016 last, this plus and inside this we have to take out and we will take out then before this and more than 120 subscribers appointed to hate servi if our collar goes to us then what will we do it Subscribe We do We are going to return the guide Whatever number of elements from rose Number of elements from rose How many will this number of elements from lung and number of runes into a number of columns Number of columns how many Number of columns in large Number of columns in two numbers Our - time to time simple weight should be done above and fold it, first of all this here which is our this AB's this low if the largest indices are big then it has come Our Amazon will not only do this then our skin will become tight. If you subscribe then you are using it here. So you are using it here. What to do first of all, two drops two What to do first of all, two drops or friend, first of all let's make the dough. I write a little faster than this. I will subscribe for this in a moment, this is our new and this is our inside pregnant inch of this 2030 apps that will last till the dot length okay and we will update it from 1 net time what to do inside this now this What we have to do inside this is that we are a row of whatever our India is that is the void of the Airtel idea, we will make it what we are today, what we will do with it, we will make it run, with what we will combine it in this form. With took the place of the thing here with the appointed village now we will keep it and for subscribe 2012 till evening our channel now inside this we if ours is what is so if our crya is tight through then what will we do give ourselves a big Will give and plus net time If you want to do the same thing for the problem, then we copy it, do the real truth and press here today, let's run for more than 120 times, instead of stop here, and instead of here, We do, we do and - Times and Times of India will be done - Times and Times of India will be done - Times and Times of India will be done and we will make it medium, submit from now and see whether the code is our Saiya or not, Let's See and this is for our space. That's right, now let's submit it and how to write the rest of the tests, this has been our sabsakraib and if we are poster boys watch online and 1% people try the solution in this case then you should do regular questions then you can do it on our channel. You can join the link in the description Thank you for watching my video
|
Cells with Odd Values in a Matrix
|
break-a-palindrome
|
There is an `m x n` matrix that is initialized to all `0`'s. There is also a 2D array `indices` where each `indices[i] = [ri, ci]` represents a **0-indexed location** to perform some increment operations on the matrix.
For each location `indices[i]`, do **both** of the following:
1. Increment **all** the cells on row `ri`.
2. Increment **all** the cells on column `ci`.
Given `m`, `n`, and `indices`, return _the **number of odd-valued cells** in the matrix after applying the increment to all locations in_ `indices`.
**Example 1:**
**Input:** m = 2, n = 3, indices = \[\[0,1\],\[1,1\]\]
**Output:** 6
**Explanation:** Initial matrix = \[\[0,0,0\],\[0,0,0\]\].
After applying first increment it becomes \[\[1,2,1\],\[0,1,0\]\].
The final matrix is \[\[1,3,1\],\[1,3,1\]\], which contains 6 odd numbers.
**Example 2:**
**Input:** m = 2, n = 2, indices = \[\[1,1\],\[0,0\]\]
**Output:** 0
**Explanation:** Final matrix = \[\[2,2\],\[2,2\]\]. There are no odd numbers in the final matrix.
**Constraints:**
* `1 <= m, n <= 50`
* `1 <= indices.length <= 100`
* `0 <= ri < m`
* `0 <= ci < n`
**Follow up:** Could you solve this in `O(n + m + indices.length)` time with only `O(n + m)` extra space?
|
How to detect if there is impossible to perform the replacement? Only when the length = 1. Change the first non 'a' character to 'a'. What if the string has only 'a'? Change the last character to 'b'.
|
String,Greedy
|
Medium
| null |
1,095 |
hey everybody this is lry this is day 12 of the Lego daddy challenge hit the like button hit the Subscribe button drop me on Discord let me know what you think about today's prom uh 1095 finding Mountain away all right we have a hard problem which is should be fine I'm really tired I've been on the plane or some form of traveling for 25 hours got some sleep but you know not quity sleep uh and every time I get some problem about mountains I usually put in like a drwing thing but today I am too tired to do that so let's see I am even going to uh finish doing this problem really quickly as early as I can so let's uh let's do that together all right 1095 find in Mount away so away is a Mount away if it's more than three elements it's okay so it goes right given amount away um so it goes all the way to the front and the end okay so given amount a way turn minimum index such that mount okay so we know that this is a Mount away and we're trying to find Target if such an index does not exist we turn negative one you cannot access that you're going to get n or length Okay so assume that we always get this for free what's it that length right so we get this and I assume that okay yeah you only make 100 course to get um so I mean it's very obvious that they want you to do some sort of binary search and is 10 to the 4th um so we have to figure out how to do binary search right uh that's a little bit of cheating though but uh we can think about it uh let's see uh so we're just trying to find some Target right um let's see so this is a Mount away uh we have to if they're more than one we have to return the smaller one okay I mean the thing with binary search is that there's a loop in variant that we basically has to uh try to do in general right so that you can kind of uh bict it every time um you also maybe do a turn research maybe um okay I think one thing that I was thinking about in an edge case kind of thing but it actually is not happening is that all the numbers should um well it's not unique but adjacent numbers will have will not be the same right so that means that a Target can only appear twice once on the UPS slope and one on the down slope and given that we have to find a minimum index we're trying to find the one on the up um you know on the up slope side first and then it doesn't exist to on the Downs slope side I think that should be good enough um I think for these problems uh it's important to kind of just figure out you know I mean I given a 100 course you know that's way enough time to do anything um cuz you know even if you do three course to get one bit of information that's going to be 2 to the 33 which is you know more than enough for 10 to the 9 um but we here uh I think we are going to try to there a couple of I think I'm just like a little bit I wouldn't say stuck but just thinking about what I want to do there a couple of ways you can attack it one is to just kind of find a peak and then kind of B on the peak after that I don't know that's too slow or not I that's why I'm kind of sh a little bit uh and then the other side is just I don't know just like kind of play around with just binary search in general um yeah you get the first element and then you just kind of take the middle element and then does that tell you anything I guess technically not because it can appear on both sides of a mountain right I think I guess that's a little bit of a yucky part am I is my head too big I don't even know um yeah let's think about this I'm just trying to think where so I think I can do the find the peak part and then from that just find it from the left side and find on the right side that should be pretty straightforward I'm just kind of um wondering if that's too slow so we can find the peak in and let's see 10 to the 4 and we do two CES each right if we do two course each then after uh what's 10 4 is 10,000 so after uh what's 10 4 is 10,000 so after uh what's 10 4 is 10,000 so that's what like 15 14 so time 2 is 28 so we make 28 cores to just get the peak and then we do a binary search on the left that should be at most 14 cores and then another 4 I guess that should be okay uh it's a little bit complicated though that's why I'm a little bit lazy about it um but guess maybe that's fine uh yeah okay fine so let just say there's a fine Peak right um and then now we have a left is equal to zero right is equal to n minus one inclusive I suppose and then now right now what do we do so mid isal left plus right over two and then we want to see if mid is Peak then it is the smallest index where um where mid is greater than mid plus one right something like that because it means that is SL the smallest index where this is sloping right so okay so that means that if good of mid and here we can say mid is going to be so good is if this is sloping down so if the slopes down then we want to try a smaller number where mid is the right is a uh possible number so Okay this may have to be n minus 2 um so that doesn't because that checks it plus one okay else plus one and then yeah then we return left right um and then we have to uh let's call Peak good right so def Peak good um of Target right so we just return uh let's just let's call it a get function get uh mid is greater than get mid + one get uh mid is greater than get mid + one get uh mid is greater than get mid + one right also get uh of some index is just return Mountain array uh. get of Index right reason why we write it this way is because now we can add caching so that we don't make them um make a call for the same number more than once it probably doesn't matter for especially when n gets bigger or doesn't come up as much but it's a nice practice to kind of you know uh just at way at least for the smaller Ray it should help a bit then here we find Peak right so uh yeah Peak is you got to find Peak uh and then guess technically this cannot be zero but that's fine I don't care about that uh and then now see if it is in on the left side right on the left side of the mountain fine from left maybe uh maybe we can may maybe we can uh generalize this a little bit better but for now I'm a little bit lazy so let's just keep it that way for now um uh is going to Peck uh Peak will be going down after that so Peak yeah I guess that's fine whatever should go okay uh maybe we should pass in Peak I think that's a little bit better uh okay right um m is you go left press right and then now if uh let's just say if get of mid if this index is greater than um if this is greater than Target is it yeah this is greater than Target then we want to go to the left side right is equal to Mid minus one because we want to try smaller number else if get of mid is less than Target then we choose left is mid plus one because we have to get past mid and then else we can return mid right and here we can return left just as to left is equal to right and then uh yeah then left found maybe for find left is you go to find from left the peak and then if find uh if let's do it again if this index is equal to Target then we can return F left otherwise uh this otherwise we do the same thing but now the other direction on uh just so much code but and I don't even feel good about writing this Cod there is some um possible uh optimization here but I don't know right and this is just on the right side or like not optimization just in terms of writing code a little bit cleaner but yeah okay now this is decreasing now right so if this is greater than the target then if this index is greater than the target then you want to go to the right side so then left is equal to Mid + one side so then left is equal to Mid + one side so then left is equal to Mid + one or else if get mid is right is equal to Mid minus one else we can return mid because they're the same maybe we could test them for that first I don't know shouldn't matter then you find right is to find from right or Peak if get or fine right isal to Target then return this index otherwise we return one is it right so let's give a spin do I where have a typle somewhere probably oh here oh whoops all looks good here I'm a little bit lazy to add more test cases I'm going to just give us a I'm really tired to be honest like I can you keep my eyes open it is midnight here in taipe oh I'm in Taipei by the way I don't know uh see I'm just I don't even know if I mentioned it already so have it but yeah what's the complex here right we do three binary search this is going to be uh log n and yeah uh we do okay we don't you know what I do that wow that was four years ago GE B uh I guess I mostly did the same idea except I name things maybe slightly better uh yeah I don't really have much to add to this one uh hopefully this made sense I probably if I was on my home computer and less tired I would draw this out a little bit but uh but yeah we basically just find the peak and then we this just becomes a standard binary s on the left and on the right and that's it uh I am going to pass out so stay good stay healthy to go mental health I'll see yall later and take care bye-bye
|
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 |
1,235 |
hey everybody this is Larry this is day 26th of the legal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this part maximum profit in job scheduling um hope everyone's having a great weekend Thanksgiving weekend long weekend whatever it is that you'd like to enjoy uh and let's get started I'm it's a little bit late in the day so I just want to get this done and then go to sleep hopefully uh yeah so today's part of me is 12 35 maximum profit and job scheduling so you have n jobs where every job is scheduled to be done from start to end obtaining a profit or profit Supply okay uh you can start time and time profit always returning the maximum property in Texas okay um I think there are a couple of ways you can think about this one there are some dynamic programming Solutions as well um the way that I think about it though is actually as a sorting problem where basically you process um the way that I would like to think about it is basically you process these events um as two things right the beginning and the end and maybe in the beginning of the time you scheduled the end of the time but then you have to the maximum profit that you can do before then um so okay I don't know if I explained this quite well but um let me put let me bring on some drawing utensils first quick second um because I know that a lot of people do this with the dynamic programming and the way that I'm doing it is kind of dynamic programming depending on how you want to visualize and uh whatever in your um in your head but let's just say for example I have this thing right double checking that you can see because otherwise that we will decide um okay what I mean by data startups um there are let's say we only look at the starting events right so here three four and six way so what we what I'm the way that I visualize these is that okay so we go from left to right scan line algorithm again um that's what I mean by sorting maybe so yeah but here after we scheduled one we scheduled um so we've gone from left to right you see this thing and then here you scheduled the ns3 right um so the best so far is zero and then now you go from time from one to two you from here you schedule this to go here that means that here what's the best profit that we can make so here is zero still and here it's going to be 20 right and here also 20 from this one and then now we process time step three we process to 20 we go okay now the best score is 20. and then now when we process um this one we go okay well at uh time 10 this is going to be the best it's going to be 120 right because this is 20 plus profit of a hundred right um but the present is so far that we've seen is still 20. four okay so it's going to be 20 still so schedule 6 at um 90 right dot and then here uh we go to uh time five so then now this is gonna be 20 is you know same as 20 so nothing changes but you know if this is dirty then you update it do it here times six you go 90 and 90 is your best time so far or best profit so far and here we scheduled this to 150. so that's the way that I usually think about these things for non-overlapping things for non-overlapping things for non-overlapping um I think in Phoebe uh depending on how you structure the dynamic programming or whatever um like different variations might have different um I don't know if I would call them optimizations but different variants to self so I don't want to generalize too much but this is the way that I would think about this problem so um so yeah let's kind of start doing that wow we got very overwhelmingly positive scores that's like 99 or something right or close to it okay so that's basically the idea and then basically what we want to do is I have a events thing for index dot or let's just say s e and enumerate sip of start time and time um maybe Spell correctly and profit huh right and that may be best as you go to zero here and basically and this is just what we're doing right and the index do I need to index actually I don't know that I needed the index but basically here we do events that um we just set up the other events so we have the starting time we have what kind of event it is and here in this case we want the beginning of the begin the start times to come after the end times right so let's just say then um in this case you know start your fed as you go to um one and N is e is equal to zero um the way that I did this way is so that when we saw we want the end defense to happen first so that we process um you know if two if you look at example one at time step three we want to process the profit that we got from 550 goes to 50 before prostate is going to start right so that's basically why we have it like this oops uh start um and also I kind of I wouldn't say that messed up but we'll get to it a little bit um and then maybe the end time and then the profit foreign yeah okay I think that looks okay maybe we don't need to index I don't know that we need index I mean so the other so the reason why I'm kind of going back and forth is that you know if you could there are a couple of ways you can write this and if you put the index in the event then you can just pull out enp so that's why I'm kind of like whatever it doesn't really matter to be honest so it just depends on how um whether you think it's more readable or whatever um so here because we're adding new events this you can't just sort it I mean you can but it'll click what you want to do is hipify um I think that's the name of the function well maybe just start to go correctly okay I just wanted to make sure that this is because if it's not the right function name that will give it to me and then now we've got wild length of defense is greater than zero we have um so the time we have the type which I think is a keyword so okay um and then I don't know just P1 P2 for parameter one and parameter two this is terrible but we'll rename it if necessary so this is equal to hip queue dot Heap pop right uh of events and the time doesn't actually even matter because everything is you know we just use the time to keep it sorted so if T is equal to zero uh well if you go to start then e p as you go to P1 P2 um else GP uh sorry um if this is an N effect um well we'll get to any event later because we haven't really defined it right this takes so much space um okay so then now what we want to do now is we take the best as we said so far we take the best so best is equal to Max oh wait no that's not true we don't update the best yeah we update the best after we take um at the end section right so now we want to schedule the end plot and uh so we want to push um the time oh so I guess no we have e so e is the time the type is n and then what do we need for n right so it's best plus P because that's the new profit and that's pretty much it and then maybe just negative one because we need to take the room I think because that's the thing that we're updating right um because that's the profit that's the best that we know of given this event okay and then else so T is equal to n foreign the new best maybe you want to say is you go to P1 and then you know this best is good new best and that's pretty much it and at the very end the best is going to be the answer so I think that's pretty much it um yeah so that looks good that's good with submit maybe we missed some edge cases but I'm lazy today I don't know negative numbers and even funky right all right cool well apparently I did I've done this before how do I get a timeout um I guess the idea of dynamic programming and binary search huh those are funky Solutions but yeah um each item gets um getting defense as part of the Heap um what is it uh yeah so that means that for n items this is going to be n log n just because it's basically uh all we do each item gets pushed onto and popped from the Heap twice one for the start you found one from that once for the end event and everything else is pretty all of one other than the Heap push and pop and this is going to happen twice per item so yeah um that's pretty much all I have though for this one like I said it's gonna be analog and time all of n space for the defense and that's pretty much it so yeah uh let me know what you think this is kind of a shorter video but I hope that I explained it okay um it's been a long day so yeah uh let me know what you think so yeah hope y'all have a great rest of the weekend so stay good stay healthy to go mental health I'll see y'all later and take care bye
|
Maximum Profit in Job Scheduling
|
maximum-profit-in-job-scheduling
|
We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.
You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`.
**Example 1:**
**Input:** startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\]
**Output:** 120
**Explanation:** The subset chosen is the first and fourth job.
Time range \[1-3\]+\[3-6\] , we get profit of 120 = 50 + 70.
**Example 2:**
**Input:** startTime = \[1,2,3,4,6\], endTime = \[3,5,10,6,9\], profit = \[20,20,100,70,60\]
**Output:** 150
**Explanation:** The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
**Example 3:**
**Input:** startTime = \[1,1,1\], endTime = \[2,3,4\], profit = \[5,6,4\]
**Output:** 6
**Constraints:**
* `1 <= startTime.length == endTime.length == profit.length <= 5 * 104`
* `1 <= startTime[i] < endTime[i] <= 109`
* `1 <= profit[i] <= 104`
| null | null |
Hard
| null |
387 |
hello viewers welcome back to my channel hope you are doing great if you haven't subscribed to my channel yet please go ahead and subscribe I have created several playlists for various problem categories such as dynamic programming sorting searching BFS DFS and so on please check them out I have uploaded the core for this problem to github you can get the link from description below this video let's go ahead and jump into today's problem the problem is first unique characters in a string given a string find the first non repeating character in it and return its index if it doesn't exist return minus 1 that means if it doesn't exist means all the characters in a given string are repeated right so we have to return the first non repeating character right so let's see with an example right so leet code in that le was never repeated right so we are looking only for the first unique character so L is never repeated so which give the index of the L that is 0 so lovely code so L is repeated in here o is also repeated V is never repeated so the index of V is 2 so that's what we have to return so another hint that is given here is the string contains only lowercase letters so only lowercase letters in English right so there are 26 lowercase letters A to Z in English so right so basically we need to keep track of given letter and see if it occurs again or not right so that's one thing and once you keep track you need to find out what is the first unique that occurs so there are two things here so first is we need to keep track of the character when it occurs actually occurred more than once if it is occurred more than once that then that is fine but if there are characters which occurred only once right if there are more characters which occurred more than once right so for example in the lead code case L occur only once T also occurred see also occurred only once D also occurred only once but we are interested in the first unique character so out of all LT C or D L is the first character right in this string so that's why rewritten zero as the answer for this index for example if we are given with a string called a BB CC right so in that all characters occurred more than once so we return negative on right so for that so leet code we return 0 for this thing like a ABC C right we return a negative 1 so that's what it is so as we discuss so English lower case let us there are 26 letters right so what we are going to do essentially here is we will do a placeholder class which will keep track of this start position at which the character occur and end position at which that character reoccur right so that's what we are going to keep track in the placeholder class so we go through the entire string and fill up that list of those objects for the placeholder class so we are going to put the placeholder class into a map corresponding to a given character it so we since we know there are only 26 letters the map will have 26 entries so A to Z right so for a when it cut out first when it occurred last for B when it occurred first when it occurred last so likewise right so whenever we see the thing right when it occurred that is when we are interested in right so map will have 26 entries so once we maximum 26 entries right so for example in this case lead code right it won't have 26 entries for sure so L e.t.c o D so the entries for sure so L e.t.c o D so the entries for sure so L e.t.c o D so the it means it will have only 8 entrance right so maximum the map can have is 26 entries right so once we have each of those characters taunting and ending positions right so initialize the starting and ending position to the same basically L 4 L we initialize the starting and ending position to 0 we start initially starting any question - one whenever we see the any question - one whenever we see the any question - one whenever we see the next time II we update the ending position right so like that we are going to do the process so once we go through this complete string and complete the map filling up right then we go through the map and find out if there is a any character where the starting and ending position is same so those are the characters which we want when the characters starting and ending position is same that means it occurred only once if no character has the starting and ending position same in a given string that means you have to return as -1 that means you have to return as -1 that means you have to return as -1 anyway because all of them have more than one occurrence so if there is only one occurrence the starting and ending position will be same in our map right so but what we are interested in is first unique character right first unique character so what is the minimum starting and ending position is the question that we need to answer right so that is what our answer for this problem so let's go ahead and try to apply that logic right so I have written the logic in a sentence formation here once we go through the entries and collect the starting and position of the location keep track of the mean and exit and initialize it to int max so minimum index we initialize 2 into max based basically we go through the map and find out if the starting and ending location is same for a given character so that means if it is same that means it occurred only once right so if so check start of the given character is less than a minute min and X so that is what we are checking so if start is less than the main index then we update the min index out otherwise we don't need to update so many next is whatever it occurred so finally we return the min index so let's go ahead and apply this logic to this first row first same string leadcore so down below I have put all the indices for L is 1 X or L is 0 is 1 next T is 2 so those are the indexes right so now I am preparing the map so L will occur this is the starting position so this is a character and start and end position right so that's how it is e it occurred at 1 and occurred at 1 so when we go through the complete so this is when we are going through this string right going through the string and fill them up right so now so when we are at ii we update eetu the ending position is 2 and next thing is t.t occurred at what 3 and next thing is t.t occurred at what 3 and next thing is t.t occurred at what 3 right so 3 is starting and tree is ending right all right so elite ii code right c/e is at 4-4 right oh also oh is also c/e is at 4-4 right oh also oh is also c/e is at 4-4 right oh also oh is also at 5 right d is at 6 right that's what we are initializing and next thing last thing is a sorry e so E is already occurred so we are going to update E as the last location is 7 right so now we have this map right so we have this map so now we go through this map and try to find out if there is a start location and any location is same and let's initialize the min index 2 min and x2 in max right so that's what is initialize and we go through the map so we are at l means this is 0 start and end the same and the 0 is less than mid intimate right so we take the into max off and put 0 in there and when we are processing II the starting and ending are not same so we ignore that when you process T starting and ending is same so 3 is the starting location so 3 is greater than min index so we don't update min index so steal sorry see next character right so 4 & 4 they are same character right so 4 & 4 they are same character right so 4 & 4 they are same for is greater than 0 again 405 is greater than 0 for D 6 is greater than finally what is the minindex we have left with 1 and x is 0 so return this right which is what we want right return 0 for lead code so this is how we are going to proceed go ahead and look into the core the idea of the code is exactly the same what we discussed right so now we created a placeholder class what I'm calling us place so it will have start and end location right so I have a character this is a map for each character and keeping track of the place that will keep track of the start and end location so that will be in a map I'm going through the length of the string so I'm going through each character and updating the maps starting and ending locations right so with this so once I update the maps ending and starting locations I will have to go through the map right so in each place the main index to the intimates value and go through the map so while we go through the map check if the starting and ending is same in other words I am checking starting and ending difference is zero right if it is zero that means they are starting and ending location is same right so and check whether the minimum Dex is minimum or start is minimum so update the stuff update the minimum index if it is you know when X is greater than start right so finally check if the minimum index is still pointing to in max value so this means what the co the string has all duplicates right all duplicates there is no unique character that means right so if that is the case reassign minindex to -1 finally written the min index so to -1 finally written the min index so to -1 finally written the min index so this is how the code is going to look like so let's go ahead and look at the time complexity for this and space complexity also right so time complexity we are going through the complete string s right so this is s so the length of s so let's say length of s is M right so that means for this for loop we are going through the entire string so we will say order of n is a time complexity for this photo and the next for each so this one is so the map will have the maximum of twenty six entries so that means it is a constant number right so 26 is constant irrespective of your string length even if your string length is 100,000 or if your string length is 100,000 or if your string length is 100,000 or 200,000 it does not matter it the string 200,000 it does not matter it the string 200,000 it does not matter it the string length will change but the map is constant because we are having only 26 English letters in lowercase right so this for loop will be executing only 26 times irrespective of the string length so we can take that as constant R plus order of 26 in that case right so it will be order of n plus 26 since we don't care about the characters are the constants in the Big O notation finally the time complexity we are going to say is the order of M and the space complexity so space complexity is we are using this dictionary rate as we said the dictionary will hold 26 characters right so that is also a constant right 26 characters and 26 starting and 26 ending locations so basically each entry in the map will have order of one character plus one integer so starting and ending so that is order of nine bytes right so but of course this nine bytes will change depending on the number of I've been depending on the language I'm just taking it in general right so this will be we are multiplying it with 26 right so 26 into that many right so 26 into 9 bytes right so this is all constant again so what we are going to say is it will be constant space irrespective of the string length so the time complexity for this algorithm is order of N and space complexity for this algorithm is order of 1 that means a constant if you have any questions please post them in the comment section below this video I have posted this code to the github repository you can find the link in the description below this video if you haven't subscribed to my channel please go ahead and subscribe and also share among your friends also please click on the bell icon so that you will be notified about my future videos thank you for watching I will aback with another problem very soon till then stay safe and good bye
|
First Unique Character in a String
|
first-unique-character-in-a-string
|
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`.
**Example 1:**
**Input:** s = "leetcode"
**Output:** 0
**Example 2:**
**Input:** s = "loveleetcode"
**Output:** 2
**Example 3:**
**Input:** s = "aabb"
**Output:** -1
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only lowercase English letters.
| null |
Hash Table,String,Queue,Counting
|
Easy
|
451
|
771 |
all right welcome to this video we're gonna solve Lika prom 771 jewels and stones now I do want to say ahead of time this is a very easy problem to solve at least in my opinion and I would never expect to be asked this on-site never expect to be asked this on-site never expect to be asked this on-site interview however if you're going through a technical phone interview or technical screening I can definitely imagine this being asked because this will filter out a lot of candidates I also think it involves a lot of different problem solving skills so that's what I want to focus on this problem now of course you like this kind of content be sure to LIKE comment subscribe and hit that notification Bell to be notified of new content and of course I have full-length courses on my course I have full-length courses on my course I have full-length courses on my website ka education com ok so let's get started so what I'm gonna do is create a count variable B equal to zero all right I assume that you've read the directions all right so then I'll say Const jewels hash table is equal to this empty object okay and we're gonna toss all the jewels right so let's say to be give us a jewel string of a and so we want this to say oh hey a is a jewel so just say true here and capital A or excuse me let's get within that JavaScript object and capital A also counts as a jewel so we're gonna use a hash table store what things are actually valid jewels because we also want the oh of one lookup time that hash tables give us which is a very good time complexity right so then let's fill this out because it's empty and we get to make it look like this based on the input string of capital J which represents jewels so I'll say for Const jewel of J jewels HT jewel is equal to true right so let's go about the four of loop that JavaScript gives us is we can iterate over every character of the string capital J and our input string is you know let's see this was like that right now our jewels HT will look like this then I'm gonna say for now let's iterate over every character of capital S right so we can just almost copy this verbatim here so it's also to say for cons stone of s you could also call this s chart you call this J char but let's go with the directions for a kant's tone of s if stone in jewels HT right or you could also say if jewels HT stone is a truth devalue but I prefer the new syntax of cut if stone in jewels HT count plus equals 1 right and then after this for loop runs our account will now be accurate sauce a return counts save make sure it passes our tests or passes leak codes test excuse me okay great so what is the jewels and stones complexity analysis time complexity is o of j + s right which complexity is o of j + s right which complexity is o of j + s right which makes sense where J and s are the number of characters and input strings actually comp this out right now so this is o of J because we iterate over every character of input string J right this makes sense is oj when you we fix that and then this time complexity is well o of s makes sense self-explanatory we of s makes sense self-explanatory we of s makes sense self-explanatory we iterate over every character of input string s of j plus o of s ok that is a j + s or o of S Plus J whatever space + s or o of S Plus J whatever space + s or o of S Plus J whatever space complexities o of J because our jewels HT hash table will have the number of keys right equal to the number of characters in J right jay-j hence our of characters in J right jay-j hence our of characters in J right jay-j hence our of J space complexity alright I hope you enjoyed this video I'll see you soon
|
Jewels and Stones
|
encode-n-ary-tree-to-binary-tree
|
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`.
**Example 1:**
**Input:** jewels = "aA", stones = "aAAbbbb"
**Output:** 3
**Example 2:**
**Input:** jewels = "z", stones = "ZZ"
**Output:** 0
**Constraints:**
* `1 <= jewels.length, stones.length <= 50`
* `jewels` and `stones` consist of only English letters.
* All the characters of `jewels` are **unique**.
| null |
Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
|
Hard
|
765
|
73 |
hello friends in this video we will solve it code problem number 73 set matrix zeros so first we will understand the problem statement after that we will see approach for this problem and at the end we will see code in java the question says that we have given encroachment matrix if an element is zero we need to set its entire row and column zero and we need to do in place so in places we do not need to create any other matrix we need to do in the given matrix only we have 0 is at this position so we need to make all of that row to 0 so means this and all of that current column also to zero so as we can see we have here zero and zero so we need to do this thing in same matrix let's understand the approach for this problem so we have given this matrix and we have taken two boolean variables for taking the first row and first column if zero is present or not here first row and first column have no zeros then by default it is initialized with false so it is remain false only so we will go through the matrix we will skip this part and we will focus on this part so this is this have index 0 1 2 after that if we found 0 at this point so we will convert that current row and current column means from that first row and first column to zero so this will be zero and this will be zero after that we will go through this is one so we will not convert its row and column after this is one after that this is one so again we will add it through this matrix means this part of the matrix and check if this is one and its first value is 0 or not if it's 0 then we will convert it into the 0 so currently we have this matrix 0 so we will convert this value to 0 because we have this 0 or this 0 but we have here 1 and here 0 so we can convert it to 0 after that we will go to this index so this will remain as it is so we will check if it's for first row and first column have 0 or not so 0 is there in the row so we will convert into the 0 after that we will check for this and row have zero it don't have zero and current column is also not zero so we will keep one as it is so this is our final answer so there are two points we need to keep in mind we need to assign first column and first row if we found any 0 at any position after that we need to iterate through the matrix and check if that current position is one and if it's first column and first row is zeros then we need to assign value zero after that if we have first row and first column is present is zero then we need to convert that column or row into zeros so now let's see example two that we had solved with example one so first we need to check row and column let me index it zero one two three zero one two at first row we have two zeros so at this point we get zero then we will first row equal to true and first column is also true so we need to focus on this part now so we will check if it's first row and first column is 0 or not so it is 3 it is not for this also we not after that 4 2 we have zero in the row first row and column we don't have so we will convert this into zero so from the both we need one zero we need to convert that into zero after that we will check for three column and row note have zero four one also not have four five the row have zero then we will convert it into zero after that we will iterate through if row is true then we will convert all the row elements to zero so it will be zero and column is also true then we will convert that column values into zero so it will be zero 0 so from this also we can see this all elements to be 0 so this is our final answer let's see the time and space complexity for this solution so time complexity will be of rho into column inside it into matrix and space complexity will be of 1 because we are not using any extra memory only variables we are using now let's see solution in java so here i have taken two boolean variables first row and first column for identifying the first column and first row have zero or not so for this loop is checking if the current column has zero or not if it has zero then we are breaking at that index means we identify that at particular column or particular row we have zero from this both we are checking after that we are checking for elements means skipping the first row and first column so we are skip the index 0 for row and 0 column so we are iterating through the 1 after that we are checking at that particular index we have zero then we are assigning that first row and first column to zero value after that we are rotating to the same loop from one and checking if that current index means first row and first column have zero at that column and row and we are assigning zero here we are checking if first column have zeros then we are assigned all columns to zero and here also thank you for watching my video please like and subscribe to my channel because it motivates me to create more videos
|
Set Matrix Zeroes
|
set-matrix-zeroes
|
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s.
You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
**Example 1:**
**Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\]
**Example 2:**
**Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\]
**Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[0].length`
* `1 <= m, n <= 200`
* `-231 <= matrix[i][j] <= 231 - 1`
**Follow up:**
* A straightforward solution using `O(mn)` space is probably a bad idea.
* A simple improvement uses `O(m + n)` space, but still not the best solution.
* Could you devise a constant space solution?
|
If any cell of the matrix has a zero we can record its row and column number using additional memory.
But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker?
There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
|
Array,Hash Table,Matrix
|
Medium
|
289,2244,2259,2314
|
66 |
all right today we're going to be solving problem 66 plus one it's an easy problem it has a lot of likes but it has even more dislikes i actually like this problem so let's just do it uh i'm not going to read the description because description is a little bit confusing i will just show the example so we have number 123 and the stored as an array we want just to increment by one return line 24. so it's four three two one we want to return four three two so the interesting case is when we get nine so what we when we get nine we want to increment and actually return 10. so how can we solve it so we'll loop up from the back of the array and if we see the number does not equal to nine we just increment by one and return right away but if we see the number let's say 9 and it's 9 then we have to switch it to 1 to 0 and then append one at the beginning so let's look at it in the code so first we create a for loop irradiant from the back of the array so let's say four let i equal digits that length minus one i is more than equal to 0 i minus so that's the regular for loop and then we say if digits if the current number that we on equal to 9 what are we going to do we're going to say we change this number to zero and if it not and if it's not zero we'll increment this number by not by one digits i plus and then we want to return right away because we don't want to append one we return digits and then if we go through if it's 999 let's say if it's the array like this 9. we'll flip everything to zero so it becomes zero but we have to append at the beginning one so in javascript the way we append we say digits dot on shift one and then we return digits so if we have 123 we'll go into the loop and we return right away so we'd never append one but if it's all nines 999 only then we go through the loop we append one in the beginning and then we return the you know correct number let's submit and see how we've done all right we have five percent speed and 91 percent or space so good speed i mean good space uh not so good uh speed but i think it's just because of my internet connection is slow so this is how you solve number 66 plus one if you find this information useful please you know hit that like button and then leave me a comment below for which video you want me to uh which little problem you want me to discuss and good luck for your upcoming interviews thanks for watching
|
Plus One
|
plus-one
|
You are given a **large integer** represented as an integer array `digits`, where each `digits[i]` is the `ith` digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading `0`'s.
Increment the large integer by one and return _the resulting array of digits_.
**Example 1:**
**Input:** digits = \[1,2,3\]
**Output:** \[1,2,4\]
**Explanation:** The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be \[1,2,4\].
**Example 2:**
**Input:** digits = \[4,3,2,1\]
**Output:** \[4,3,2,2\]
**Explanation:** The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be \[4,3,2,2\].
**Example 3:**
**Input:** digits = \[9\]
**Output:** \[1,0\]
**Explanation:** The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be \[1,0\].
**Constraints:**
* `1 <= digits.length <= 100`
* `0 <= digits[i] <= 9`
* `digits` does not contain any leading `0`'s.
| null |
Array,Math
|
Easy
|
43,67,369,1031
|
213 |
today we'll be going over leode problem 2113 house Rober 2 this is another problem off the blind 75 list which is a list of problems commonly asked during technical interviews in this problem we're going to imagine that we are a professional robber and we want to rob a certain amount of houses along a road what we want to do is return the maximum amount of money that we can rob from these houses however we must keep in mind two rules one is that we cannot Rob two adjacent houses and a second one is that these houses are arranged in a circle now the second rule is the only difference between House robber one which is another problem I solved on my channel and this problem House robber to because the houses are arranged in a circle this means we cannot Rob both the first and the last house in our array so we have this nums array and this nums array represents the houses and the amount of dollars each of the houses has the first house has $2 the second house the first house has $2 the second house the first house has $2 the second house has $3 and the third house has $3 and the third house has $3 and the third house has $2 I have drawn another example here to $2 I have drawn another example here to $2 I have drawn another example here to the right and we have a nums array with four houses and Each of which containing a different amount of dollars now we're going to go through the solution that we used for House robber one because this solution for this problem is actually just going to be a tweak to that algorithm we already learned during House robber one so again we're going to use dynamic programming which will allow us to solve the problem in a linear time complexity as well as a constant space complexity now we're going to look at this array and we want to take into consideration the two possible paths we can go through because this will allow us to break the problem into smaller sub problems which we could then reuse in order to solve our bigger larger problem so we know that when starting from the first house we have two options we can either decide to rob the house and therefore we would take the $1 and therefore we would take the $1 and therefore we would take the $1 and in that case we would have to skip the next house because these two are adjacent and we cannot Rob to adjacent houses and then we would go on to find the max that we could add to this $1 the max that we could add to this $1 the max that we could add to this $1 dollar that we robbed by going from this part of the array all the way to the end having skipped the second house our second option instead would be to skip this first house and so what we would do is go and find the maximum amount we can rob starting from this second house and we see over here at the bottom I have basically wrote out this recurrence relationship so we have our first case which I underlined in red where we rob house zero and then go on to find a Max from robbing from house two all the way to the end and then our second case where instead we skip the first the house at index zero and we find the max that we can rob between house one till the end and what we're doing is basically finding a Max between these two cases and returning that as our solution now both of these two sub problems here when we go from the second house to the end and from the first house to the end can be similarly broken into smaller sub problems just like we broke down this problem for the entire array and because of this we can use dynamic programming so now we're going to see what we're going to do while moving along the array we're going to start from the first index zero and at each point what we want to do is find the maximum amount we can rob possible up until this point now if we're only considering this one we know that we can either rob it or not and since we're not looking at the future we'd rather Rob this house and so up until this point our Max would be one then we' move on to the next index one then we' move on to the next index one then we' move on to the next index now we see we have a house with $2 so now we see we have a house with $2 so now we see we have a house with $2 so our option would be either to Rob this house with $2 or Rob the house with $1 house with $2 or Rob the house with $1 house with $2 or Rob the house with $1 which we have the value here but we cannot R them both because they're adjacent so of course at this point up until this point we were decide to rob the second house with $2 then we move on to index 3 again we $2 then we move on to index 3 again we $2 then we move on to index 3 again we have two options we can either Rob this house and if we do we can go and add the $1 from two positions ago $1 from two positions ago $1 from two positions ago or we can decide to skip this house and take the preceding value however we cannot take this proceeding value if we decide to Rob house three because these two are adjacent so of course because 3 + 1 is 4 adjacent so of course because 3 + 1 is 4 adjacent so of course because 3 + 1 is 4 and that is greater than two we'd rather Rob house three plus the first house and get a sum of four then we would move on to our last index in our array so again what we didn't House robber one is we would consider if we want to Rob this house and therefore we would be able to add the two from two positions before or if we want to skip this house and instead take the preceding value however once again we cannot wrap both the preceding value and this current one because they are adjacent so we'd rather take this four because it is greater than 2 + 1 four because it is greater than 2 + 1 four because it is greater than 2 + 1 which is three and so we'd have four as our max value now this is exactly how we solved House robber one and we know that because in each case we are analyzing our current value and comparing it with the values which come preceding it and two houses prior we only needed three pointers Rob one Rob two and Cur we would solve the solution for the current value which depends on Rob one and Rob two each time and then we'd move our pointers along to find the next values now for this case however in house Rober 2 we need to consider one extra thing and this will be a small change to our algorithm in fact we are told that these houses are arranged along a circle and because of this we know that the only difference is that we cannot Rob both the first house and the last house because if they're arranged along a circle the first and the last house are actually neighbors consider this a circle and this is the first house and this is the last house so what we're going to do is basically run this algorithm from House robber one twice and the first time we will run it starting from index zero up until the second to last position and the second time we're going to run this algorithm starting from index one and going along until the last position in this case in our two algorithms we're not taking into consideration both the first index and the last index at the same time so we do not interfere with this Rule and after having run this algorithm twice we would basically just return the maximum value that we obtain each time between both the times that we run the algorithm so because we're just running our algorithm twice it remains o of M and we are still using the three-pointers so it's constant in space three-pointers so it's constant in space three-pointers so it's constant in space complexity but we just have a small change from our house robber one algorithm and I'll show you this in the code we're going to start off our code by taking care of an edge case we know that if our length of nums the nums array which represents the houses is one this means that we only have one singular house and so we want to rob that singular house because it's the only one we can possibly Rob so we're going to return nums of zero now what we said we're going to do is basically run the algorithm from House robber one twice and each time we're going to get a different value the first time we want to run the algorithm which we're going to call F Max Rob and we'll Define this function later and we want to run it by taking our array starting from index zero and going to our second to last position in our array so I'm going to put here as the end point length of nums minus one because we know that this second parameter is non-inclusive and then our second value non-inclusive and then our second value non-inclusive and then our second value Max 2 is going to be taken by running the same algorithm but this time going from the first index up until the end of the array so length of nums and what we want to do at the end is return the max value between these two cases now we need to Define our F Max R function so we're going to Define this function and it's going to take in our array which is going to be different in the two cases and initially we can Define our Rob one and Rob two pointers which will be initialized to zero and remember our timeline goes like this where we have first Rob one Rob two and then our current value and then for each number in the array we want to calculate our current value which is going to be depending on our two cases one where we rob the current house and then add that to the max value we had up until two houses prior so Rob one or we can decide to skip the current house and keep the value from the previous adjacent house which is Rob two and then we want to move our pointers so Rob one is going to be Rob two rob two is going to be the curve or the current value and then at the end of our function we can just simply return Rob two or we could also just return the current value because we know at this point Rob two and c will be the same so let's make sure this runs and we see that it works thank you so much for watching this video if you enjoyed it please like it and subscribe to my channel I'll see you on the next one
|
House Robber II
|
house-robber-ii
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[2,3,2\]
**Output:** 3
**Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
**Example 2:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** 3
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 1000`
|
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
|
Array,Dynamic Programming
|
Medium
|
198,256,276,337,600,656
|
598 |
welcome to august leeco challenge today's problem is range edition two you are given an m times n matrix initialized with all zeros and an array of operations where ops i equals a comma b essentially means uh it should be incremented by one for all of zero less than or equal to x less than a well essentially they give you a coordinate and that's going to start from zero all the way to that coordinate and everything inside that area box or square whatever you want to call it is going to be incremented by one so here we see that we start with 2 and we increment all the boxes or cells from 0 to 2 all these become 1 and then we increment everything from 0 to 3 by 1 and then we find at the very end we will have 4 cells with our max integer which is going to be 2. so at first glance this seemed like a problem where i just recreate this temporary array here let's make this matrix rather and then i can just go through the operations and increment every cell by one but that's not going to work because immediately you'll get a memory limit exception so that told me that we don't want to create any temporary matrix we want to figure out if there's a way to do this in constant space and the way that we could think about this is we know that all the cells from zero to whatever here are going to be incremented by one right so what that means then is whatever rectangle or square that we're given at the very end there's gonna be one area of squares that starts at zero and goes to some coordinate that's going to be the maximum amount and given that all these overlay from 0 that basically means our area of the maximum integers will be the minimum rows and the minimum columns and if we have those two then we can just calculate the area and then just return that and that's going to be the number of cells with our maximum integer so let's figure this out what we'll do is initialize call it min row and min column and these start with m n next we'll just move through all of our rows and columns in operations and we're going to calculate what the minimum is here so min r and min c is just equal to the min of min r and this would be the min c and c finally we can just return the area calculated here and this would be it let's make sure this works okay let's go and submit it there we go so time complexity is just o of n or um n being the number of operations which is nice and it's going to be constant space yeah so you know you can easily go down bad paths here and try to do this like brute force straightforward but pretty quickly you should realize like that's never going to work because um you know when the numbers get even a little bit big it starts giving you memory limit exceptions so yeah once i realize that i knew there had to be some clever way to do this and that's what i came up with so okay thanks for watching my channel remember do not trust me i know nothing
|
Range Addition II
|
range-addition-ii
|
You are given an `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai` and `0 <= y < bi`.
Count and return _the number of maximum integers in the matrix after performing all the operations_.
**Example 1:**
**Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\]\]
**Output:** 4
**Explanation:** The maximum integer in M is 2, and there are four of it in M. So return 4.
**Example 2:**
**Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\]\]
**Output:** 4
**Example 3:**
**Input:** m = 3, n = 3, ops = \[\]
**Output:** 9
**Constraints:**
* `1 <= m, n <= 4 * 104`
* `0 <= ops.length <= 104`
* `ops[i].length == 2`
* `1 <= ai <= m`
* `1 <= bi <= n`
| null |
Array,Math
|
Easy
|
370
|
105 |
hey everyone welcome back and let's write some more neat code today so today let's solve a pretty fun problem construct a binary tree from a pre-order construct a binary tree from a pre-order construct a binary tree from a pre-order and in order traversal so we're actually given two integer arrays representing one the pre-order traversal and two the pre-order traversal and two the pre-order traversal and two the in-order traversal in-order traversal in-order traversal of a binary tree and our goal is to take these two traversals and the orderings of those nodes and then can reconstruct basically the original binary tree that the traversals are from and it is technically possible these two traversals have all the information we need we just need to take that information and then deconstruct it and then reconstruct this binary tree from those so just to verify it let's go through this tree and actually do the pre-order tree and actually do the pre-order tree and actually do the pre-order traversal first of all so first we know pre-order traversal is you first we know pre-order traversal is you first we know pre-order traversal is you start at the root and then you process the current node then you do the left subtree then you do the right subtree right so let's just do the pre-order traversal so we're starting at pre-order traversal so we're starting at pre-order traversal so we're starting at the root we do the root node first that's how pre-order works so then we get a three pre-order works so then we get a three pre-order works so then we get a three next we're going to go to the left sub tree and then do pre-order traversal on that and then do pre-order traversal on that and then do pre-order traversal on that left subtree we see nine right so we're going to add nine to our pre-order traversal and it doesn't have pre-order traversal and it doesn't have pre-order traversal and it doesn't have any children so we're actually done with nine we're done with three now it's time to do the right subtree in pre-order traversal so we start at 20 in pre-order traversal so we start at 20 in pre-order traversal so we start at 20 add 20 to our pre-order 20 to our pre-order 20 to our pre-order go left we see 15 add 15 to the pre-order pre-order pre-order 15 doesn't have any children now we go to the right subtree seven so add seven it's our last node to the pre-order traversal right and to the pre-order traversal right and to the pre-order traversal right and this actually take a look at this take a look at all the values it matches exactly with the input so this is the uh pre-order traversal now let's just pre-order traversal now let's just pre-order traversal now let's just validate the in-order traversal validate the in-order traversal validate the in-order traversal as well inorder traversal is we start at the root right we take care of the entire left subtree first then we take care of the root node and then we take care of the right subtree with in order traversal that's the general order so let's validate the inorder traversal of this tree so we're starting at one we're starting at the root three but we're not going to add three yet first we're gonna do the left subtree we see we have a nine the nine does not have any left or right children so now we can add that nine to our inorder traversal remember we're doing this in order left to right we go back up to the root now we can process the root we can take three and add it to the inorder traversal and now we're going to do the entire right subtree so we get to 20 but we're not we're going to wait for 20. we're going to first do the left subtree 15 is the only value here so it doesn't have any children add 15 to the inorder traversal now we can add 20 because we've done the left subtree 20 is added and then last we go to the right subtree only one value seven let's add that seven to our in order now let's take a look at these five values notice how they are the exact same five values in the exact same order as that in-order traversal that we were that in-order traversal that we were that in-order traversal that we were given so we can see that the that what they gave us was correct but now the question remains how can we actually take these two uh arrays these two traversals and construct this tree well it's definitely possible let me show you how to do that right now so i just want to let you know that there's actually two things two main facts that we're going to be using to construct this tree so the first fact is that the first value in pre-order traversal is always going in pre-order traversal is always going in pre-order traversal is always going to be the root right we remember when we do pre-order traversal right pre-order traversal right pre-order traversal right we're always processing the root first so if i was taking the pre-order traversal that we're given the pre-order traversal that we're given the pre-order traversal that we're given right we remember this is the pre-order traversal remember this is the pre-order traversal remember this is the pre-order traversal that we're given the first value in pre-order traversal is first value in pre-order traversal is first value in pre-order traversal is always going to be the root so this is the first value three it's guaranteed to be the root because that's how pre-order traversal works the first pre-order traversal works the first pre-order traversal works the first value in pre-order traversal is always the in pre-order traversal is always the in pre-order traversal is always the root node now we don't know about the rest of these right but we can recursively construct now the left subtree and the right subtree right we can we're done with this three right now our goal is to reconstruct the left subtree hey lucky for us the first value here is always going to be the root of the left subtree right because that's how pre-order traversal works that's how pre-order traversal works that's how pre-order traversal works right so that's one thing that we're going to use the first value is always going to be the root and then we can take the sub list right we can remove the three we don't need to look at it anymore then we take the sub list and then basically we're going to do this recursively that's what i'm telling you okay we can construct the root but we need more information than that right and then we're let's say we're done looking at this three now i want to take this uh array right and i want to know which values are going to go in the left subtree and which are going to go on the right subtree from looking at the actual tree itself we know the answer right we know that this is where we're going to cut our list right the 9 is going in the left subtree right these three values are going in the right subtree but how can we determine that well that's what we need our inorder traversal array for okay so now let's take a look at the input array we're given for the inorder traversal and by the way let me just mention that every value in the traversal is guaranteed to be unique that's true for both of the traversals the inorder and the pre-order every the inorder and the pre-order every the inorder and the pre-order every value is going to be unique because every value in the tree is going to be unique but okay so far we know that this first value three is gonna be the root right so now let's find three right we know three is the root right so we removed it from our first list basically right but now let's find it in our in order list we find it's right over here 3 is in this index right so we know we don't need this 3 anymore right we already created that node but so now what does this in order array tell us notice how this is convenient for us every value to the left of the 3 that we just created the root from every value over here which is only 9 is going to go in the left subtree and every value to the right of 3 is going to go in the right subtree that's really convenient for us why is this the case because that's basically the purpose of in-order basically the purpose of in-order basically the purpose of in-order traversal right it guarantees that we're going to go through the tree in order right from left to right basically right so if we see the three here and that's and this is the position in the array we know everything here is going to be in the left sub tree everything here is going to be in the right subtree that's what it tells us this is really convenient for us because we can count it right we can see there's exactly one value that's going to go in the left subtree and there's exactly three values that are going to go in the right subtree so what we can do is we can take the remainder of the pre-order of the pre-order of the pre-order array and then partition it right partition it over here because we know one value is going to go in the left subtree and three values are going to go in the right subtree so that's what we're doing and we're going to continue this right so now let's recur and by the way in the code we're going to do this recursively let's create the left subtree we know that okay this is the in order portion right and this is how we're gonna partition it from pre-order right we see this is it from pre-order right we see this is it from pre-order right we see this is the array to create the left subtree the thing here is notice how this is size one right there's only one value here and there's only one value here right that tells us that the sub tree we're creating is only gonna have one node in it right so nine is the only node in the left subtree so we're going to create that node put the value there and now we're basically done with this left sub tree obviously because there's no more uh you know there's no more nodes left in this general area right this these values are reserved for the right subtree this is reserved for the right subtree okay so now we're looking at the pre-order portion right there's three pre-order portion right there's three pre-order portion right there's three values just like in the in order portion and remember how are we gonna create the root node of this subtree now we always take the first value in pre-order take the first value in pre-order take the first value in pre-order traversal it's 20 right the value is 20 so we're going to take this value 20. we don't need it anymore because we're going to create a node from that value and so now we need to know which values are going to go in the left sub tree and which are going to go in the right subtree we know by finding 20 right 20 is the value let's find 20 in our in order traversal it's over here by the way in the code i'm going to be calling the index of this mid so m for mid we find the index of 20 right we know we don't need 20 anymore so we can get rid of it right we see that there's one value on the left of 20 and there's one value on the right of 20. this tells us that one value is going to go in the left subtree and one value is going to go in the right subtree right just like we have over here so now let's construct that left subtree we know it's going to be exactly size 1 from looking over here so we take this 15 right where can we now our job is to recursively create the left subtree we're going to take this 15 since it's the first value in the subarray for pre-order right we know that it's going pre-order right we know that it's going pre-order right we know that it's going to be the root of the current subtree we're at so let's get rid of this 15. let's create that node right 15 over here is going to be a node and there's no more values left in this subtree because we know it's only going to be size 1. okay now we're creating the right subtree we know that there's only one value in the right subtree from looking over here with and since there's only one value left in general it's a seven we can make a node from it and then we're done we know we're done because we've basically gotten rid of every single value in our arrays pre-order and in order in our arrays pre-order and in order in our arrays pre-order and in order so using these two arrays we were able to create our tree correctly and just let me just summarize what we're actually doing we're not doing a lot we don't need a ton of information remember the first value in pre-order the first value in pre-order the first value in pre-order the pre-order array is always going to the pre-order array is always going to the pre-order array is always going to be the root right that's just how it works and then once we take that value create a node from it and then when we try to look that value up in order traversal right then we can get some subarrays right we can take the length of the left and right sub array so the right sub array is three and the left sub array is one note now these counts one and three they tell us how to partition the pre-order traversal how to partition the pre-order traversal how to partition the pre-order traversal so take a look at the pre-order so take a look at the pre-order so take a look at the pre-order traversal one tells us that we're gonna cut over here because this needs to be size one this needs to be size three and then from this subarray with only one value we are going to recursively run the algorithm to create this left subtree and with this sub array we're going to recursively run the algorithm to create this subtree and we're just going to continuously repeat that process until we get to our base cases and until we're finished with every single node that we need to create so now let me actually show you the code it's actually very short less than 10 lines okay so as i mentioned this is a recursive algorithm so we always want to start with the base case and the base case is going to be what if we don't have any nodes to traverse through the two arrays that we're given that means we can return null or basically we don't have to create a tree so if pre-order is empty or a tree so if pre-order is empty or a tree so if pre-order is empty or in order is empty then we can return null we have no values so we don't need to create a tree we can return null otherwise we're going to create a tree node right and what's the value of that tree node going to be well it's going to be the first value that happens to be in the pre-order the pre-order the pre-order array just like i showed you right always going to be the first value so it's always going to be index of zero and then whatever that value was we want to find the position of it in the in order array so inorder dot index so we want the index of that value pre-order of zero pre-order of zero pre-order of zero and we're going to get it in mid now this is the part where we're going to build the subtree so root.left let's create the left so root.left let's create the left so root.left let's create the left subtree and we're going to do this recursively as i mentioned so self.build tree we're calling the so self.build tree we're calling the so self.build tree we're calling the function that we're inside of and the convenient part about python is we can do sublist so that's going to cut down our code quite a bit so we need to pass in the new pre-order and in order arrays or the pre-order and in order arrays or the pre-order and in order arrays or the sub-arrays more likely so pre-order sub-arrays more likely so pre-order sub-arrays more likely so pre-order what are we going to pass in for the left subtree of pre-order well mid tells us pre-order well mid tells us pre-order well mid tells us how many nodes we want the index of basically the value of mid tells us how many nodes we want in the left subtree so what i'm going to do is for pre-order pre-order pre-order we're going to start at index one we're basically skipping the zero index because we already just created a node for the zero index we're starting at index one going all the way up until mid plus one in python this mid plus one is non-inclusive so this mid plus one is non-inclusive so this mid plus one is non-inclusive so this sub array is really just a pre-order from index one to mid so a pre-order from index one to mid so a pre-order from index one to mid so that's what we're doing and we're going to pass in the in order portion that we need as well and that's just going to be from the beginning up until mid but not including mid right this probably makes more sense if you go back and look at the picture but basically we're just creating the appropriate sub-lists appropriate sub-lists appropriate sub-lists that we need to create the left subtree we're going to do basically the exact same thing with the right subtree and i would encourage you to draw this out yourself to basically reinforce what you're learning or watching me do right now so to build the right subtree we need every value after this sub list right so we can just say starting at index mid plus one going until the end of the list that's how you do it in python we're starting at mid plus one and going until the end of that sub list just like i showed in the picture and for in order we can actually do the exact same thing we want every node to the right of mid in order right from our inorder array we want every value to the right of this index mid so we can do that with mid plus one start starting at mid plus one and then going until the end of the array so now let me close this function and so this is literally all you have to do the reason it's so easy is mainly because i'm using python but you could read you could do this code without python it would probably just be a couple extra lines you might need to pass in a couple extra parameters into this build tree function basically just these indices that i'm doing you might not be able to create sub lists but you can at least create you can at least pass these indices into your functions in java and other languages so with that we have actually created our uh tree so the only thing left for us to do is return that tree so with that being said this is the final solution it's probably less code than you would have predicted but the problem is a little tricky but it's kind of enjoyable at least in my opinion so i hope that this was helpful if you enjoyed please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Construct Binary Tree from Preorder and Inorder Traversal
|
construct-binary-tree-from-preorder-and-inorder-traversal
|
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** preorder = \[-1\], inorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= preorder.length <= 3000`
* `inorder.length == preorder.length`
* `-3000 <= preorder[i], inorder[i] <= 3000`
* `preorder` and `inorder` consist of **unique** values.
* Each value of `inorder` also appears in `preorder`.
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
106
|
148 |
a very interesting problem with Donald liko it is sort linked list so basically um if we know that if we want to sort a array it would be much simple with a lot of methods such as bubble sword or merge sword and quicksort so today we're gonna apply merge sword in this case we can think this linked list as the same as the array case for the array right so how to apply the merge sort oops sort in Array right so basically for the array we would Define let's say we would have two array one and the array two and we want to merge them up but the pre-request the request for the arewa pre-request the request for the arewa pre-request the request for the arewa and array to there or sorted right so and we can merge them easily because uh let's um we can use two point let's say we have array one which is two four five seven and uh sorry we have array two which we can say five eight six three right so we could have like let's say two pointers Point into uh the start of two array and we will Define a new array we can call it new oh this is wrong we you should have a sorted array right we have uh these two arrays and um we want to merge them into a new array so first of all we have this two pointers right we have these two pointers and we want to move them so first we compare it with the two pointers at We compare these two numbers one and two right so in this case one is um less than two so we put one here and we started to move this pointer right we move this point to the next one and compare it to this two number and we can see that 2 is less than three uh so we put a 2 here and we can and we start to move this um this pointer to the pointer for array one right move to the next one let's put um more obvious column you can put like two um pointer so in this case 3 is less than four so we put three here and we continue move this move the pointer for array two and now the 4 is less than six we put four here yeah you got this mean so we continue to move this two area and two pointers and we've got of this algorithm to our linked list right because now we don't have um to sorted a linked list but we should know that the link list can be separated into two parts right and we can continue to separate it and continue to merge each of them um to uh sorted and linked list which brings to a very common um algorithm um which is recursive recursion right recursion so now what should we do so first of all we should find the minimum length of a linked list which is just uh let me put it this way and Clueless so we can separate this linked list into small part we can let's say separate this example into these two part but still these two parts are not sorted right so what we should do next we should to continue to separate them into more into a smaller part which is and say oops four and two here and now it becomes one and three now it's more clear right we can um because it's the most the smallest unit smallest uh sub array here and we can make them into our sorted list which is um oh we change your color so two should point to four and we return this linked list right and the one should point to three it's the same gray and now these two link uh link linked list is sorted now we can return to the root array which is one to two three four so that's how this algorithm would work so this is how the algorithm works so first the first uh basically we separate this um solution we do two parts first part is to separate the linked list into um break them down into smallest pieces which is a single element and we use recursion to do this part to have the smallest um to have the smallest part of summary and what we do that we should get each time we should get the middle of the linked list and that's kind of a tricky part because we let's say we want to get um here right each time and here and finally we do not have to um do this anymore we need to get the middle element so how should we do that so we can we have come up uh solution in leeco in because um number as 76 it's a easy legal problem which is to find the middle um get the middle of the linked list but now we are kind of do the different things but it's still similar we want to get the middle and we want to separate um separate the linked list into two part so it should be we get this note and this node should point to not right that's how we separate to to sub uh sub length list so yeah that's the first part um and then we should do the um sorted merge sort would be just what I said like we do we did for the array which is two um to assorted Sub sub array sub length list and we have two pointed two pointers pointing to each of them and we get a small one to um put that put the small one into the um into the new sorted array into this in this case it's a linked list so basically let's take a small example here the initialize a dummy note and the Domino would point to the smaller to smaller element which here it's one and after that the pointer will move to the next element right and we want to compare this 2 and 3 and we now see that um 2 is that less than three so we take this is the key part we take this pointer to here to point to the smaller one let me change your color to make it more obvious which we pointed to the smaller one right and uh now we start to move this smaller one the pointer right to the next one okay and we compare still we continue to compare these two and we found that three is less than four so what we do now is the same we change this pointer to point it to the smaller one correct and finally um we have this four left right because the three is has reached um reach the end of the linked list I mean this pointer has pointed to and now and in this case we have only one um assorted linked list left so the only thing we need to do is just glad the um link point to the left sub length sub list and that's how the sorted linked list become inform formed basically we want to as I said before we want um to separate main functions which is first we want to have a spill it to split the linked list to two part from The Middle and then we want a merge sort function right in here we need to sort it a list this uh two should be sorted one okay so basically we want to um first wait you should get the middle of um middle part actually in this function we want to separate both the head and the middle so which means on the left part will be on the head and we put that into the um into this brick per serve function we put the head but remember that the head has stopped uh that's in this position okay so after this split function it has the head becomes just this part just become for two part and wrong right well become the leather part which is one point two three and finally we want to put these two sorted lists into we want to return the sorted list right so this is how the recursion worked but remember we have to put our base cases in this function which is if not had or not had next we will return to sad which means if um it's not if the head is known as the input or the head only has one element we would just return the head and let's begin to implement our split function so basically the split function would be um first of all initialize the pointer and while a head and because here we're gonna use a slow and fast pointers 2.0 pointers to get the middle right so here we want to add a record previous to record the previous middle position and we want the middle mid this pointer to be the slow pointer and um had be the fast pointer which is next and because we want um we want this position here to separate the linked list that's why we need this mid proof previous pointer because if we don't have we just use the mid the middle pointer we find we finally stopped at one and that was that is not what we want right um and we're just gonna put the mid approve as to record and finally we use the mid proof to get um to separate these two to point it to the knot so that they have officially separated at this point are just gonna be removed right at this point they're just gonna be removed and finally I'm gonna return the mid the right part the final part and the head gonna just be uh this part right and finally we're gonna implement the merge sort algorithm so let's create a dummy node at first and we are put to a random number let's say just minus one and the pointer can be dummy and wow to each of these points I didn't reach to the end and we start to compare these two so if um the value of list one is less than the value of um list two um our results will point to the um smaller one okay pointed to L1 and we move L1 we don't move L2 at this point because um L2 is still gonna need to stay and compare to the next L1 because air one is the smaller one and we don't know if the next one is still smaller than L2 or not so erotic should stay same and if O2 is greater or equal than L1 we get the result linked list 0.202 and L2 starts to move next 0.202 and L2 starts to move next 0.202 and L2 starts to move next and finally um L2 as a result L is continuously moving so it can update the next node and if either of these two lists come to an end we've just stopped this Loop and whatever it left let's say if L1 has left on the pointer we're gonna point to L1 and if Note 2 has left we're just gonna point um to about two and finally we returned the Sentinel node yeah we return the result we're using the Sentinel node right so yeah that's basically how we implement this algorithm and let's see if it is work yeah right um it works and let's see so basically it's not as good as much as other solution but it's pretty clear to understand and hope you enjoy it
|
Sort List
|
sort-list
|
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
| null |
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
|
Medium
|
21,75,147,1992
|
713 |
what's up nerds welcome back to t-time what's up nerds welcome back to t-time what's up nerds welcome back to t-time with your favorite software engineer if you guys haven't already if you guys are new to the channel check me out subscribe i post record videos a few times a week i also have a slack channel where i post problems every day first discussion solved so that invite link is in the description and then today we're going over subur sub array products less than k so um there's a lot of these like sub-array sub-array sub-array problems so here's another one sub-array problems so here's another one sub-array problems so here's another one sub-array sums divisible by k then there's like summary sum equals k so you're going to notice a pattern with these problems i would also recommend doing sub-ray sum equals k if you haven't done sub-ray sum equals k if you haven't done sub-ray sum equals k if you haven't done that one first it's a little bit easier um so you're basically going to be using the same concepts you need to be able to notice these patterns so that's like the intuition behind this problem is you kind of just have to pick up the pattern already so um we typically use sliding windows in these subarray products because they're contiguous subarrays so we're sliding the window into the subarray so the description reads you are given an array of positive integer numbers so positive is pretty important um i'll explain later why count and print the number of contiguous sub arrays where the product of all the elements in the sub ray is less than k so um they just want us to return the number so we don't have to actually like store all these numbers in an array and so for example 10 is less than 100 so we would have 10 and then 10 and 5 is 50 which is less than 100 so we'd have 10 we would have 5 by itself as well so we would have to add 5 at that time and 10 and 5 and so then we'd go here so that's 50 times 2 which is 100 so it's not less than k so what we'll do is wow while it's less than so we're going to have product equals one because we need to multiply something by one we need to multiply ten by one to get ten to start off and so while we're going to execute this statement while product is greater than or equal to k we're going to how we would just we would need to get rid of 10 we're going to be using a sliding window so we're going to have a left pointer and a right pointer we want to move left one over so how would we do that we would just divide uh product by nums of i so that would basically slide the left pointer over or not numbers of eye well it would be numbs of left i guess you could use numbers of i too and we would also have to increment left so that's what's sliding it dividing it is removing it from the product uh variable and so then we would just have 10 in product and we would go again and so left is now here and we would move right as well so that's how um we adjust for it but how to how do we add incremental correctly so for example in this one we have five times two is ten times six is uh sixty so the correct amount of arrays we'd want to add is five two six uh somebody's called me and two and uh we want to add two and six as well so we'd want to add six two six and five and two and six so that's the three subarrays we want to add how do we get that we would do answer plus equals i always do that right minus left plus one um so let's go over this why this works we have right is three minus left is one plus one we get three um so that's how we get add all the correct sub pr uh sub arrays for this iteration um so basically that's how it works we're just moving the pointers in the sliding window where we need to adding the correct amount to the answer and now let's just code it out we're also going to have a base case so if uh k is less than or equal to one um since the number the numbers are always going to be greater than zero so um if it's one the minimum is one um it would be impossible for it to ever be less than one so in this case if k is less than or equal to one return we would just return zero since it's you know impossible and then we just want to we need to create our variables so let's create product equals one so like i said we want to create one we have our left pointer set it to zero and our answer so that's also zero and then we're just going to loop through i'm actually going to call this right um right left end numbs.length right plus numbs.length right plus numbs.length right plus okay so um first thing we want to do is multiply product by uh the nums of right so we're multiplying it by numbers of right because that's the one we're moving um nums of left is the one we're dividing by because it's the left side so and then we need to check to see if uh products is greater than or equal to i put almost put 100 we need to divide it by numbers of left so that's we're getting rid of the left one because we already calculated all the sub-arrays that sub-arrays that sub-arrays that it can possibly exist in we want to move the left pointer over so we're calculating all the new sub-arrays and then we're just going to add the uh right minus left plus one so this is calculating all the um new possible subarrays um the reason it works is because as you increase right the possible number of subarrays also increases so if we had a fifth number if we had 10 5 2 six three i know that's not less than 100 but let's say it is for this instance we would want to add uh three so i'm going to change the color we would want to add three um three six two and five two six three so it's basically just uh increasing by one each time um so we need the indices to calculate this so we have right and where did i have oh at five left so it is um four minus one plus one so we get four um and then we just need to return answer so hopefully that makes sense this is just a sliding window problem and then you need to do the calculations figure them out how you're going to add i think the trickiest part is this part right here being able to figure that out how to correctly add all the new number of subarrays because we're not just adding one subarray at a time we're adding all the possible permutations basically so let's submit this and so this is let's go over the runtime now so this is just a for loop um so it's of n runtime and we didn't use any data structures so just over one space complexity i believe that was the uh it's same runtime and space complexity for survey sum equals k so you should notice like patterns with these problems i'm going to do this one next today so i'm sure there's it's another sliding window problem but that's all i got for you guys i hope you guys enjoyed the video and learned something and if you did smash that like button i'll see you next video
|
Subarray Product Less Than K
|
subarray-product-less-than-k
|
Given an array of integers `nums` and an integer `k`, return _the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than_ `k`.
**Example 1:**
**Input:** nums = \[10,5,2,6\], k = 100
**Output:** 8
**Explanation:** The 8 subarrays that have product less than 100 are:
\[10\], \[5\], \[2\], \[6\], \[10, 5\], \[5, 2\], \[2, 6\], \[5, 2, 6\]
Note that \[10, 5, 2\] is not included as the product of 100 is not strictly less than k.
**Example 2:**
**Input:** nums = \[1,2,3\], k = 0
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `1 <= nums[i] <= 1000`
* `0 <= k <= 106`
|
For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k. opt is an increasing function.
|
Array,Sliding Window
|
Medium
|
152,325,560,1083,2233
|
112 |
hello everybody welcome to another video on problem solving in this video we're going to be solving a problem on lead code which is path sum so it's a relatively simple problem you can see it's tagged as easy so let's just go through the description and then we'll see how i'll be solving it so the problem says that we've been given a root of a binary tree and an integer which is target sum so we need to return true if the tree has a root to leaf path such that adding up all the values along the path we get the target sum and a leaf node is a node which has no children so if we look at this tree 7 2 13 and 1 are all leaf nodes so in this tree we have been given the target sum as 22 so we need to find a root to leave path which on adding all the nodes in the path gives us the target sum so this is one root to leave path five four eleven two going to seven would be another root two leaf path five eight thirteen is another route to leave path and five eight four one is another route path so when we add up the values in this path which is 5 plus 4 9 plus 11 20 plus 222 we get our target sum which is 22. so if we find any such path in the entire tree moving from the root to any leaf in the tree that we get our target sum we need to return true else we return false so over here we have another example 1 2 three target sum is five and the answer would be false because there are only two root leaf paths one goes one is this and one is this so this path going from one to two would result in three going from one to three would result in four so we can't reach it another uh example which has been given is one two so this example would be something like this tree without the right side of one and the target sum is zero so obviously the answer is false there's only one root to leave path which would give you the answer as three and let's just three see the constraints say that the number of nodes in the tree range from zero to five thousand their values range from minus one thousand to positive one thousand and the target sum also ranges from minus one thousand to positive one thousand so that isn't really a big concern now let's talk about the approach so what we're going to do to solve this problem is we traverse the entire tree and as we are traversing the tree we'll be keeping a track of the sum that we've got until now up till now and as soon as we reach a leaf node we check that the current sum that we have obtained till now if it is equal to our target sum if it is then we simply return true and if it is not then we return false so now coming to the code so we need to return a boolean we've been given the root and the target sum first of all let's put the default case right and after that we say let's call the function recursively has spot sum root of left with target sum and before we do that let's just do one thing let's say let's declare an integer variable let's call it in sum well in fact if you're going to keep a track of the sum then i'll be needing to pass it to other functions and to pass it to other functions i'll have to add another parameter or i can keep a global function global variable but if i am keeping a global variable then every time i get a new test case i get a new tree i need to re-initialize get a new tree i need to re-initialize get a new tree i need to re-initialize that global variable to zero but as we've been given only one function over here and i don't have a score i don't i can't add another parameter to pass to other functions so what i'm going to do is let's leave this function let's write another function of our own and in that we'll be doing all this we keep parameters for target sum and all so let's say bool check path sum and let's give it parameters like struct tree nodes star route and in sum and i'm going to store this target sum in a global variable which is let's call it target sum only and as soon as we this function is called we say target sum is equal to target sum and now let's come to our actual function let's see what we're going to do in it so again as i said the default case if not root return false and over here we can check that not check we can recursively call it check part sum and over here what we're going to do we'll call the left child and let's just do one thing we'll say sum plus equal to root of where and what we do over here we pass sum as the parameter and after we've called this let's also call check path sum root of right comma sum and after this let's just now let's just do one thing and if we put an if condition and let's check if our node current node has a left child or not if root of left and root of right and i'm going to put if not root of left and not root of right so if we don't have a root of left or a root of right then what we do i'll just move the statement below so if we don't have a left child or a right child as well then what we do we check if our sum is equal to target sum yeah i miss an underscore then we return true because we have got such a scenario where our current sum our current node is a leaf node and the path from the root till the leaf node has given us the target sum so we return true and if this condition is not true then we return false now another thing that we need to do is we need to put if conditions over here because if our path below this node or let's consider we are at five so five gives a call to four gives a call to eleven gives a call to two now two will return true but eleven should also return true to four 4 should return to true to 5 and 5 should return true to the caller so our returning true is dependent upon what answer we get from our recursive calls so if check path sum return true then i from this function will also return true similarly if check path sum of root right return true then i will also return true from this current node so we have checked put the base condition we have recursively called the right child and the left child and we have checked if our current child of if our current node doesn't have any child any children then it is a leaf node and if it is a leaf node and the sum is equal to the target some will return true else we return false now all i need to do is just give a call to this function which says check path sum root and we initial sum 0 and we simply return whatever this function returns so this should work about right let's go ahead and test it works fine for the this test case let's go ahead and submit it and it has worked fine for all test cases with 57 better run time and 57 better memory usage so there you have it that's the solution for the parts some problem and i hope you liked the video do make sure to subscribe if you're new to the channel
|
Path Sum
|
path-sum
|
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22
**Output:** true
**Explanation:** The root-to-leaf path with the target sum is shown.
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** false
**Explanation:** There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
**Example 3:**
**Input:** root = \[\], targetSum = 0
**Output:** false
**Explanation:** Since the tree is empty, there are no root-to-leaf paths.
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
113,124,129,437,666
|
779 |
Hello everyone welcome, my name is Himanshu, you are watching the lecture, I will give the D series review, so let's start You must have seen in the thumbnail, what is the question, so see friend, once you define the question, input. What will be given to you? In the input you will be given two numbers N and K. Okay, N is showing what is roll number and K means man, you take column man, it means okay. Now listen, what do you have to output, first take the condition, how is that? Grammar is written, zero has to be replaced with zero van, ok now man lo n = you have to form third row ok now man lo n = you have to form third row ok now man lo n = you have to form third row then how to replace zero with zero van, this van with 108, this zero with zero van. Have you understood what to return? You have to return the cage symbol by row. Let's suppose n = 4 given and k = 5 so 12345 so you have to return van. Okay, you have to output this. If you have to output this then it will be zero or van. So let's go. Friend, I will find the question link in the description. Once you want to attempt the code, do it once. Friend, let's see how to code it. What is coming in my mind, I just told you that the current row is on the previous row. It depends, so what I will do is I will say that I create a string as a previous, I am going to put zero in it, which means it is defining the first row, okay and I put one thing that if n = 1 then return it. that if n = 1 then return it. that if n = 1 then return it. Previous of zero, what is it doing, so there is a character in the previous zero, today's value will be returned but I have to return, so I made minus zero, okay, I am going to do it, I am going to put a loop from i = 2 to i. <= Okay till N, I will create a string current in it, I will store the current, it will store the current condition, it will continue like this, now in which am I going to do the driver, now I am going to do the driver, the logic in my previous is simple, friend if. Element equal tu zero tu equal tu zero then what to do then current plus equal tu zero what to replace zero with van and or van will be there I will make the previous equal to the current ok what will I do return the previous of - 1 - 0 If the wait is right to return then it is ready, see what has gone, our beloved everyone's beloved Tilia, why has the time limit gone? Now let's discuss it, listen to me once about its time complexity. Tell me friend, the previous value can be this much, now listen carefully, I am taking the last value and getting it done 30 - 1 means 30 - 1 means it has become 29, then what will be the time complexity, brother, this is very high time complexity, meaning if you are like that. If we write also then soak off n * meaning if you are like that. If we write also then soak off n * meaning if you are like that. If we write also then soak off n * 2 is friend, have you understood why towards optimize approach because now we have squeezed everything out of this question so now let's see what we can do friend, in this we saw that A was gone in it TL now let's see what If we can then we write again what is given in the input N and K. Once we see what becomes row van means N is ok what will happen in row four zero to zero van to van 108 looks something like this ok This first second third, you analyze only till here, once, meaning if you see is there and there will be too, friend, if you think carefully, then we are replacing zero with zero van, so this zero is from zero, we are not replacing van with van. If you are replacing it with 10, then it is correct that these vans are the same. Now let's talk further about fours onwards. So if you look here, before looking at this, look here what is happening by replacing zero with zero van. This means I's done to zero, if I take A = 0, then what is this written? We are = 0, then what is this written? We are = 0, then what is this written? We are replacing A with A and A's complement. Similarly, if this is B, then it is B and B's complement, so it means this is complete. What will happen, this will be its complete complement, see whether it is Zero Van, what will be the complement of Van Zero, 10 dangerous observation skills have been acquired, and it is given in the question itself that the next row will depend on the previous row. Got it, got it. After some observation skills became good, I understood that there is a story from here to here and from here to here there is a different story and whenever two stories play out, it means that this story has played out. Now friend, I asked a question. Power of Look carefully brother, till this point, what actually happens till this point, which index is this? Now I told you how many entries are coming, if this is true, then how much is this increase, power of 2, minus, how much is this increase. Hai tu ki power 2 - 1 = 2 how much is this increase. Hai tu ki power 2 - 1 = 2 how much is this increase. Hai tu ki power 2 - 1 = 2 ki power 4 - 1 = 2p power 3 = 8 4 - 1 = 2p power 3 = 8 4 - 1 = 2p power 3 = 8 And what is this is middle so give it the name of mid done means if your here on here if your ke < Okay, previous row is over. It's done, now let's go directly towards its code implementation. It's fun today. What's going to happen? First of all, okay, I just showed you the completion, so now what's left, I've written a question in it, I've written this, what's left of our beloved country? And if he has given something ridiculous, I mean, he has given Foot Pathan which is not valid, then do it here, there is no one, submit, it is accepted, okay, did you understand? Is the invalid base that invalid test case kept? That's it, I understand, let's analyze it once, friend, let's analyze it, see friend, how do we write the logic, let's write three things, the base case, yours is less and trust is fine, this is what you want. Yours is less, I understood completely, first now tell me by commenting, I am not telling now what is time complexity and space complexity, meaning tell me what is the time complexity of this code, if you are not able to understand the power of x why am I am here because it is a similar question, it is exactly like the question, it has been explained well in it is exactly like that, we had applied our observation skills in that also, we will apply our observation skills in this too, it is absolutely from exact, just made N and K in it. Obviously a little power is coming out, so this thing was different, it is a little different but it is a similar question, so see it and comment, I will give the answer in the comments. Okay, so come on friend, see you in the next video. Give sesame with new and good questions Happy God [Praise] [Praise] [Praise]
|
K-th Symbol in Grammar
|
max-chunks-to-make-sorted-ii
|
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`.
* For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` row is `0110`.
Given two integer `n` and `k`, return the `kth` (**1-indexed**) symbol in the `nth` row of a table of `n` rows.
**Example 1:**
**Input:** n = 1, k = 1
**Output:** 0
**Explanation:** row 1: 0
**Example 2:**
**Input:** n = 2, k = 1
**Output:** 0
**Explanation:**
row 1: 0
row 2: 01
**Example 3:**
**Input:** n = 2, k = 2
**Output:** 1
**Explanation:**
row 1: 0
row 2: 01
**Constraints:**
* `1 <= n <= 30`
* `1 <= k <= 2n - 1`
|
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
|
Array,Stack,Greedy,Sorting,Monotonic Stack
|
Hard
|
780
|
356 |
hey everybody this is Larry this is day 15 of the February uh 20. hit the like button hit the Subscribe button drop me a Discord let me know what you think about today I'm doing a next year premium problem just to charge myself in it also just you know get my money's worth um I did get a request about 356 so let me take a look uh it is a premium problem and I haven't done it so let's go for it okay so today's bonus Farm is 356 line reflection all right let's give an N points in a 2d Point fine if there's a line parallel to the y-axis line parallel to the y-axis line parallel to the y-axis parallel to y-axis that reflects the parallel to y-axis that reflects the parallel to y-axis that reflects the points the given points symmetrically in other words enter where there's a line which have to reflect on over the given line which runs the y-axis the vertical line which runs the y-axis the vertical line which runs the y-axis the vertical one right uh I always XYZ confuses me but anyway uh The Original Point set is the same as the reflector know that they can be repeated points okay we can choose wait what parallel to the y-axis so y-axis is to parallel to the y-axis so y-axis is to parallel to the y-axis so y-axis is to which one is the y-axis x-axis y-axis which one is the y-axis x-axis y-axis which one is the y-axis x-axis y-axis I'm so confused now because the line x equals zero is oh no the line x equals zero is vertical okay I am it's being done okay um in this case it will be a diagonal okay um yeah I was gonna say so uh n is ten to the fourth let's keep that in mind uh let me also just type it but uh so the very naive problem is that between any two set of points um there is a vertical line right and then between any two sets of points there's a vertical line right um so with that you can check whether that line is a good line of a good refraction line um by looking at everything and see if they match right so that's going to be n square or n cubed depending on how you do it um I think the other way of thinking about it is that if a reflection exists then it has to be the median right um I guess it could be odd do you count itself know that they can be repeated points um yeah I mean but I think in either case it should be the median right uh and this could be the arithmetic median or the actual you know median right um under on the x-axis right on the x-axis right on the x-axis right um and the reason is I mean to be honest I think to me that is just intuition I'm trying to and I think you could probably prove it if you're very much stricter I mean I think the proof is just that um you could prove that there are no two lines right but yeah there can be two lines because um they're not two lines because that just doesn't make sense I don't know how to do this geometry proofs to be honest uh but I think median is probably what you're looking for because if there has to be one line and there can only be at most one line of reflection um at least with respect to vertical lines because um yeah because if you do like maybe other axes there could be more um and in that case it should be just a median so yeah so we can calculate the median and then we just look at it again right so basically we have you know and here I don't know if I could do this but uh I'm just gonna put them in a set I and I say that I don't know if we can do this only because I don't know how they expect us to treat repeated points exactly well let me phrase this the original um that we Flex All Points over the given line the original points are exactly the same so that means that it has to match up like if the two on the left has to be two on the right is that right we could test that actually so like for example if we do one more then in theory that should return true if uh it'll return Force if they need to be matched up precisely so we'll see what the so this returns true which is very awkward the way they phrase it right The Original Point set hmm it's a little bit it's a really poor phrasing I think or I mean maybe like you can make sense of it but there's a lot of guessing um and like a little bit a lot of impositions saying right anyway um and then maybe I you know we do something like uh access and then X is that X and then we can just do the median um and you could do this in linear time of median finding of course um but I am just lazy so let's just say you know um yeah if length of x s is the code to uh if this is even that's be at least one point right okay uh if this is even then it's just excess of um I guess this is n let me think about this if this is even then we want for example it's two elements then we want zero and one right so it's this and this um over two right and the line doesn't have to be on the uh on an integer so okay two three um yeah okay right and I know that I have to divide this by two but I think what I rather do is actually times everything by two so that we don't have to either y doesn't matter yeah okay that's the right matter is the white the one that matters I mean I'm confusing my x's and y's uh well the Y's don't matter because it's just a height right as long as they match yeah oh yeah and then now I can do divided by two because I multiply by two anyway okay um and then now we just have to look at it again so maybe I do something like uh reflected side whatever right um what do we do uh reflected at so we have X Y we want to reflect it over the median so man this part I always messed up so if you have X and you have median so it's x minus medium Mian is the Delta and then okay let's just write it out then right down two is equal to x minus median and then x minus um Delta times two is the reflection right so um so this is the new X right and then now you can put it again except for times two because just for matching uh return original as you go to reflected oops hopefully this is right um it's actually support maybe today's okay so the original is negative two one and then om what is the median that I put here minion should be zero oh hmm I see that's actually a good Edge case um my median is wrong because my median is one because we want the median of stuff that is deduped so okay that's it though weird but okay fine um I mean at least it's not a little weird but it makes my album feels a little bit weird uh to be honest um but this is why we test cases um As She Goes okay something like that right and then now it's not n anymore because of the D dupe uh um and two I don't know okay so that looks a little bit better uh am I good enough to yell those Summit let's YOLO Summit oh no expected true that's what I thought I was testing for didn't I test this well I mean I didn't I could I didn't test this but I thought I was thinking about it that's why we have this multiple times two thing right so then okay the median is at one it's between zero two and then so two goes to add Times by two incorrectly I don't know because points is always weird which point is to original things so then now you have the thing and then now you stretch it after getting the doubt oh because the median is not dotted by two uh a lot of silly mistakes okay fine um so okay hmm so one is right and then two oh I see um this is times two as well basically a lot of uh because I created this new uh equivalent Dimension and it's just uh maybe I need to I think what I should have done is just convert everything in the original points by times two then I wouldn't have to think about it but I think I was trying to be like yeah let's keep it slightly cleaner and instead it was not because what I should have done is something like this and then now I don't have to do any of this uh and that part is still yucky though but and then I don't have to worry about any of this thing right gonna submit again yeah but I was just I don't know I was just trying to get away with it um yeah so I mean I am sorting so this is going to be analog n but if you use the median uh if you use a linear median finding thing um you know obviously then this is going to be linear because I think this is the choke point um or this is the dominating function in terms of complexity right everything else is all of one uh you have sets and this is our sets so yeah I mean and the refractions as such everything is all of one and which combines to O of n o of N and yeah no event so it gets dominated by this I'm too lazy to kind of implement the media or the linear median finding but assuming that you can then this is going to be of n times in total and also in space it's just all of n space just because we use a lot of sets in a lot of places but um don't know I think you need a set in any case for a quick look up so I don't think that's um I think linear spaces uh at least the lower bound of what I'm doing in terms of just complexity um yeah that's all I have for today that's why I have this problem let me know what you think stay good stay healthy to good mental health I'll see y'all later and take care bye
|
Line Reflection
|
line-reflection
|
Given `n` points on a 2D plane, find if there is such a line parallel to the y-axis that reflects the given points symmetrically.
In other words, answer whether or not if there exists a line that after reflecting all points over the given line, the original points' set is the same as the reflected ones.
**Note** that there can be repeated points.
**Example 1:**
**Input:** points = \[\[1,1\],\[-1,1\]\]
**Output:** true
**Explanation:** We can choose the line x = 0.
**Example 2:**
**Input:** points = \[\[1,1\],\[-1,-1\]\]
**Output:** false
**Explanation:** We can't choose a line.
**Constraints:**
* `n == points.length`
* `1 <= n <= 104`
* `-108 <= points[i][j] <= 108`
**Follow up:** Could you do better than `O(n2)`?
|
Find the smallest and largest x-value for all points. If there is a line then it should be at y = (minX + maxX) / 2. For each point, make sure that it has a reflected point in the opposite side.
|
Array,Hash Table,Math
|
Medium
|
149,447
|
216 |
Hello Guys Today They Are Going Prince Combination Sentry Problem Swiping This Is The Second Last Problem His Name Not The Second Like This Is The Thirteenth Problem In Our Back Tracking List Withdrawal Episode 212 Problems And Discrimination Problem Is 210 Commission Problem Is Singh Find All Wealth Combinations of Numbers Date Sum Up to In This Regard for Living Conditions and Proof Mainly Number 0 9 Views and Page Number Is Used at Most Once OK End Return List of All Possible Valid Combinations Changed List Note Ghanshyam Combination Price and Nomination Been Written End Water should be provided with you only numbers and number 129 and go to get only supports to use a digit 21 that and day VHP and means how many days were going to airtel money were able to do a create that date combination switch print Actually Say Emphasis First Things First Five One Two Three And Digits Are 00 Maximum That We Can Make You Feel Like It Will Share Profits For Numbers Will In Turn Will Lead To Examine Your Life When They Are Riched Subscribe Our Merit List Coins And Note It Is Not K Did Not The Candidate Answer And Effective That Is The Candidate Answer To Hair Vacancy Light I Am Imposing Samay Constantine And Most Problem Solved Hair Conicles In First Scientific Generate All Assets Of Size K And Din Ravi Pick Dwoj K Size Combinations In Which Some Of All Elements Which Can Render True Service Tax Credit Veer Waste Create Unrest Times In A New Railway Route And Mandalgarh College Function Solve Ki Cricketer Hain Play List The Practice Of MP4 Main Tujhe To Candidate Yo Arrest Let's Call Solve 600 Dual What Like Or Somvansh Will start from chronic and candidate and return yes sir now let's implement this award function on jhal me interest rate ki print k ko turn total hua tha national candidate's show is one of the violative airways check life i am just total e want to tail effect Candidate dot size equal to two K Pandey on total record 10 Gillard how to find answer of question that if global lizard return e want heat was not the case in which one like only then start have excelled do it is better than life Image Simply Need to return to that if will skip and element at index start element and go to star plus one that their end to total land candidate and but light show will include Uble Titu and candidate to start is skeleton solapur to start ashwagandha ke to total - Start And Candidate And Bold to total - Start And Candidate And Bold to total - Start And Candidate And Bold Content A Remote And Art's Size Gain Obscene Ha Thus So Let's From This Is Or Small Working Fine Let's Check Hum Samagra Input's Quantity 3 Jhala's Two Three And Think What Do You Know Jhala's Ki Swarna World Title need oo jhal achhi teacher updated on ko sanspri jaaye this video and concept the firm aur video ko like that do subscribe my channel thank you for watching
|
Combination Sum III
|
combination-sum-iii
|
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true:
* Only numbers `1` through `9` are used.
* Each number is used **at most once**.
Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order.
**Example 1:**
**Input:** k = 3, n = 7
**Output:** \[\[1,2,4\]\]
**Explanation:**
1 + 2 + 4 = 7
There are no other valid combinations.
**Example 2:**
**Input:** k = 3, n = 9
**Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\]
**Explanation:**
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.
**Example 3:**
**Input:** k = 4, n = 1
**Output:** \[\]
**Explanation:** There are no valid combinations.
Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.
**Constraints:**
* `2 <= k <= 9`
* `1 <= n <= 60`
| null |
Array,Backtracking
|
Medium
|
39
|
1,329 |
Hello welcome to you new video and today we are going to discuss the challenge in this video so today's challenge is so we have given a matrix like this matrix has been given to me so what will become the diagonals this one diagonal one This diagonal, now look at this triangle, now if we sort this diagonal, it is automatically sorted, so it will be made in this, if we sort this diagonal, it will be made at the top, you will come down, look, it is gone and we will sort it. 1 2 3 And if we solve it like this, then one is here, you are here, three is here, this is automatically sorted, so my matrix which was earlier like this, has become like this, okay, so this is the diagonal line of sales, okay read this and the rest of the questions. I explained what we have to return like we see in every question, vector and vector end means we have to return our matrix, okay then end return D result, we see what should be my approach, okay so One observation, if we see, these are the diagonal elements, if we look at three tu van, three's zero pe tu kis pe hai van kama van pe and van kis pe 2 pe ok zero kama zero van kama 1 and 2 something You are noticing the pattern that their difference is what is their difference is from that so what will we do with the difference of this what will we do in which our key will be the difference and value of these elements which will be the index which But suppose if 00 is three then it will go to 1 value and corresponding 00 means 0 - 0 will go to zero then 1 - 1 will go to 0 and you will go 00 means 0 - 0 will go to zero then 1 - 1 will go to 0 and you will go 00 means 0 - 0 will go to zero then 1 - 1 will go to 0 and you will go to 0 and then your 2 will go to van tha to tu kama tu a will go to your. Right in the van So now this is not in sorted order This is not in sorted order So how will I sort it 123 Okay so what will be its time complexity Leave the time complexity How do I solve this Either by sorting or So I can store the hit, either I can make it short, or I can store it in the hit, I have two options, so what will I do, I will make it one min only, right, so you understand what I am trying to say, right? I have created a and created a value, okay, the value is stored in it like this, I have also told in my previous video that the value is in the foot, so what is the difference of the element here and what is your value, it will be stored in the map. Okay, now this That's enough of me, what will I do now, I will keep popping my elements one by one with min hit, if I come to this index, then I will go to this index, whatever value I have will be stored in it, I will keep popping, pop. I will keep doing this and give my opinion, what tricks will I do, I will return, okay so this is the basic approach of mine, okay, what will be the space complexity in this, Big Boss M * M because Big Boss M * M because Big Boss M * M because M is here if I have the number of roses and N is from the column. So what will happen, my space complexity will be this and time complexity, now we will see when we code, okay when we do the court, then we will see what our time complexity should be, so relax, watch, read and you guys try to solve it, okay then we People will do their court and we will see in the code what approach should I keep, so friend, while doing the code, I had said that write the basic approach on pen paper and then put it, okay, basically what we are doing in the court. They are the ones who write and we see, first of all, what will we do, first of all, we will make the daily, okay, so what will be the daily, matrix of zero dot size, okay, now I will take it as a matrix, what will happen here because it is a matrix. If yes, then daily columns will have to be defined. Matrix dot size will be ok. This column will be my matrix of zero dot size. Here I have defined daily and columns. Right, after that what do I have to do. How is it made here now? What is the difference of element of pay, element difference, earn, greater rent difference, so friend, you must know this much code, I have not written any rocket related code, rocket science one is ok, now let's see what will happen inside it. What will I do, understand that I did it right, I did not do anything, it is okay, I did not do anything, I made this my difference named Hashmat, in this I - K means suppose, 3 in this I - K means suppose, 3 in this I - K means suppose, 3 is 0, so means difference of zero, means difference in the map. Difference of zeros in Hass Map Corresponding of Zeros in Hass Map I - U Difference of I - I - U Difference of I - I - U Difference of I - Difference of Zero So what has become this difference of zero dot some matrix of zero earn zero ok first of all 0 this will come from here only If al comes from then I am saying that difference of zero is the difference in difference value, I am the correspondence of the zero, so store three values, okay, so this has become mine, okay, what am I doing with this? First you come to zero, earn zero, then the difference of zero and its corresponding value, what is its corresponding value, three, then you come to 0, 2, its corresponding value - you come to 0, 2, its corresponding value - you come to 0, 2, its corresponding value - 2, and what is its value, one, then by doing this, you keep making hashmat. Yes, this is a clear view, so code it in such a way that you will never need to keep it. Now what will I do, brother, now I will iterate again on my tricks, I will iterate again on my matrix. Okay, so I can copy paste this. Okay. Now I will tell it again on my matrix, what else will I do, which of the minimum is the top element of the number, which is the top element of my hit, exactly what became of me, I became the matrix equals, you are the difference, as if this is mine only. Okay it is done, see how my mini hip will be made, now my man will be made as if sponding towards zero, come one minute Zero do n't know what is happening It will become It will become It will become 123 and this will also become 123 One each element one -One element, I am just One each element one -One element, I am just One each element one -One element, I am just doing the same, dot talk difference of matrix of ease, second line, third line and fourth line, I will just make four lines of my matrix, so score and I hope, let's fix it all and then submit it. The time complexity of this code is The time complexity of this code will be How is the time complexity, you tell me in the comment section, okay that means the preparation must be going very well and we will meet in the next video. Till then keep reading all the very best
|
Sort the Matrix Diagonally
|
minimum-cost-to-move-chips-to-the-same-position
|
A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `mat[3][1]`, and `mat[4][2]`.
Given an `m x n` matrix `mat` of integers, sort each **matrix diagonal** in ascending order and return _the resulting matrix_.
**Example 1:**
**Input:** mat = \[\[3,3,1,1\],\[2,2,1,2\],\[1,1,1,2\]\]
**Output:** \[\[1,1,1,1\],\[1,2,2,2\],\[1,2,3,3\]\]
**Example 2:**
**Input:** mat = \[\[11,25,66,1,69,7\],\[23,55,17,45,15,52\],\[75,31,36,44,58,8\],\[22,27,33,25,68,4\],\[84,28,14,11,5,50\]\]
**Output:** \[\[5,17,4,1,52,7\],\[11,11,25,45,8,69\],\[14,23,25,44,58,15\],\[22,27,31,36,50,66\],\[84,28,75,33,55,68\]\]
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `1 <= mat[i][j] <= 100`
|
The first move keeps the parity of the element as it is. The second move changes the parity of the element. Since the first move is free, if all the numbers have the same parity, the answer would be zero. Find the minimum cost to make all the numbers have the same parity.
|
Array,Math,Greedy
|
Easy
|
1895
|
1,614 |
hi everybody my name is alisa and in this video i want to show you my solution and explain uh how i solved little problem maximum nest in depth of the parentheses honestly this specific problem took me way more time to understand what exactly the problem about than to solve it because the solution is pretty simple and fast and quick to understand than the problem itself so i'm not going to read too much the problem i will but just a part of it and i will just explain what the problem is about and what exactly we need to solve and then we just dive right into writing the pseudocode and the code itself so a string is a valid parenthesis string that we call vps if it meets one of the following if the string is empty or a single character that not equal to parenthesis basically left or right parenthesis it can be written as a b or a or it can be written as a where a is a vps sorry that's my dog he's always angry mika why are you angry so in this problem basically what we need to find the deepest string inside in this sort of the deepest string inside the parenthesis and we need to find how deep is it so here we have an example this is our string and we just need to start and count the parenthesis so let's just start and count them as it is so one two three four here we have eight this is a string and let's count the right side one two three so what do you think is the deepest uh parenthesis here how much parenthesis we need to count until we go to the deepest string in this specific example it will be three and i will explain why first of all as they said here basically um the string that we count is a single character it can be double character couple characters uh or even an empty string inside parenthesis that we have basically the left and the right parenthesis around them outside so here it doesn't count as parentheses two and three it doesn't count as parenthesis because they like by themselves alone hanging out outside they're not connected to the deepest like to the parenthesis of this specific string which is eight so if we count only the parenthesis only the depth it will be one two and three because this one we just don't count them and from other side i also need to see if they're close because i cannot just i cannot only open the parenthesis i need to also close them so we open one two three we open three of the parentheses and then we need to check if we actually close them one two and three so the deepest string here in the parenthesis will be three and an explanation they also write down that digit 8 is inside of three nested parentheses in the string so it doesn't matter what kind of uh test case they will give us all we need to do and this is very simple we just need to count the parentheses we need to see if we open the parenthesis and if we close them if it was open at close and closed like here with two and three so we don't count them that's all and this is very simple and let's start and write our pseudo code so the first thing i want to do i want to go through the string which my string is s i want to go through the string in the string i want to count the parenthesis all the parentheses i prefer to write just par but so i want to count all the parentheses in order to count them i will create a variable i will call her the variable count or whatever count sounds a good name i want to create a new variable to count the parenthesis and i will one and i want to create another variable that i will call her maximum number and i will explain just in a second why do i need this and count together ah red again i'll create another variable for maximum number so pretty simple we have count variable we have maximum number variable we want to go through the string and we want to count all the parentheses now why do we need maximum number if we already have count maximum number we need in case that we okay let's go like this we have the count right so we start to count the open like the left side of the parenthesis so let's start count one two three four i count only the left side right but when i'm counting i also want to check if i actually close the parentheses so when i'm going to the string i will check if i open the parenthesis and if i close them so if i start counting i will start one and two and then here i close the parenthesis so count will be minus one so it will come back to one why do i need the maximum number because if i keep going like this plus and minus because we open and we close the parenthesis and we have different test cases i want to check all the time if count is greater than maximum number if in any specific point the count will be greater than will be bigger than maximum number so i will change the maximum number to count and if it's not it will stay the way it is sounds simple and the code is pretty simple so let's just write it down let me just clean it up and let's just go to the pseudocode i want to go through the string in order to go through the string we do it with for loop so for i in string second thing i want to count all of the parentheses in order to count them i want to create a new variable to count the parenthesis so let's call the variable count and it will equal to zero for now and we want to create another variable and we call her maximum number and it will equal to zero also only for now so when i'm going through the string and this is the part when we start to count i want to check if i equals to we open the parenthesis if it equals to the left side like to open the parenthesis then what we do um if it if i equals to opening the parenthesis we add to the count one so we always increase the count if i equals to we're closing the parenthesis so the count will go minus one because we don't count the open parenthesis anymore because we close them right also we have the maximum number so the maximum number we always need to check if maximum number is less than count then maximum number will be count and at the end we want to return the maximum number return maximum number and actually i don't need this space here so let's go through the code once again we have our string which is our test case we created two variables count and maximum number we're going through the string and we check if we open the parenthesis so we increase the count by one if the maximum number is less than count so the maximum number will equal to count so if we started to count here one two three four and the count was four the maximum number will become four so it doesn't matter if after that i uh decrease the count by one by two or by three the maximum number will still stay four and then at the end i'm returning the maximum number so let's try and run our code see if it works and already here we have an error and let's see why if maximum number less than count invalid syntax y is the invalid syntax yeah i forgot the syntax isn't valid and what else let's see maximum number equals to count yes oh gosh why we have so many syntax problems yeah i forgot here too wow what's up with me okay it looks like it works let's try and submit it and see if we pass all of the test cases and it looks like we are so guys i hope you enjoyed this video if you have any questions please write them down and also you know what write down what do you think is the complexity of this algorithm so have a nice day bye
|
Maximum Nesting Depth of the Parentheses
|
maximum-nesting-depth-of-the-parentheses
|
A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following:
* It is an empty string `" "`, or a single character not equal to `"( "` or `") "`,
* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or
* It can be written as `(A)`, where `A` is a **VPS**.
We can similarly define the **nesting depth** `depth(S)` of any VPS `S` as follows:
* `depth( " ") = 0`
* `depth(C) = 0`, where `C` is a string with a single character not equal to `"( "` or `") "`.
* `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are **VPS**'s.
* `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a **VPS**.
For example, `" "`, `"()() "`, and `"()(()()) "` are **VPS**'s (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not **VPS**'s.
Given a **VPS** represented as string `s`, return _the **nesting depth** of_ `s`.
**Example 1:**
**Input:** s = "(1+(2\*3)+((8)/4))+1 "
**Output:** 3
**Explanation:** Digit 8 is inside of 3 nested parentheses in the string.
**Example 2:**
**Input:** s = "(1)+((2))+(((3))) "
**Output:** 3
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists of digits `0-9` and characters `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`.
* It is guaranteed that parentheses expression `s` is a **VPS**.
| null | null |
Easy
| null |
496 |
Jhal Hello Everyone Welcome To Coding Cut To Edison Electronic Problem Vacancy Abhi Problem Hai No List Greater Element That One Should First Planning Department Will Give U 2017 Element For Example For One And Two Se 0.5 1342 Se 0.5 1342 Se 0.5 1342 Nine Percent Second One Is Most Termed Hey To ki and dialects of present ki notification present in odi are not to where is element play list aur hai ka naam status go to the next element ki ke president element is ajwain na vacancy hai the place par was a great To see this place for all elements of elementary middle that super raw one and answer will be option not media group Planets Element Next Remedy J2 111 to see this place for all elements of elementary middle that is a great help to find this place but after This Place for Elements Loop Saunf 125 End Elements of Twitter - To-Do List - 1313 Problem Vidron Its Respective Governments for Effective To-Do List Play Karo Ka Effective To-Do List Play Karo Ka Effective To-Do List Play Karo Ka Naam Limited Another Example Elementary Mid Ki Sapoch 3 Jhaal Dheere-2 Jhaal Dheere-2 Jhaal Dheere-2 Apne Mitra Side Six End Nitrate 121 in 5 is one so very first elements for over two years of very attractive place for elements of this element according to this place where to find any next greater element sequence I have a reminder to 65 K for this loot from fiber Greater Noida Greater element than this is miding 400 points 6 hai not only etc. Next element Nitish Kumar Subscribe Share Like Share and Comment for one is 303 hua tha Next film in this to point to that is question is 2025 Angry Birds print only for rent in that city Jaisalmer Rajasthan A second year for free distribution ceremony where to like share and second elected s president who hair images for fennel free will return for switch to return to 6000 members' problem is near to iterate 151 way members' problem is near to iterate 151 way members' problem is near to iterate 151 way phase among them is the problem of jhuj and strong on Thursday Simple hai ko 108 will admit one step in one intake tag ki hanuman dictionary app 21 2010 everyone is most top head toe 100 will not find answer from 20th why not initially and Tuesday 20th 108 also unit rate from heaven from 250 The element system will entertain entertainment and the water element plane which has stag years of medicinal value with upcoming cars and join the elements present in the upcoming cars with that boat in middle east Delhi by Naveen aka Dinesh Singh Sr. Resident Evil Elements Which Destroy This Element Appointment Element Which Nursing Assistant's Reality Show Will Introduce Element In Place Newly Created 2G Net Style Images For Not Taking Increase Screen Printing Mistake Recent Upcoming Element Which To Respond Will Be Conducted On That Now Next Elements Select This 200 also chair and elements present in this track pittu it's due to it's true that they will celebrate the adnan sami's sentence that a prohibition upcoming element witch se name a message text note mtn merger inches increase elementary education must have a prayer for elements year it's True suveer pandey element's width is so that the anti smart video will be apprentice a new there next element which S5 that now e can see will develop this 600 places in this element's naav servi half limits ko is 180 in these dictionary only one e Will Search For Super Gamble Pfizer Servicing Research In Dictionary Pimples Internet Share For This Present For Performance Will Be C Elements For Next Remedy Is So Please Correct Bigg Boss-7 Sapna Let's Check So Please Correct Bigg Boss-7 Sapna Let's Check So Please Correct Bigg Boss-7 Sapna Let's Check And Daily Saint Witch One Superman Him On Loud Life Spending Working Photo A Photo is a senior position disgrace to elementary servi end subscribe 923 super cars servi subscribe to a 97 we getting hair diwali busy hua tha na vitiligo inch another 17th dictionary se emphasis present facts not present when will return - 4a return - 4a return - 4a 110 days logic latest Right toe implement this number dish year only and lineage greece free live web series pairs and three grade 4 6 3 4 grade c and grade 2nd appointed robbers check the president of element at index medical store se were latest also experiment warrior a solid As a design award function the Indian dare check that which will take to list position of one and number two main itni gym dushman hai na a ki main to take one list type that Hanuman Dictionary app that nobody would have to eat in the least two Here replying district is and vin us to na ho ka sanchay first element i stags in this will be up and tagged that you and value ka naam that it was money's very first suppose for example ko medium to is having value and here Sappoch one to 12345 warden naveen udhyaksh element witch can see what does apne mitra medicine twist a news channel ki value present in the stags in this element district se hindi upcoming element software rathore logic hai to wheel chair hai wahein the minister is not empty end At the same time bf 's value appeared in kameez but this is common in this gallery or take w means strike minus one is loop is the state from - 1m state from - 1m state from - 1m ki policy very first top menu hai here it is luddi upcoming delhi which is being loot tip in it's true 250 day old element from distant stagnant water due to which my hotel bill is also a problem and in my dictionary app that is inverted that dictionary or easy home remedies that they will be coming late on that thing and tell me brother done at last When all elements and where to return to a mischievous print hair ajay singh and dictionary for checking on that and also lead to return real agency return and journalist time is loot in britain are one which is for 21st in name suman hai that nine Inch B Hai Na Par Is VPN That Person To Go For A Who Is Chief In Every One Vihar To Check In This There Are To Nagaur To Where Already Said Singh And Dictionary Super Dishes Dictionary British Resident Evil Returns - Na Returns - Na Returns - Na Hai So also the number one newly appointed dictionary app is a soft glass window Soil-rooted is a soft glass window Soil-rooted is a soft glass window Soil-rooted All India King's Time Dictionary Name Withdrawal Date Value Present President - President - President - Not End Power and Pradeep and Luvdeep Celebrate Produce Everyone Passenger Service Result List My tab last year 2nd stage and answer is prompt vegetables den the latest year permit and restaurant in the heaven's having value and 4120 the initiate a the inherent went into equal to is dynasty three is and in all just to that boat 's latest hindi songs in To 's latest hindi songs in To 's latest hindi songs in To check passing a variable in there environment in do that CBSE is neither X nor West Indies that sex net mixing song is nor cancer filled super before you can see the deposition appointment which has any vacancy nikli elements present and to take medicine for appointed - 151 - 151 The take medicine for appointed - 151 - 151 The take medicine for appointed - 151 - 151 The Power's Will Be Inheritance Test 3 Why Didn't Regency One Million Is That Garlic Spent Working Fine The Same S For To You Can See Is Tuesday January 29 Near Elements Present Distic President - 2 President - 2 President - 2 Loot Name So Comment Is Out And Take for example a ki distic 3 and he divine 6 ki in five sequence year for 2106 ki and for free in return for oo a second year here four initial point service one servi 3.27 servi copy paste what happened to another country To cure cancer it is working fine but the committee is taking a second year its working side effect feel that this Video plz subscribe Channel thanks for home
|
Next Greater Element I
|
next-greater-element-i
|
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array.
You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`.
For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`.
Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._
**Example 1:**
**Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\]
**Output:** \[-1,3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3.
- 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
**Example 2:**
**Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\]
**Output:** \[3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3.
- 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1.
**Constraints:**
* `1 <= nums1.length <= nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 104`
* All integers in `nums1` and `nums2` are **unique**.
* All the integers of `nums1` also appear in `nums2`.
**Follow up:** Could you find an `O(nums1.length + nums2.length)` solution?
| null |
Array,Hash Table,Stack,Monotonic Stack
|
Easy
|
503,556,739,2227
|
1,984 |
hello everyone in this video we will solve read code problem number 1984 that is minimum difference between highest and lowest of k scores so let's read the problem statement first you are given a zero index array nums where nums of i represents the score of its student you are also given an integer k pick the scores of any k student from the array so that the difference between the highest and the lowest of the case scores is minimized return the minimum possible difference so in this problem statement we are having two input things one is nums array where nums of i represent the score of i student another thing is you are also given an integer k so based upon these integer k we have to select k student score such that the difference between minimum and maximum of selected case score is minimized so let's understand this better from the given example so in example one that is we are having nums array as 90 nums array is 90 and we have to select one score out of this that is k is equal to one so selecting one score that is one element out of array containing one element there is only one way and we have to select this 90 so 90 is the maximum and 90 is minimum also so 90 minus 90 is equal to zero so zero is the minimum difference between selected k score minimum and maximum let's take example number two that is nums array is having 9 4 1 7. so in this case we have to select two element selecting two element out of four elements we can do it in a six way that is nc r and here 4 c 2 it will give us 6 so we are having 6 ways that is we can select 9 with 4 we can select 9 with 1 we can select 9 with 7 similarly four with one four with seven and one with seven so differences between these two if two elements are selected then one will be minimum other will be maximum so we have to subtract each one from another in this case so the difference between minimum and maximum here will be five here it will be eight it will be two over here it will be three and here it will be eight so what i can see the minimum difference between the maximum and minimum of selected case scores is 2 so this is the problem statement let's think how we can solve this so to solve this first thing we will do is sort the given nums array that is sort nums array second thing we will do we will select k elements in such a way that their difference of maximum and minimum is minimized so let's take this example that is 9 4 1 7 this is our given array after sorting it so sorted array will be 1 4 7 9 and here k is equal to 2 so if we have to select a k element that is two element in this case then we select any two consecutive element that is one or four that is four or seven or nine so these three are the possibility so like this these three are the possible cases where we'll get the minimum difference between maximum and minimum of those two selected element and if we select one with nine then we are not going to get the minimum in case of difference so after sorting this array we have narrowed down to that we can select the continuous k elements going further like if the array is 1 4 7 9 and we have to select 3 element then we can select continuous 3 out of this sorted to get the minimum difference so after selecting 147 the difference between the minimum and maximum will be 6 and if we select this 479 then the difference will be 5. so if we have to select 3 element out of this array then we can select 479 and the difference will be 5. so this way ah we can narrow down the choices of selecting the elements so let me clear this out so first thing we will do is sort the array then select the key continuous elements and we will find the minimum difference by uh subtracting maximum and minimum of the k selected element then we can compare the minimum difference of this case selected with the previous encounter all the k selected element and at last we will return the minimum difference so let's code this in c plus so quickly i will explain what i did in the code first thing i did is i created one variable main diff and initialize it to the integer maximum so that if we encounter any less difference than this then we will update this minimum difference second thing i store the num store size that is a vector dot size in one variable then i have sorted this nums array and after sorting this nums array we are iterating through this array and we are comparing the difference of the i plus k minus one element and numbers of i element with the previous encounter minimum difference and if the minimum difference is lesser than the previous encounter minimum difference then we are updating this minimum difference and at last we are returning this so let's run this code for one of the test case so it is accepted now let's run for all the test cases so this is accepted thank you for watching this video
|
Minimum Difference Between Highest and Lowest of K Scores
|
maximum-distance-between-a-pair-of-values
|
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105`
|
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1]
|
Array,Two Pointers,Binary Search,Greedy
|
Medium
|
2199
|
739 |
hello so this question is daily temperature so i give an initial array temperature and then basically you need to return the array of answer uh which is uh the number of the day you have to wait until after the item the eye day to get a warmer temperature so this question supposed to be really straightforward so just imagine this is 73 right and the next one is 76 let me just draw a little bit and then 72 right here and then 69 71 just a little bit above and 75 and 74 73 right something like this right so uh we can actually notice um when we just look at our right everything will get it right how we can be able to understand like how far i mean how many days you can get warmer and if we start looking at the uh if we start uh looking at the end to the front 73 is supposed to be zero right and 76 there is no woman there after this right so it's still zero and 72 but 17 was actually one day right and 69 72 is one day 71 and 69 72 so this is two day right and 75 one two three four right four days one day right so you can notice like this is increasing when you're increasing just only one day and then when you are like decreasing and this is like a boundary something like this like we go and you just basically check the closest one right so uh we can ask you what we can actually use the method called stack so i'm going to push the index into my stack and then when i subtract by i and this is going to be my height id so which is difference so these are stacks i'm pushing one this is one two three four five six seven eight so i'm pushing index seven right uh this is land of eight but this is index seven into the stack first so when i check my 66 76 with the value inside the stack if this is a small right if this one i'm going to pop so i'm going to pop and then i'm going to initialize occurring there 76 english to zero because the stat is empty then i push six which is uh 76 all right now i'm going to check with 72 okay the current value in the stacks is 6 and i'm resist i'm gonna say temperature is six is greater than term value 72 yes then you don't move right then you initialize the value to one right six minus five is one so this is it right and they just stop coding and you will be able to understand so i'm gonna say stack integer stack right now i'm going to traverse from here i could do a temperature length minus one i query equal to zero i am management so uh no matter what i need to push the index right into the stack and i will have to pull when the stack is line is not empty and also the current value which is temperature ai is greater equal than the stack uh the stack of peak so it's going to be temperature right temperature at startup p so this is the array right and stack is the index so i need to do that is i need to get a value right so if this is it if this is true i'm going to stack that part and i'm going to say restore that uh result i if stack is empty i'm going to return here else i'm going to say stacked up t minus i you cannot pop when you power like you're loosing values you have to use p and why you need to minus i this is because the stack of p the value is always greater than current i because you're starting from the end to the front and that stack of p is always uh i greater i mean it's always greater than i right and the big number minus a small number is a positive number and then you will just return results so this is pretty much a solution so let me run it submit all right so let's talk about the timing space this is going to be a space right stacking array of space so the worst case for the space is all the time is gonna be overflowing and represent the land of the temperatures and let's not look unless this is still uh it's still inside all the planet right so the worst case for the times all the time and for the timing space so uh let's start doing another question and i will see you next time bye
|
Daily Temperatures
|
daily-temperatures
|
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
**Example 1:**
**Input:** temperatures = \[73,74,75,71,69,72,76,73\]
**Output:** \[1,1,4,2,1,1,0,0\]
**Example 2:**
**Input:** temperatures = \[30,40,50,60\]
**Output:** \[1,1,1,0\]
**Example 3:**
**Input:** temperatures = \[30,60,90\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= temperatures.length <= 105`
* `30 <= temperatures[i] <= 100`
|
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
|
Array,Stack,Monotonic Stack
|
Medium
|
496,937
|
60 |
Hello hello friends welcome to coding interview channel on doing great difficulty on channel please do subscribe my favorite playlist news verification problems best dance update structures such a specific that link list research and also some program dance certification in programming and on please mind Now Upload Vote For This Problem You Can Also From Description Of This Video Problem Is 167 1234 Anil And Contains A Total Of An Factorial Uniform Questions Why Listing And Looting All Dham Tensions In Order Widgets Installed On The Following Sequence From 30 To Zubaan Tours Ka Safar- 3 Numbers Dham Test As per 12313 Ka Safar- 3 Numbers Dham Test As per 12313 Ka Safar- 3 Numbers Dham Test As per 12313 Tour Yantra In Three One Two Three 2016 Fermentation Souvenir vide0 Numbers Tyou Numbers And Tours Subscribe 4,650 Free Numbers And Tours Subscribe 4,650 Free Numbers And Tours Subscribe 4,650 Free Numbers In Subscribe And Return On The Farm Listen That They Have To Give A Number Diet And Number Rakhe Hai So They Have To Return Written Praman right services 100 and this flag fluid 100 to two three layer and physical to 4 minutes means you take care numbers sites you are you should have one to three and permissions veervansh vriddhi par mid day meal in what is the fourth on thursday for the sake of Street light on this will fall in this video ke seervi 232 mark of this feature in this particular example rates will list put sperm donation in the country will take all possible 4 grades of veg sandwich the fourth subscribe to be lit subscribe 25252 fluid is but when Quite Difficult To How Many Parmesan 512 Looks Amazing spider-man 2 * * * Parmesan 512 Looks Amazing spider-man 2 * * * Parmesan 512 Looks Amazing spider-man 2 * * * 98100 Electronic Subscribe To Have But Is That I To This Will Just Amused Fat In This At Veer 122 196 Per Hum Ray Rovella Plus God This Decision Us Zor Permissions Available Ride Show You Hurt Electronic Dashrath Relief But And Dros Number For The Soul Will Give You A Listing And Friend From Tensions And Selecting A Is Not Feasible Approach Tight Sada Khayal Dhruva 467 We Are Going Places All Information In Fact He Parmeshwar Number subscribe And subscribe The Amazing Subscribe to the channel 51512 It contains Vitamin E That we will then see this letter Monitor Ujjain This fog will remain Almost three thousand times existence What's the game This approach towards the Village of Dhirwas This point has been added to extra I'm soft on easy this I don't like take any point for ok suit means the number sir 12345 chronic 12345 12431 more 1243 subscribe 100 on I'll go alone in the oil and so 10 48 is so what if I'm looking for physical tool se See exactly two to president and what is second competition saugandh abe 1243 and chronic answer should be want to point and winter games for kids fashion show left right arrow is now just how for any say product treatment for playlist start with girl get all the Members Together And Aspirations And 123 Dars On That And What Were Gone To Far The Next Thing Is Take Last Number Par A Tempered Glass Number Hai What Is The It's Pre So When You Have Single Number The Formation Singh Live Video Single Number Par Subscribe E Want A Single Number One Two Three Opposite Remind Scenes 123 Only Sharing Just One Number 91 Number Seat A Tree and Quiet Front Part 2nd Year Surendra Two Numbers Parameshwara Possible Two Easier What Is The Day The Priest Doctor With The Next To What They Are Doing A Girl Were Trying To Fix One Number Share And Craft Promoter Members Should Give Them With What They Have Hands Free Mode Numbers Limited This And Left Or Right President Chosen Ajay A Number One by two one message will be my are discipline parva magh maas playlist sunao district 3050 and first quarter number five walk na draw with pics for free a fixed village is affected the waters left for oo during wali money plant sudhir and bath will have to Go Back To Step Into Place Where 400 1245 12345 Thursday Position Due Respect For What Is The Full Form Of Hai But Just Doing Preparation Is Not Want To Solve All Problems Pride This Generally This 2.5 Thursday Will Let You Know The Deaf N Par Mote The ones with numbers were right but in order to give the motivation on the field What you need to know what is the position of the What is the first character in president Vinod with minus one number to the number five Walk element on mute the name On deception quarter inch subscription on tuesday subscribe 1234 get what is the first number one talking on the first production in what way but fruit's information time jammu station witch number will give number 66 - 151 - subscribe permission again into divider happened that woman Factorial Sogdu Is Game By Email Minus One Bowls - 110 Will Give What Email Minus One Bowls - 110 Will Give What Email Minus One Bowls - 110 Will Give What Is The First And Pintu Be Fixed Pack What Is The Worst Thing Effect Feel Want To Exercise Rights Because Of Equal To What Is Acid Win32 Desire 828 By What Is The End Spoil - Vanaspati To Relax 6 Sawa 6 Is The End Spoil - Vanaspati To Relax 6 Sawa 6 Is The End Spoil - Vanaspati To Relax 6 Sawa 6 Idli 10 Point Like Tree Light and Bright Flash Light At This Time Can They Get Anything From This Is Not Really What They Want to Wear Gown Art Silk Operation Social Operation Ceiling of Water Will See What Is The Meaning of This What Ever You First Position in What is This Point to Play List Do E Welcome All Odds and Today at Indore Police Robbers Ne Chah Na What They Want to Know the Limits of Soft Elements Needed to Draw What is the Best possible way that today special and were going to use this formula and virus bowl also previously seervi nadu and wick in thy will news18 that today and baking minister we need to reduce all friend development previously object civil defense monitor friends what Is The What You Want To Give Me Information Of Women Possible Is The Question Of Why Fight Is The Difference Between And Subscribe Open Thursday 200 Put Water Was The First Element Care In Hair Right Now In Order To Reduce See Water Used Oil Use This K and factorial file friend to elements in us dry well-being of ministers us dry well-being of ministers us dry well-being of ministers sworn in as to remove a good number of what is the number of birth subscribe to I see means the quite difficult to what they want from - * - 1381 days but If we are more than one in two in one factorial what will happen is the means on Thursday in fast the first sight or not that Bathinda and particular are where not get passed Udayveer what they want to x minus the obscene Baikunth on Thursday A person with new values are the will get a A person with new values are the will get a A person with new values are the will get a new release from this point bhala we are going to get the positive character Thursday Subscribe Like Comment Share The validity subscribe and subscribe the detention Hai Quote Parde Par Classic Right Previous Song Vishesh Veer With And A Great May The Initial Li Building List Population 1234 Building At Least Are You From Want To And Just Build Atleast Harvesting Builder Answer When Due To Ignorance And Am Going To Freedom So Wild Numbers Great Khali The Number Will Keep Doing Just For The Festival Function Thursday Subscribe To A Valid And Want To Calculated In The Fast After All Of Invention Dowry Veer Celebs Subscribe Button Subscribe To Subscribe Video To This Dynasty Or Painter Digit Will Be Removed From Price List Just Like 15.1 Hair And From Price List Just Like 15.1 Hair And From Price List Just Like 15.1 Hair And Removed From Delhi And Power Limited 2348 1234 Rate Forever Timed And Will Be Only That Recent Well What Is The Given Position Logic Which Passes Through The Permissions For This Particular Person Thursday Note First Position In Police Department And Subscribe Our Dip That Knowledge Input Service Exactly Wedding Number 5 That Way When Logic Gets Finally Water The Amazing Pimple Code That Building Subscribe Number One Right Subscribe to that were given with and care ok good suna me bhi this field country list with jain more hai a plus morning send a smile on this point to execute festival subscribe and like thanks for watching this Video plz subscribe Channel subscribe Video ko appointed result Subscribe to this will be reminder conference anywhere in the space work previous video channel subscribe difficult questions please comment section in this video subscribe my channel description video subscribe videos thank you for watching my video problem hai hua tha
|
Permutation Sequence
|
permutation-sequence
|
The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:
1. `"123 "`
2. `"132 "`
3. `"213 "`
4. `"231 "`
5. `"312 "`
6. `"321 "`
Given `n` and `k`, return the `kth` permutation sequence.
**Example 1:**
**Input:** n = 3, k = 3
**Output:** "213"
**Example 2:**
**Input:** n = 4, k = 9
**Output:** "2314"
**Example 3:**
**Input:** n = 3, k = 1
**Output:** "123"
**Constraints:**
* `1 <= n <= 9`
* `1 <= k <= n!`
| null |
Math,Recursion
|
Hard
|
31,46
|
334 |
hey everybody this is larry this is day 18 of the leeco daily december challenge hit the like button hit the subscribe button join me in discord let me know what you think about today's forum so i do explain and solve this live so if it's a little bit slow uh let me know or fast forward i usually go for my thought process and not just the solution so your mileage may vary okay so today's problem is increasing triplet subsequence uh okay so okay n is 10 to the fifth i think the i think there are a couple of naive solutions and the really naive is n cube where you know you go i j for i for j for k right um it's probably a little bit easier to do an n square just by you know four um yeah just like two loops and then you kind of check where uh in order one whether there's a number or like the biggest number that's to the right or something like that and yeah and you could there are some linear time algorithms for sure um though yeah try maybe not know once because i'm practicing because the basically the idea that i had was that okay um you're just basically trying to get them the min so for each uh number you're trying to get the min to all the numbers to the left or previous and trying to get the max of all the numbers to the right and if the current number is bigger than the min and smaller than the max then you have you know then you can do it in linear time uh and that is very straightforward kind of it's a it's uh you know you well the prefix part is easy because you could just do it as you built but on the suffix part you either use well you just you either use um you can maybe do use some sort of like minor stack or something like that but you could also just have a suffix uh a way of dividing max um which would be monotonic obviously so uh which is you know another way of doing mono stack uh of course that's gonna be linear time but that's gonna be uh linear space um don't know if i should go over that one a little bit more but um but okay right all right let me go over that very briefly and then we'll go over the one with all one complexion i think i have an idea about or when complexity i do want to go over it because i feel like that is a pattern that comes up in other problems or other similar problems and it's a good way to kind of think about it right so that the two techniques that we can think about to solve this in linear time and linear space uh you know you can have it follow so for x and nums and then you know min to the left say i mean you know my variable names are a little bit longer just for it uh for explanation reasons explanatory reasons uh so it's equal to you know mean of x uh well maybe x and then the current min right to the left right so we have to start this off by some like infinity that's fine right uh and then we have to of course we only update that afterwards but then you know max to the right um is equal to some stuff so we'll put that on later as well um so then basically i'll check is if min to the left is between uh this have to be strictly increasing i it has to be strictly increasing i just have to check the signs max to the right then we return true otherwise we return force and of course we update the min which is easy but as we do a rolling sum uh and then we can update or we can set the max by just having a suffix max so that's of a suffix max is equal to an array of oh it could be negative infinity so let's just do negative infinity or negative really big number uh times n plus one i always do n plus one yeah and it's equal to the length of numbers of course put it in top and then now we go backwards uh i like to write in a while loop so n index is equal to n minus 1 while index is greater than 0 index minus 1 so and then suffix of max is just the code 2 or suffix of max of index is just equal to suffix of max of index plus one max of this and the num sub index right so i hope i don't have to explain this part uh let me know if i do but um but i would also recommend just um looking into prefix some prefix and suffix um sum and all those things uh this is basically that idea of basically just rolling a for loop as well right basically you're looking at you know uh i'll do a quick example real quick but basically what this loop does is that you know it goes for the last element uh and actually there's an extra element that's negative infinity um and then look at the last element is it looks at is this the max yes then let's put it in there um and it looks at the four and goes is this the max no so let's take the previous max and so forth so then now we have a lookup table of uh things to the right and the max of that number and actually this is a terrible example to be honest because this is all sex but that means that at every point to the right uh so the query that you want to answer is that for this number to the right what is the max number and that's a six and you can do this all one time if you build this out and all of end time um and then yeah so here is just um and actually we could just put this up front because it's the same anyway suffix max of index right and of course you have to set index here enumerate just adds it to the index so someone like that we're going to run the code real quick so yeah so this looks good i'm not going to submit it yet because i want to do an optimization uh and this is kind of an optimization i like to talk about because it does come up from time to time and you may hear the term mono stack or monotonically and i guess in this case it is decreasing stack right um and basically the idea is that you build um this array in a good way um you know this takes of end times to build uh and there's really no way about it because you have to look at everything but you can actually convert this into a stack because by noting that and this is not a great example but um actually let's use this one where and now let's just not only use this one i'm going to put it in the middle maybe no take out the six all right let's just put it in the end and then put six here and then you know here it's gonna be r6 so then now when we generate the array it's gonna be excuse me uh negative infinity uh one two i'm writing it backwards so that's kind of silly but so it's just gonna be six five four three two one right oops and as you can tell it is monotonically uh decreasing and so if you're really slick about it you could convert this into a stack um and you know going from right to left and that would save you some space but um and i think in this example oops uh yeah and let's say you have a i don't know another five here or another seven i don't know like this is always going to be monotonically increasing and you may skip some numbers if you know there's a five here for example uh then you have five here instead um but anyway my point is that um this is a good pattern to notice because it comes up in different problems and this problem actually doesn't save you that much i mean in theory you could say that it saves you a little bit extra space depending on the longest uh decreasing subsequence or something like that uh from the back but it's not gonna you know it's still gonna be linear time it's still gonna be linear space in the worst case in the case of everything being decreasing right but i like to point it out because it is a pattern that comes up from time to time um and knowing these patterns will allow you to simplify things um for you know different constructive reasons right okay cool so that is the linear time linear space one um let's think about the o of one space right so i actually don't like the old one version of this that much um i mean it's cool but uh but i don't like thinking about it in that term what i would like actually to think about is actually dynamic programming uh and if you saw this coming uh from the beginning let me know uh because i think what i remember is uh the explanations that uh on this type of problem is that you know i always bring up cadene's algorithm which is that when you look at people's solution and they take away the you know they take away the dynamic programming aspect it makes it harder to understand for me or from my angle i think i find it harder to understand because some of the logic is just like too magicky you know it's just like oh this is a thing and yeah if you want the algorithm it's true and you're able to prove it but for me true learning is about reproducing it and solving a new problem using it and stuff like that right and this it's not related to contains algorithm except for in a sense that of um the space reduction part of dynamic programming which we'll go over in a second so the way that i would think about it is thinking about well this is actually similar to a problem that you may have faced before uh the longest increasing sub sequence right so basically um i'm not going to go that deeply into longest increasing subsequence because that is a long explanation as well but um but so i am recording these explanations live and trying to think about the best way to explain it so my apologies it was a little bit rough but yeah but now for the longest increasing subsequence there's the n square algorithm where you know very naively jeff let's just say our s3 maybe for naming is hard or even is three right we're increasing subsequence of three you have an index you have a count and the thing here is and this is kind of involved but you know you have to index an account or the state where index is the index of the num of nums uh and count is equal to the count of numbers to the left of index that are smaller than index something like that right um and in that case your algorithm will look roughly like this if kind of go to three then we turn true because that means that you're able to get there otherwise you have a for loop that goes for i don't know next index in range sub n starting from index plus one maybe and then you have something like if num sub index is strictly less than numbers of next index um you know let's have possible is equal to false then possible is equal or equal to is three of uh next index uh count plus one right something like that and then we turn positive at the end uh so i'm not going to even run it because this is going to be way too slow um but i just want to illustrate this because this is n squared right so this is n square implementation of the longest increasing subsequence if you only need three of them again of course n is 10 to the fifth so that's gonna be way too big and square is gonna be way too slow give them know the states um the only n o of n states because count is only going to go up to three and index goes from zero to n but anyway so now we're gonna um we're gonna convert this to the top down and the way that you would do that is something like this uh for next index and range sub uh index plus one of n uh dp maybe someone like if num sub index is well in this case the next index is a smaller one so that's actually terrible maybe the name of previous index layer okay fine uh no this is still next index but i'm doing it i like to do it the other way uh when i do this so actually we should go from zero to index um so that if numbers of index is greater than numbers of previous index then possible of index is um oh i forgot about the degree psi um well you can you could do it in a number of ways so then you can actually just do like something like the impact uh is uh you go to the max of dpa sub index uh dp of previous index plus one uh and then you know in this case we would just return dp of if index uh or you know if any of the index for index in range sub n um someone like this right so now we check whether any um any dp has a count of higher than three so and it that's one way to do it another way to do it is to notice that um notice that it has three variables right so we can rewrite this to um or like it goes the count goes up to three so we can rewrite this to add it to the dimension to kind of you know fill out that boolean map instead of having this mostly equivalent but the reason why i want to focus on this part is that um yeah so there's a double a couple of ways to do it with dynamic programming the way the reason why i want to focus on this part is that uh longest increasing subsequence if you do remember but has an n log n reduction that reduction is actually kind of tricky to prove and understand but the short idea behind that is that okay so you know you basically st uh how do i wanna explain it um but i would definitely implore you to kind of try to understand that explanation uh because it is kind of hard i'm gonna go over a little bit but probably not in depth for you to like really understand if you haven't seen it before but the idea is that okay right uh and it's kind of a tricky idea so that's why i don't know i'm well equipped right now to prepare to explain this but basically the idea is that okay right you look at the longest um in the longest subsequence you know instead of storing the dynamic programming on index we store it on based on the length of the longest increasing subsequence right and of course that's gonna be of and space because uh because the longest it could be it's just n elements right so the thing is that if you take any um fungus let me take an example here is that we can construct an array you know in n squared times say i mean and there are ways to obviously change this to n log n that's the basis of dynamic programming but the idea here is that okay for each number that comes in uh we keep a storage of the long the smallest number that is the last number of a length uh of a longest increasing subsequence of length i so okay so let's say we have an array called longest length uh we let's just set it to uh start with negative infinity oops uh oh i don't have infinity setup okay negative infinity times n right n plus one i guess actually and from here let's define this let me write it out and find it longer as lame um maybe the maybe i call it let me try to think about naming this uh but okay fine let's just stick with this name longest lane sub i contains is equal to the smallest number that um the smallest number of um that ends a chain or answer yeah increasing subsequence of length i something like that um and you know i'm gonna and that only contains the smallest last number but i'm going to um i'm going to show the list just to ensure right so for example in the beginning this is equal to just nothing right negative infinity right uh so negative infinity i'm just this is a pseudo code anyway so uh and then now the we process the two right here so two and we're going to just do an algorithm so then now what's the longest length of zero well it doesn't change because it doesn't do anything uh so then here the longest uh so this is actually undefined technically i suppose actually uh but length longest of length one uh so what up to this point what is the increasing subsequence of length one what is the smallest number uh the smallest path right and you know right now it's just two and all the other ones can be undefined and then now we're going to go to one and well here the smallest number that could be an uh ending at a path one is going to be one right so now we replace the two of one uh and we would actually also replace this but this is still undefined because there isn't one that exists um and then now we're gonna do it five gets interesting right where's the longest length of one well one is still going to be the answer uh so then now we could take this you know we could use this to build on the longest of two uh and now we have one five right this is the longest this is uh the sub sequence of length two at up to this point oh i have to update this to 0.5 this to 0.5 this to 0.5 and then we do it for zero well for zero now we go for the for loop and this is actually zero this is smaller than that so this is going to be updated to zero um i'm gonna add more numbers in the end just to kind of show the longest increasing portion right uh and then now we do the four well the four now we can either take you know and this is where the dynamic programming type of mindset gets in is that okay so the new you know longest of one it's not going to be smaller than that so that's fine but the longest length of two can either be uh the current longest length of two which is just one five say or the longest length of one plus can counted by four which is equal to zero four right and in this case we do this comparison between one five and zero four and so 04 is you know smaller because we only care about the last element and i guess by tie breakers you could go up the list but uh but it shouldn't matter too much uh at least in this problem because you only need you don't need to minimize anyway you don't need to get the smallest one so then we now we update this to zero four right and uh and i guess technically before that uh i guess you have to do it in order that makes sense otherwise uh like in theory you could add a at a longest length of 3 but it's still undefined because if your number is 4 you cannot add it to the longest length of 2 and you know that because if you do it in the right order well then varian is that there's that if the last number the longer longest length sub 2 is 5 there's no possible subsequence of length 2 that contains smaller than a five as the last um that's the last digit right so that anyway now we updated so four and so forth uh and then now update the six uh nope uh and then this is zero uh for six right and then look at seven um well i mean there's gonna be a longest length of four dot i'm just gonna dot that part just to kind of keep it short um and then now we see the two it becomes interesting again uh this is no good no bueno uh because two over four is no good so for this one uh longest length of two is just longest length of one plus two so then now we can update it over two and then eight at the very end you know we update all the bigger ones uh and then let's just fit in a five if we have a five then actually even if ever six then actually the longest length of three gets updated because longest leg of two plus there's uh sequence of 5 this becomes 0 to 5 segments uh and that's pretty much the idea okay so that's the idea of the longest increasing subsequence um in n log n or well that's an alternative version of n squared because you know you see me do this n square but the thing to notice about the sequence is that um if you only look at the last number and now we're going to remove until except for the last number well the last number is actually always going to be increasing right because you know by contradiction or something like that where um where if this number is bigger than this number then uh well this is a contradiction because then either you know either this should be five uh let's go back to the more digit ones right like if this number is 06 for example right that means that uh there's a contradiction because i'm for the length of 3 there's always you know you could take a subset of this and replace it with you know a sequence of two right so by that logic this is always going to be an increasing order and because it is in an increasing order uh you can binary search to figure out what's the longest length that you can do um to uh the longest thing you can do to uh alter it right and then change that number uh going forward um yeah so that's the analog and explanation of the longest increasing subsequence kind of i hand waved a little bit but that's kind of the idea behind it right but in this case um as we talked about this is actually just an increasing subsequence of length three and we have to check whether it exists so the short answer is we just use the same algorithm except for that we keep only the first three elements and we don't even have to care about the log n part we don't or log k or log n or whatever because this is a constant right we just care about the first three triplets so now we're gonna write it again right um now we're gonna write actual code uh yeah and here we can just say this is three let's say this is four because this is three plus one uh just for so that i don't uh so i don't return early so that you can see the example a little bit more so yeah so now for um no so what actually what i want to do is a little bit different no this is fine i mean we could do a little bit more illustrative but yeah but now basically just implement what i said which is that for let's say x in nums and then now we go through uh the lengths so for length in range sub 4 uh remember to this is a weird way to look at it in python but basically it just goes from four to zero right so basically what this does is uh implement what we did what we imagined earlier so if longest of length minus 1 is less than x now um i mean it's true but we actually have to care be careful about using just negative infinity in this case um centigrade is more undefined but um yeah maybe i should just make it more explicitly undefined maybe that's a little bit better so that uh we so that we have an extra variable about saying it not exist but basically now we go if longest length of length minus one is not none meaning that there is a value and this value is smaller than the current number let's actually name it current because i use x too much it gets me in trouble uh then now basically what we're doing is okay we're saying the long uh the sub there is a subsequence of uh length minus one and that the last number is going to be smaller than the current number then actually now we can create a new uh increasing subsequence of length right so longest of length sub length is equal to the min of the current number because this is the last number and just the previous link so like you know if it is already lo uh small enough then you don't have to update it and that's pretty much it so now at the very end and i know that you could actually fast for uh you could do an early return or something like that but i just i'm going to show you at the way and we just do we turn longest length of uh three and checking that it is not none right let's run the code real quick because maybe our typos hopefully yeah uh ooh force for force um well it's false because everything is none so we have to set uh set length sub zero is equal to negative infinity this is a little bit awkward but um oh yeah and we don't update zero so actually we should just go from four to one so then two minor errors i'll pull it uh let's run them real quick um none type and end i thought we checked that this is not none uh 9 18. oh because if this is none then yeah okay fine so the longest so the current is none then we just take it i don't otherwise we take the min okay whoops see daisy's uh coding is hard oh index our range what oh this should be three of course i don't know why i started at four so this should be three to one man all five once my brain is a little bit juicy today but yeah so that looks good uh let's give it a good submit and hopefully that's right if not it'll be a little bit sad okay cool so what is the complexity right well it's gonna be linear time because we look at each um for each number that is in nums we do a for loop sure but it only has you know it's a constant amount of iterations in the for loop so it does a constant amount of operations uh especially inside so this is going to be of n time in terms of space well we only create four uh four like array of size four so it's going to be constant space and that's pretty much it um i know this is a very long video and hope you learned something from it because there are a couple of techniques here in general but it's kind of a cool problem i dig it i mean i and it is something that once you know if you remember the trick then it is much easier but for me it is about kind of knowing why like this works uh it's kind of important as well and of course uh once you're more familiar with it then you're actually able to do this for you know like this just becomes longest increasing subsequence uh of size whatever so yeah um and you know you could do a binary search here but that's fine um cool that's all i have for this problem let me know what you think this is a long video um but i hope for a good reason so yeah definitely watch at your own pace and i'll see you later bye
|
Increasing Triplet Subsequence
|
increasing-triplet-subsequence
|
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
| null |
Array,Greedy
|
Medium
|
300,2122,2280
|
209 |
Hello Hi Guys, today we are doing question number three of the playlist of Sliding Window Mechanism, the name of the question is Minimum Size Ride, Assam Recruitment 201 Question, Additional Session Court Company, Google Amazon App Co Light, Facebook Governments, OK, so let's see the question. You will be given a target, I will stop and an interior will be given, you will have to find the smallest sub in the interior, find the smallest one, which is equal to or greater than the target, okay, I repeat again, this is the interior, I will tell you the smallest sub The smallest sub is the one that should be continuous. So the bell will have to be the smallest bread whose sum is greater than or equal to which the target is ok so the smallest is the subri whose learned to is ok now which is the city of the to lens whose The length is whose capacity is equal to the brigade, that is this side and three. Okay, so its length is two, so the minute weight is done. Okay, now one more example, if we assume that it was something like this, how to. MP3 1243 Okay, if you pay attention then all this is its constitutional and target, that is visible to you, okay, its committees are okay, it is okay that greater than or equal to two, and if we make it bigger, I swear to you, at what time should we tie the knot, but What do you need to make the smallest roast right? Okay, so we will not make it, okay, and if we go ahead, here there are 438 discs, even service, then your answer should be K, AIIMS-2, it should be the be K, AIIMS-2, it should be the be K, AIIMS-2, it should be the minimum. Which balance is it, you are ok and one more balance was found whose prosperity is Dr. Ok ok, one is a complete journey ok one is complete and one is a complete life whose prosperity is the target but that one is big is n't we the least The window should be of minimum size whose prosperity is flipped out as per the target. Okay, which is our answer. Me too. Okay, so let's see how to solve it with the help of sliding window. Okay, remember one thing whenever in the question. It was being said that continuous is a continuous word or if that word country is used then understand it that it is the end, hence sliding window 8 from now on don't think on the side, think millions of times, think at least once that yes. Can it be made from that or not? Okay, so let's see how we will solve this question. So, let's take this example and move on. Okay, so first let's take an approximation in which I will continue the journey of minimum balance. Right now I don't know. If it is, then I will take some big number. Okay, what is the size of the gesture? If it is 123456789, then for now I will accept that as its possible. Greater nickel two should be my target. Okay, now let's see if it is cheaper for me. Let's take two points, first you are here, okay, when here, okay, now look, and the window that will be created will be 20 minutes of I and J, so I will start freeing the first, okay, let's go, I will now. I understand that the window is good, it is fine, I am not interested yet, so I am leaving in 2013, my time is now zero, okay, now see what I have done, I have whitewashed my name, everything is fine, while Virat has made it evening. At the time of the committee it will be only the 2012 latest. You have come, so it is okay whether it is equal to the two targets, otherwise I will let me go, okay, now there is a big one, otherwise nothing will work, let's move forward. Okay, okay. Have removed it, now I move Jai forward, brought Ji here, okay, now let's see, San Om Sham will have to be added in Awadh Assam, in the taken tag in the judges index, that lever of that time was Ya To, earlier it was Plus. Which we will do right now, like here, no, what has happened, it has become free, this has failed, okay, is it five greater than equal to the target, no, okay, no problem, we will not do anything right now, let's remove this, you also offer this. It will move ahead, okay, I have come here, I will add it again, I will do Scorpio, what is the time of the spinners, then all the musical two's or five plus, what is the value now, on which one is there, then the command is six, okay, 60, what is the cigarette daily. And the target is not fixed, no problem, now let's move ahead, so I have moved the check forward, okay, now let's see, at this time, the time will be yours again 222 6 plus two 8 is 8 Is A Greater Than Equal To Target Yes? This means this window could be my answer because understand it is greater than equal to target okay now look at this carefully what do I do first I delete it okay what is the value of this time right now or is one Which window does it contain, which is among the Android apps, its time is eight, which is the time from the targets, what is the pet, which is created equal to the target, tension, target is only 10, okay, right now, think of me as such a window. I have got it, I have got my answer now that yes, you will get the size of a window which is this much, one, two, three, four, okay, I swear on this visit is greater than enough to target, but can this video be made smaller, then try every time. How will we shorten this video and how will we shorten the target of Silicon's Can We Get From Delhi, we will shorten it due to the fear of I, okay then I declares, okay, now if you shift brother, what will be the window quarter? But Layu declared, moved away from here, okay, and came mine, came here, okay, now window has been made, A window, mine, this has become okay, now look, now you are the one who has declared, it is yours, whatever capacity came in it, but first here. But if it becomes 280, then at the index time it will also have to be cold, otherwise what will I do at this time in the evening - will I increase the this time in the evening - will I increase the value of where the eye falls before - 2 will give six. value of where the eye falls before - 2 will give six. value of where the eye falls before - 2 will give six. Okay, then I will check. The lesson is that the data is recorded to the target, no, okay, if it is not, then it means we cannot make it smaller, and let's go, okay, we can make it smaller and if we cannot, then it comes out. Now let's focus our attention back to J. Okay, now that Look, this is mine, we removed this here, we take J here, okay, update everything to my 60. Om Shree plus Vansh plus two took it was done. Hey, where has it come on index number four, his heart is for, so we will only what will happen? Time 222 600 Okay, so first watch this video, let's see if I hit this window first, which window from A to Z is this window, why did I grab it because this window swears it is greater than equal to. Target fixed rate, look here carefully, return has come, it is ok after collecting 1 liter of fuel, then I will ask the question, can this video be shortened and by shortening, can we still get ahead, please check this updater nickel to target. First of all, let's remove the I. If we shift the height forward, then let's see the page value - if it is also there, let's see the page value - if it is also there, let's see the page value - if it is also there, then what will happen to us? Which one is at 0.5 inches, is it then what will happen to us? Which one is at 0.5 inches, is it then what will happen to us? Which one is at 0.5 inches, is it free now, is there a conversation with gas, so let's first shoot, you can fit it. Gives because we have removed it, come here, I have removed Hina Khan, now my window has also become smaller, I am making the window smaller, so the window will become mine, whether it is this one or not, but right now, it is mine with all the colors. That's the right thing here, one plus two plus 470, is it now targeted at the bread man, very good, this is now targeted at the formation, that is, I have got a small lens, go and what is the size of the I person, is it free, right? Isn't this Jab Bigg Boss how much is Jim - I will be Isn't this Jab Bigg Boss how much is Jim - I will be Isn't this Jab Bigg Boss how much is Jim - I will be plus one in size, it has become free, now we have got another smaller one, so now I have updated the thing, I have updated it, okay, then let's see what else can be shifted. Let's see, if it is done then it is a good thing, so I have removed Ai from here and I have taken Ai from here. Okay, so when I have taken Bhai, then the garlic where it was before on the side will be reduced, so it is from us, isn't it? Your number is not 207, now this intake will be divided, this one is closed that if you, that will be fine, okay, then what cigarette is not the target, it means if you can't make it any smaller, then brother, get out, okay, let's go out. And now Vijay Pradhan gives, okay now you swear, how much Chenna is the window's organizer, Buzz Window, sorry, its time, six, now let's move G forward, let's see what happens, yes, I moved G from here and moved J here, okay and when increased So whether it will be valid in our time then the number will increase. Now the incident of 6 plus 3000 is 6 plus 3000. This is bigger than enough to target. It is very nice. Okay, now as soon as you see the size of the box in the middle, it is This is not our box, its size is three, this is Saffron three, so our channel has lunch now only three, so those spines and Chhota Bheem have not been found. Okay, it is fine, but please pay attention to one thing, I have got a few targets, but I Then ask yourself, can it be made smaller? To make it smaller, we used to shift the I. If it is right, then we will attract the I. If we shoot it will break, when we shift it to the right side. Here, I, when here. If it comes then it is also of broken form, it is not our number but yours, okay then what will we become, nine - two, that is 72, this is also grade next date, very - two, that is 72, this is also grade next date, very - two, that is 72, this is also grade next date, very nice, that means we have got even smaller wind, brother, okay, and more. Got a small window which I think is the Greater Nickel Target and let's see which window is this window, this is our window. Look at the I and J. Okay, still let's see if we can shift the I further. Okay. It has been accepted that if I have been shifted then where will I go if I am here or not? Now when you send I, we will also have to update. Golaghat in Assam was the first intake. Now when I have been shifted then come first for. If we had it then we will have to consume this world in which there is no data daily and target meaning we saw it wrong meaning it cannot be any smaller then it is okay after this when we go further our look will end and remember we have seen a very small wind I had already found that the size of this one is two pointers, well two in that our smallest window whose number is greater than enough to target is of given size and this is our output was also two, so I thought it was just 2 pointers. Have played an I and J, you have to keep doing Jacomo and as you know, well consider this window as the target of fire, quietly and try to make it smaller, keep mowing the bread idli I will taste the food with you till then Move till the scientific target is going on. Okay, after that increase the victory. Okay, if you understand, let's code it and again tell the same sorry in the code and you will understand better. Okay, so let's start recording. So first let's see the question that you will be given a positive energy source and you will be given a target. You have to tell the minimum balance continuous sub. Hey, you have to tell its penis which includes greater than and equal toe target. Okay, I had shown you this amazing feat. Okay, so constraints are nothing special like that, no, okay, there are many ways to clear this, but follow up question, I have told you follow that even if Ashari flops, we will see what we have created in One Solution, what I just told you was One Solution. After that we will see that we can create it in login also, is it okay, so first let's see our one solution which I told you, we will tell you the same story in the same way as we explained here, take out the largest and start size, okay, what did I do? I had said that I will keep two points, J will remain at 90 and I have set the alarm to be the size and I have assumed that it is fine and my window will be running smoothly. I swear, now you understand what I said when you jack and will run till the last, after that. What did I say that I will keep doing maths Jackie Velvet, Sampark Na is on the index, so we have added the vegetable, okay, everything is clear here, how did you know inside this that when then when I feel like I will come to know that What will you know? Do you think targeting the kidney is done? As long as it is there, what will I do? I will try to remove it. The size of the window is fine. I will try to remove it from the window. So, I can update first. I am a nipple toe man of mail. And this is the size plus one, this is the window size that I got, its size is smaller or the first one is the smallest one or we will fall back from the first one, it is fine from the channel and it will keep running in the files until it becomes smaller. Okay, then what did I say, Chota, the action will have to be shifted, but only Gurjar will shift, then understand - also, we will shift, then understand - also, we will shift, then understand - also, we will name it Safai, Na Sam - surgical, salt Safai, then Eco has been Na Sam - surgical, salt Safai, then Eco has been Na Sam - surgical, salt Safai, then Eco has been shifted, so this is the point. This point, this is the same, I want to make the window smaller, I am coming, okay, stop and every time you look, you have to make it bigger, okay, it has increased, in this way you will get your main value, let's see this, let the commission understand again. Let me tell you that we have taken two points, if it is set from i10, then the window size is 200, which is fine and we will keep adding vegetables among ourselves and as soon as I know that a good organization has been targeted, then I will make this video smaller. I will try to do it as long as it is small, it is a good thing, I will update it separately, my minimum balance has an effect, now I will keep watching and how to do it small, I will try night shift, right swift off, and concentrate while shifting. Will have to be given because the short fast and intercourse will be decreasing till the window, then the moist side will answer this question first - that too, then it is declared on this first - that too, then it is declared on this first - that too, then it is declared on this site and this should remain big, it is okay, then as we come out of this iron, our The scum must have come out. Okay, let's run it and see. Left right two seats will have passed all the example test. So here let's see whether all the dishes are passing the example test or not. Let's see what's wrong with all my methods like this, Kailash. Well, it will be okay, so we have mixed things, if there is any such thing, you do not get everything, I swear, medical records, if you have to return zero, okay, that's how it is done here, consider this example as a birthday example. Have you ever got one better than 11? It has grown up, no, okay, what is its time? 123456789 This whole thing is smart, which is the target of garlic, so now we will never get it is a question whose constitution is tight, then we have to run at such a time, but we were mail. Let's return whose volume is nine and here it is okay so by saying N we will check this min is equal to two so then I take a bigger one, enter takes max, now I thought let's assume my enter max is good. Okay, so I have to do the protein. It's okay to describe the value of the help channel. I hope this is the time, it's personal details. Sss. They have left side. Submitted is New Delhi. Solve this question. Have you understood? If you have any doubt, you can comment. s do ultra 238 shiv guys i did this video thank you
|
Minimum Size Subarray Sum
|
minimum-size-subarray-sum
|
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
| null |
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
76,325,718,1776,2211,2329
|
8 |
Lucca number a string to integer implement a 2i which converts a string to integer so the function first discards as many whitespace characters as necessary until the first non-white as necessary until the first non-white as necessary until the first non-white characters found okay then starting from its character takes an optional initial plus or minus sign followed by as many numeric digits as possible and interprets them as a numeric value the string can contain additional characters after those that formed integer number which are ignored and have no effect on the behavior this function if this function of sequence of non whitespace non white the characters his system is not very integral number or if no such sequence exists because is either straying astray CMC or it contains only whitespace character or no conversion is performed if no Valley conversion could be confirmed as zero is returned only the space character is considered whitespace character okay so if we get 42 we return 42 if realize why space 42 - 42 if it is like this OH if the numeric number is out of range we should return this but in JavaScript so it's much bigger than this I think max integer okay Oh and if we get a word 10 9 8 7 because this word is not digit so it's not a numbers she returns zero and like this you should output this because this should be the biggest sign number okay the first thing is that what is the same integer number we can have okay we say number max safe integer is like this so what it's much bigger than yeah so javascript uses like got more than 32 bits as a integer right equals 64 for the numbers so how many bits are there I don't know it's actually not very difficult I think it's just three four we just traverse through the string and first we skip the whitespace and check the sign and the collected numbers and then we just get the result so I think we should Asur the first one is that the results that result in zero and then we should save the signs I just say save the sign it says one and then we were four let's I equals zero I smooth it out string and then I plus we used to traverse to digit so factor Esther we should also store the flag is let check whether it is at the beginning so it's white space no is no white space Matt is false okay so if character is just white space on this white space this okay so if but if it is like this if is no white space man then you should be mad right oh no it's not so we should continue else break okay the other case is character and then if we met plus it's okay we're just too silly to continue the sign is one if the character is minus sign equals minus 1 this equals to 2 and this equals to true if continue if character s numbers how can we say it's numbers so it should be if character is bigger than 0 and the character is smaller than 9 it's not the integers right okay so it was a result equals result times 10 plus number the value of this character so it does should be character minus 0 okay finally we can return the results but we need before that we should can we should do some comparison so we should say return result oh the other case should be break anything other cases we should break and the return the result should be between a wrench so that's his math max this is should be the minimum is minus 2 Oh time 31 okay so this is results and we should say the seating for it is mean and it's 2-1 I'm not sure whether this and it's 2-1 I'm not sure whether this and it's 2-1 I'm not sure whether this works but should be Oh God my here is this is true the other cases it's like this okay if you got 42 for because it's four we met and then four for because this is like this so it should be four and then we break oh no we don't break here let me continue God continue here submit I think you will fail maybe yeah for these cases but if we got the space this space right we got space and it's false so we break ah it's not oh we got here so look at this ah she should type should get the sign oh I hate these problems it's like all those kids well this is snoo plus minus 2 should be minus 2 okay sign should be minus 1 she just talked with it upper minus two is zero ah I got oh he sign it so Oh s is false is true this is true I'm sure first week check if it's digital's for numbers and then if it is plus and this I met Simon allocates break 0-1 this I met Simon allocates break 0-1 this I met Simon allocates break 0-1 first we got zero continue and now we got the sign because the sign is actually this and the sign is not met so sighing oh God it's for these if you follow okay it's non-white spaceman okay so if okay it's non-white spaceman okay so if okay it's non-white spaceman okay so if it's digit if is it go to next one so okay so it's actually I'm sure you fail we should keep a flag off is number face is number started number face equals false so if not number face and you should say accept it's not fast but I think mmm anyway it's I don't have any other so it's just like a trial for exceptions mm-hmm mm-hmm mm-hmm this problems not that cool so that's all for this but for this one see next time
|
String to Integer (atoi)
|
string-to-integer-atoi
|
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function).
The algorithm for `myAtoi(string s)` is as follows:
1. Read in and ignore any leading whitespace.
2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4. Convert these digits into an integer (i.e. `"123 " -> 123`, `"0032 " -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2).
5. If the integer is out of the 32-bit signed integer range `[-231, 231 - 1]`, then clamp the integer so that it remains in the range. Specifically, integers less than `-231` should be clamped to `-231`, and integers greater than `231 - 1` should be clamped to `231 - 1`.
6. Return the integer as the final result.
**Note:**
* Only the space character `' '` is considered a whitespace character.
* **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits.
**Example 1:**
**Input:** s = "42 "
**Output:** 42
**Explanation:** The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42 " (no characters read because there is no leading whitespace)
^
Step 2: "42 " (no characters read because there is neither a '-' nor '+')
^
Step 3: "42 " ( "42 " is read in)
^
The parsed integer is 42.
Since 42 is in the range \[-231, 231 - 1\], the final result is 42.
**Example 2:**
**Input:** s = " -42 "
**Output:** -42
**Explanation:**
Step 1: " \-42 " (leading whitespace is read and ignored)
^
Step 2: " \-42 " ('-' is read, so the result should be negative)
^
Step 3: " -42 " ( "42 " is read in)
^
The parsed integer is -42.
Since -42 is in the range \[-231, 231 - 1\], the final result is -42.
**Example 3:**
**Input:** s = "4193 with words "
**Output:** 4193
**Explanation:**
Step 1: "4193 with words " (no characters read because there is no leading whitespace)
^
Step 2: "4193 with words " (no characters read because there is neither a '-' nor '+')
^
Step 3: "4193 with words " ( "4193 " is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range \[-231, 231 - 1\], the final result is 4193.
**Constraints:**
* `0 <= s.length <= 200`
* `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
| null |
String
|
Medium
|
7,65,2168
|
1,302 |
Hello everyone, Evgeniy Sulima nav and today there are 3 problems years code number 13 02 the sum of the deepest leaves according to the conditions given in return we are given the root of a binary tree and we must return the sum of the values of we must return the sum of the values of we must return the sum of the values of its deepest forests below we are given two examples in the first example we have a tree of this type, that is, 1 2 3 4 5 768 and the results of the work, our place here is expected to be 15 because the deepest sheets are sheets with values 7 and sheets are sheets with values 7 and sheets are sheets with values 7 and 8 and are not at the deepest level and at the output we will get 15 if we assume there weren’t 8 here and end assume there weren’t 8 here and end assume there weren’t 8 here and end with 6 it would be let's say we have 7 then because at the deepest level there is only one leaf with the value 7 how can we approach solving this problem as usual when working with binary trees we have the choice of either going through tree traversal wide bradford or dfs dpr search I chose the second option here, let's see what you can do here, I'll allow myself to do a little magic with the drawings, that is, what we can do, that is, you and I will create an April on the stack in which we will throw our elements in this order those. first we threw elements 3421 we return 48 that is, we go in depth first from the left side and then we go in depth to the right side and we check three main variables in addition to our junction, that is, the max dps variable itself, that is, the sum of the elements at the lowest level of akarin dips is the depth of the current but to which we will get alternately from the stack and max dips is a change that will store the maximum depth that we have so that we understand that this is the depth we need these elements and get I think this is clear let's try to implement it all in code then there is here we see with you class 3 not which has a value of left right elements constructors and access to this element, well, let's get started, that is, for starters, our changes appear, that is, I have a variable int max dps itself which is now is equal to zero, we have a variable int max dps which is also zero and change it to karen dps which is also equal to zero and of course our stack appears which we will store pairs of elements, that is, the note itself and the number, that is, which will indicate its depth, that is, us a dakele appears in which we will store pairs 30 and an integer, let's call it a stack and it will be a new ray such that is, according to the java documentation we are recommended to use Rebecca instead of a joint so it will work faster and faster than a league from a sheet if we use it as a stack you can read others having created this stack, we first of all throw it on our first element, that is, we write step and here we have a new pair in which we throw the root, that is, our root element its depth will be but now we will slowly pull elements from our steak or add dependencies on conditions, that is, I say that until my stack is lowered, I do the following, that is, 1 game that I am now working with the very top but before my stack, that is, I have a player try not integer and which is equal to the stack. so that is, we pulled out the topmost element now brush to root is now equal to n branches karen etc. that is, the current depth is n. further, I say that I check that if the elements are further, that is, these are the very bottom of my tree or not yet, that is, I say if the pond lift is not equal to null or the root wright is not equal to null, then in this case I will throw in the elements, that is, first I say that if we have something on the right that is not equal, otherwise I’ll add the Huppert element to our stack not equal, otherwise I’ll add the Huppert element to our stack . wright and here there will be a guarantor dex plus they, that is, increases the value of the maximum depth because we are moving down and also if the root lift is not equal to 0 in this case, clearly the bayonet capes element new pair rub. elevator and again car and dps, that is, the current depth + 1, so I is, the current depth + 1, so I is, the current depth + 1, so I will yarn over the elements in turn if we have reached, as it were, the bathhouse itself from our tree, we do the following logic, that is, if the maximum we make the conditions if the maximum depth, that is, which there is less than the current depth in my tree, then in this case we say that the max DPS itself in this case is equal to roott. departure and the value of this root element and max dps in this case it becomes equal to me torrent dex there is such a thing and again I also say that if there is else if dps more precisely max dps is equal to karen etc. ps that is, we are at the same level with this node that we are now checking, then in this case the max dps itself plus equals rub. goal and at the output we return the max dps itself that's all, let's check what we did so we announced three changes with you this is max dips on that is the result of my method max dps that is to store what depth is the maximum icaris index for storing the depth of the current element that we are checking after that we create a stack in which we will throw our elements using dfs that is, diving deep first from the left side and then from the right side we throw the topmost element into our stack and indicating that its depth is but after this we begin to throw elements into our stack, that is, we create a variable n which denotes the current pair of notes depth we say that the current not is the key means and the current depth is its value after this we check if there are more nodes lower than the current element if they are we again we still put them on our stack while increasing the current depth of this but up to 1 each time and when we fill it all up, that is, when we already give to the bottom, we will begin to rise and count our amount, that is, the game what if the maximum depth that we In general, we found in our tree less than the current depth of the current one, but before then we say that the max added is equal to the current element at the beginning, and if the depth is equal to that is, the opposite side, we have reached this level, then we sum up these values and at the end we return these values and at the end we return these values and at the end we return the result, let's try to run this solution, check that everything is correct, we see that on the current data set everything worked correctly, that is, what is drawn here, let's try to bend this solution for all other options, we see that everything worked, everything is fine, that is, what is the complexity of the time complexity of this solution from n so we still need to visit each of the mods and difficulty from memory is at each that is, one case is the height of our tree with this we end the video I say goodbye to you until we meet again
|
Deepest Leaves Sum
|
delete-characters-to-make-fancy-string
|
Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 100`
|
What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest.
|
String
|
Easy
| null |
338 |
Jhaal Hello Hi Guys Question Keep Someone Today Is Counting Bags And It's Really A Good Question To Saunf Dost Wa Banner NDP Jewelers To Get Your Concept Clear In Which Manipulation The Right Question Is Headless Given In Pieces And They Need To Return Arya Answer With Full Length Inch Plus One Search For Child Abuse From 05102 Subscribe And I Will Contain Number One To Three Letters In 3D The Witch's Going To Canteen Dabane Representation Of Its Number Ranges From 02201 And To Write The Value Of I Go From 02 That Brother Resolution Test 90 0.1 Nothing But One And Co 2010 Right The Number 0.1 Nothing But One And Co 2010 Right The Number 0.1 Nothing But One And Co 2010 Right The Number Of Ways In This Point Presentation In Jio Phone In This Is Mines And Individuals One So They Are With Different 2051 With U Flash Lights Of Cost For You Need To Understand What Is The Question Asked In Left Right to see the second exam plus one beautiful its sir value of nh57 journey to return energy full dixit death sentence amazon tension key from 0580 12345 newly created see the value of abuse from 025 pass will press representation for this number 0320 formats water lift tools 1043 Is vansh right to three for lips 0091900 number-10 in wave number-10 in wave number-10 in wave and pintu itna thing but one increase to right in 14.5 is against to ok should contain in 14.5 is against to ok should contain in 14.5 is against to ok should contain sapna arya 2002 and if there are in the number of cases where is equal to three rights which contains a Number of we subscribe to meanwhile I in Tweet - Representation and meanwhile I in Tweet - Representation and meanwhile I in Tweet - Representation and bank account number of what we want and stories in two years time complexity of this approach with nothing but of n * off login wife very much of n in of n * off login wife very much of n in of n * off login wife very much of n in tears into liquidation the number of But In Which Is A That Is Nothing But Of Law Is Right How To The Time Complexity Of Converting Animated I * Is Wire Representational Animated I * Is Wire Representational Animated I * Is Wire Representational Goodie Of Lock I And Of Lock And Sons And Its Largest Number India The Time Complexities Of In Law Can Not The Question Say Winnie To-Do List In Near Time After Any To Say Winnie To-Do List In Near Time After Any To Say Winnie To-Do List In Near Time After Any To Tomorrow Morning Note DP Is Nothing But Computing A Joe Alarms Problem Music Of Already Computed A Small Uchcha Problem Write And Battles Watch Your Dear All Are Considered I Want To Computer Number Of But In I Go To Chhid Behavior Dpr Abs Which Already House Number Of One In Numbers From 0252 Computer Answer First Six Will Be Not In Order For The Intuition Left Right To See Depression Test Se Is Wave 200 Gram Two Things To Be Difficult to 20 Regarding last date of birth need a presentation of his life but also for B.ed also this my life is gold for B.ed also this my life is gold for B.ed also this my life is gold channel life big points i scheduled on friday 1051 one message that this number is even time a b c d a cause notice For The Best Open The Lost With His To Do I Want To Tighten Previous Numbers For Twins Reminder Wendy Divide By To Is Nothing But Want In Lift NGO In Case Of Events Such S One Observation Of Waste Is Remove Sebi That Sindh Volume Of My I Changes to I like this co tight basically a what are you doing this were right shifting the value off side vansh suryavansh 108 10 is film the last date den apne wi-fi bellcoms equal to aaye baitho apne wi-fi bellcoms equal to aaye baitho apne wi-fi bellcoms equal to aaye baitho bachchan skin tight and you will happen for any given Is a my is 7 key and minor presentation1 is a broom high feminine interior decoration in that case I am just removing host and removing dress and left with the beginning representation of three notice that in these jhel rediff is the number of once in your presentation for even numbers Atal Lesson Six Fennel and Cyber Law Also Have Been Six Fennel and Cyber Law Also Have Been Six Fennel and Cyber Law Also Have Been Represented Staff I want to write Swaha the number of but in the representation of a bit too which is to-do list of a bit too which is to-do list of a bit too which is to-do list observations in the week and divided into two parts so first part in this is by To key and second patil to left right 16 tools menu item number of bones in yii2 plus the value of gravity safe and bits on bags of I will be nothing but the number of but side to a plus and cardamom with such features in life for Animals Can Ofton Be Doing I Mode To Write Pure Smile Reference Relation Latest From Indore DP Their Cleaning Total 216 Admit Whiteness Defect Without Thing But Being Swamped By Two Is 3 Plus Medicines Palace In This Case Wireless 2000 The Number Of But SIM 312 And Suman Surabhi Tubeless Zero Two Ki And Vinod Dubey Ne Rapist As Possible Nothing But 102 Hai Sir Answers Correct Sundar Chhavi Ke Basically Builder Inside A Piya Are Destroyed A Small Example From The Beginning Flats In This Example If Any Two For Rights Over The Number Of But Sin veeru inclusion condition mein admit saunf protest is nothing but did not sit for bits of what will happen in love with someone will be nothing bits of one by two 3000 class in one month to right surya answer good thing but want is next in bits of To Dance Of But Fennel One Plus Two Want To Latest Dresses And Tears Number Of But Synth Rate 121 Ki Updates Of Three Month Baby House Bits Of Three My To Which Is Nothing But Want A Plus Free Mode Tu Sun Jiseke Smell Of Bun Flight Same Sunni OnePlus Manav Is To-Do Flight Same Sunni OnePlus Manav Is To-Do Flight Same Sunni OnePlus Manav Is To-Do List Life At Presentation Skills While And Before What We Have Its Limits After And Bittu Plus Form On To During Morning 120 Latest Time Members Get Justice Side Effects Want To Achieve This Reference Relation Usain Bolt Manipulation In What to do Subscribe Bittu sleep is nothing but right shift and I have one light every morning Sacrifice can be converted into its off side effect by one and cursed I want to avoid during last Delhi Chief of Mind is absorbed the presentation of the 200 Guddu This Dance Withdrawal Redmi A1 Lite Morning Digit One That The Best Vines And After Ibn18 Lu Time Businessman Is 700 Medicines One And Two Take It Well And With It They Can Represent 20 Minutes A Video Nothing But 0 Always Get The Value Of I And one should develop subscription of i right by one plus i android app a b p news to computer answer is a silent friday co dot bittu questions page setup bits of good things but i want to aplus so come mode on right that they chai motors before p.m. that they chai motors before p.m. that they chai motors before p.m. My Tablet Manipulation Vishal Yadav In This Situation Equal Entry Jobs For Pyun Is Equal To Two Bits For A Bribe Scam By One Basically I Want To Play A That I And One Which Celebrates World AIDS Patient I Want To Write Electronics Switch Off India Basically Reddy Labs K 100 Number 151 Like This Now We Start The Answer Using This Formula In And Morning File Sharing But Will Fight Back To Plus To Write A Jhali Knowledge Spider Sensitive What Happened On Jhal Ok Subscribe 70% For Student C Ok Subscribe 70% For Student C Ok Subscribe 70% For Student C Plus Solution Le Routine C Situation With Vitamin A Place Question And C What Different Points 98 And Your Listen Just Hundred Percent 15 Member Committee Suid In Uric Acid Play Services For The Rights Of Money How To Make A Call To The Question Videos on
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
528 |
Loot Hello Everyone Welcome To My Channel Today's Question Is Random Pick With Vivek YouTube Channel Please subscribe this Video give Ye Aaj Tak High Lifestyle W And Positive Integers Vegetable Oil Describe The Best Of Induction Heater Function With Intense Pain In Next Point Will Be Completed Within This Question To Its First Question A Question Is The Giver Na WWE That They Wi-Fi Describe The Weight Of Index That They Wi-Fi Describe The Weight Of Index That They Wi-Fi Describe The Weight Of Index Of 16 751 Entry Point 10 Video Please Click On Quantity Na Candy Crush Now Android 4.2 Went Back To Candy Crush Now Android 4.2 Went Back To Candy Crush Now Android 4.2 Went Back To Validate Index Good Pick Proportion To The Value of Sanam Vo Bill-2010 Number Android Chances are absolutely low one by four I see them in the video which OnePlus 3 is equal to two chances Injection Whip it is equal to three four that if chances Jewelery pet is 25percent chance one will be pet is 75 On cent and different sorts of death sunidhi journeys from jio phone that in view of one in between the black 06 hua hai point is aap it trans index the induction opposite have cent percent election the question se effective random number to in which is the use of Loot Witch Will Give Me A Random Number Between Zero Two Taking A Torch Light Effect Random Number Between 0215 Multiply The Total Committee For Unity Will Give Me A Value Between 020 I 16 Exit Point From Time To Time And Finally Point Five 14 Years To Now Arvind Look With Two Will Forth In This Area Hai Ki Tubal Pol Khol Do That In This Post Hai So I Will Return Induction Course Intact One Is Associated With This Point And Activities Associated With This Poet And A Composer Tak Hai How I Can Perform This Point Ek Koodi Path Availlan Karna Ki Training Among Us Absolutely 2513 That Sufi Saint Absolutely To Vansh That Every Time Always Keep Adding To Values That Adding To Values That Adding To Values That And A Better End Number Which Two And Will Search To Hindi Spelling That SDO Is Greater Than One Should Be Written Test One A slack take another example to get clear without consent 16 to nine have one to three and four that chances are intense role also pick is equal to one by two chances induction is equal to one and different ones of this app to starting from 0 Is Vansh 64 The Intellect Will Represent This Point Induction Will Represent Spot In Industry Will Present This Post Hua Tha Election Will Generate Random Number All Detail Reason Number Between 021 She Will Multiply Dant Total Song Vishishtha Ko Support 9 May Random Number Vikram 2008 65 Multiply 0.68 Absolutely 2.0 Multiply 0.68 Absolutely 2.0 Multiply 0.68 Absolutely 2.0 160 cc in with support for it will fall in the swift 240 ireland index to the central question i just maintain a prefix our blood absolutely 2518 will search for peth co intercept one is less almost all companies for peth dad i will return index Associated with the British for your suggested salary 16 This Question Select Repeated Again Asked Questions Left in Next Developed in the Text in Proportion Tweet The Match Will Be Equivalent The Probability of Getting Weight Less Total They Will Make a Difference Has a Prefix Amazon Immersion Lambo Nafees Samay Will Be Replaced With OO Hai MS Word Singh SDM Meeting Ali Near The Complexity Will Be Option Hai ABP News Binary Search To In Physical Form Ko Fourth Way Can Simply Take 2.5 Form Ko Fourth Way Can Simply Take 2.5 Form Ko Fourth Way Can Simply Take 2.5 Willow And By Law Will Point To 1000 Will Pointed To Avoid A Ki Lo Plus Hi Divide Why Random Numbers Greater Noida West Oil Modified New Rule Number Two Member Vipin Sood This Question So Let's Move To The Boat Lift And See What Is The Spelling Of A Slap Syrup Code Ki At Line Number For Rediff Inductive Effect Summer In Which Last The Sum Of The Giver With That End Last Printing Ulta Lupin E Want You Are In A Difficult Elements Top In This Page Also Taking Care Of Total Liquid Liner Do The Voiceless Tomorrow High Fame Calculating Vidmate Modified Foods Can Also Make This Question On A Friend I Will Hide And Throw You Light On Your Social Issues And Code Inter Comment Section 2 Dishas Ko DSC Weight Loss Sohray Submit Code Flash Light To Turn Factory At Vidisha Solution For This Problem you can find the dead game khelo that in this video was helpful to you please give it we all thank you so much for watching our video please to forget to subscribe to what happened
|
Random Pick with Weight
|
swapping-nodes-in-a-linked-list
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
Linked List,Two Pointers
|
Medium
|
19,24,25
|
1,726 |
Yes, hello, this is Nagopari from Live Coding. Today, I will solve the problem of tuple with sein product, number 1726 in Litcode. Yes, the problem was also brought from Litcode, and I explained it in the ppt, and since it is a very simple problem, I will start coding right away. Now, the dictionary creates a map structure. Then, ret, where we will output the result, is initialized to 0, and we have to go around the gun gate, go all the way to the erienne enemis, and go around the second gun gate, so in the range, from i+1 to i+1 to i+1 to len. It will rotate to the number of the number. Then we need to create a key. The key will be the I of the number If it is in the map, it is added. If not, it is not that it is not. Now, it is calculated. Then, since it has now appeared in the map, a key value has appeared, so the value of the key is updated appropriately. Here, updating appropriately means that the web If there is no 0 in the key, it will return 0. If there is +1 will return 0. If there is +1 will return 0. If there is +1 because one came out, if there was a limit before that, add 1 to the limit to make two. If there were two, add one to make three, and so on. It is added by accumulation. The reason for doing so is that if the value of 3 when multiplied is, for example, 3 pairs with the value of 6 are obtained, the value is continuously accumulated and calculated. It was implemented in this form. So, after doing all this, you just need to return ret times 8. It's a very simple problem. Yes, if you close the build error and submit, you can see that it is correct. I was a bit stuttering in my explanation earlier, but what are the cases? For example, there are 3 and 4 that multiply by 12 to get 12, 3 and 4 can get an ampere, 2 and 6 can get a pair, and 1 and 12 can also get an ampere. At this time, if we have 3 companies When you put in 12 and get 26, there was one, so when it meets takeoff, the RT value will increase by one. Then, the value of 10 becomes 2. It becomes 2, and then 1 and 12 are added. If we meet again, 2 has been added before, so in other words, if we say 2, we can make a pair with 2 and 6, or we can make one expression with 3 and 4, so it is implemented in this way to handle it that way. I think the explanation is . I'll try is . I'll try is . I'll try submitting the code like this and check if it's correct. I checked if it's correct. If you found today's lecture helpful, please subscribe, like, and set the alarm. Thank you for listening to the lecture.
|
Tuple with Same Product
|
coordinate-with-maximum-network-quality
|
Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**.
|
The constraints are small enough to consider every possible coordinate and calculate its quality.
|
Array,Enumeration
|
Medium
| null |
234 |
Most of them will be the president and I have learned a lot in the English series, I am telling the truth, I have covered all the basic things, here this question is getting bitter, the land from the link list is fine, is it looking good, friend? This is the question of cigarette, it increases metabolism. Now if you sit down to do it properly, then it will force you to think about the liter. You can remove this question and do a little. What three more tips are there and which of these three apps is a dangerous thing to ask? Link to check: Everyone dangerous thing to ask? Link to check: Everyone dangerous thing to ask? Link to check: Everyone knows that this question is correct. How many completes are there? I am telling you in the first interview, this app was asked in adv1 way, it was done thankfully. Baroda concept behind digitally amazing and now to do it. There are a lot of but of course also this tool witch to the Europe what is the best possible case, here in the question you have been given this diet in off and time and work for space so this kind of for elections of always asked in interview. Whether you can do it in space in the oven or not, can you reduce the time from withdrawal, I always request you friend, if you feel that the liquid is not coming then maximum 102 days will go and you will get liquid crispy liter. I am guaranteeing that even a single question from you is going to be covered because I have covered all the basic things. The most special thing about any of my videos is that I feel that people have given feedback. Which will be very beneficial for you, friends, now I am demanding that I always say about everything that if you are watching my videos then watch someone else's. However, what is this, if you are watching my videos then please do your research before watching any video. Learn to attend to your head so that while returning to the stadium, you look up at him to see whether you are able to understand it, whether you are able to turn the canter, whether you are able to code. Every day you keep thinking whether you believe it or not, whether I am assuming to handle you or not, you are a fraud. You must not have done it, I am not lying that there is no fight by lying, till date you do not lie on your face that yes I have applied, I should have known, I have seen it, no, I have copy and PAN card of my house. Let's question this quarter inch, what is ghrelin from pendrive, which I have increased from the front, it will be visible at an increased rate from the back, 121, if we read from here, 121 is equal to f12, then this is proof, yes, this plan is very good, 123 from here. Ok, 1234 to 32000 is not a pendrive, ticket is in one single, read from here, it is equal to elder brother from here, trophy, print, roy, money, profit, we would have understood, we had learned a lot of basics, when C plus seat was the fruit of Allah, we were asked a lot of questions. What happens in the printer, how does it happen, what does it mean in between, read the note from the front, this from the back, so that Vadodara can get the same website in the calendars, if there is a solution for this which you attended then it must have come in your mind. And if you are not getting it means that you are limited, it lacks a little basic, it is always more, comment, I look at the playlist, settings, starting, it seems that this business of understanding, the path of publicity is nothing, after reading your comments. See now he himself is like this in the morning, how good brother has increased the knowledge of Tiger Force brother, new post is coming, I had made a video of a bad road from the Soviet Union and then see if you can sleep in your bedroom, think what you can sleep once. Yes, it's okay, then I thought, brother, we work, but the drivers do the travels, they do the work, they store it in the data in a tractor, okay, so we store its value in the vector 121, okay and we are very good. People can check whether the result is there or not. What is the best way to track whether the doctor is from front to back and the other driver then let's equal the size of Schezwan factor Bittu and I - - Okay size of Schezwan factor Bittu and I - - Okay size of Schezwan factor Bittu and I - - Okay now let's equal or the size vector of Twitter Off I and Backed up and - I - One. If Off I and Backed up and - I - One. If Off I and Backed up and - I - One. If both of them miss match then we will pause. In such a case, what is the value of the person's ad. For is ok, so now it will run till Roop Ka. The loop will run from zero to pack. Size is vote 4 after head Chhota Kumar Hey friend will go till the first stop In the case of zero that a computer who happened and is kitna point to for - i kitna hai zero minus one meaning that for - i kitna hai zero minus one meaning that for - i kitna hai zero minus one meaning that thin but this factor 034 will compare 034 looks equal Is it straight then you will compare it and what will come in it For - 52 - One is compare it and what will come in it For - 52 - One is compare it and what will come in it For - 52 - One is that 2.1 and toe will be compared but and back and that 2.1 and toe will be compared but and back and that 2.1 and toe will be compared but and back and front will be compared and then moving forward, back to front will be compared. Where ever mismatch has been found, now return it in this. Will give and if not found then will turn then is this a solution from feet no why development in this that of any space is used and what we had seen in for questions that we have to figure out such a solution that if one space is found in it then it Balance good means that at least show it in the open space, brother, there is some women's solution, he did it in the interview, he said, yes brother, he knows how to get up, how to do the registration work, Debit The Indus knows how we will do it, now comes the reality. The work of the list is okay, it is important to do the questions, it is important to submit the questions and see and green, this is not your correct way and they strike enter and try to know how you could have solved it better, so let's understand the question, then better. What do you think Just Understanding Knowledge 121 What we will do is we will deposit the middle point in these English terms and fold the middle from here and after that we will reverse whatever list we save and replace it with not and then compare first position. Sit down, what did you say? I don't understand. No one is explaining anything. C 121 I will give it to you. We were assuming that the media is very good and when * came, it is and when * came, it is and when * came, it is half back. This is America. What is the note of half back of it? Direction is whatever hair is, force it to reverse, this became and this became ultimately, if you look at it well then what is the first half, one and two and what is this second half, one and two, both are equal, we will compare, we will do the same in 2009. Okay, what is our problem now that we know that this plant has to be compared by taking a light and the office person has to compare it but we have the option of going forward from below, there is no option of going back, I don't understand this in my mind. I thought that turn the back half upside down and then start comparing both of them. Davar Idea which many others might have thought of but its implementation is a bit tight in the code. Why Vikas is new to us, we are learning to code, okay? So now I have made it clear while talking and it is of size and the look of the talk is 12321 with linguistics of size, then its media will come. Okay, this is the meeting and I decided that now look, when it will be deeper than the other, then the butt will be middle of the office. In one, when we will do the middle point and when we divide it into two lists, then one will have more note. One note is more. If it is first decided that the front part is the front part and if one note is to be inserted in it, then it will be like this. Back it will reverse you what was one and two ok end is what is it 123 so ultimately what is this made 1234 what is this made this 1234 that this is what is your lineage end to I said school se less love kiya same hai is this computer did city No need to do last comparison. Vikas model will have equal share in both. Next Saffron will see that one is null and one is normal, then we will add penis and cut it. Okay sir, David was stuck in the computer while doing the comparison. Exit Polls I am understanding, now come back to the target, please comment on the video, then we will learn the method of doing middle point, but first we are changing the way of calling this question a little, we will understand the logic of each part like I have done here. I showed you the box, there are questions in three lessons, first send the middle, then do the reverse and then compare on the first half and second. If you are okay then we will do one lesson, you will see the logic and after coding it, let's free it from here, so what did I say in this? Did yes, explained the logic, take part one lesson, will continue quoting the lesson close loop, the first point comes, remind, the best way to attend the meeting, listen, Elva Edison would have been the name, I forgot and tell me, I never used to know, it was shown how Pankaj Solve what I said, one slow and one head, middle fast, 21 fast and one slow, point both of them here, notice the slow one, move it again, slice less bread from both sides and run the slow one at normal speed and the fast one. Double play again. Okay, if fast will go in al or fast will become national then we will stop and where slow will come, that is our middle earth C. In such a case, what is 121 slow here and fast is and face means Shoaib. Meaning fast, I heard from people who ran single phase fast food and ran it on it, okay, so let's go here, first here is fast tap, no fast, national, no, we will not get together, slow came here, fast came here, ok on channel, faster brought rupees, slow. Here is the ultimate where slow has come, it has come to us, I am you, who is us, those who have taught us before, look at the settings of Liquid's playlist, we are better able to understand how it is doing, I feel like doing midnight, just the way. It turns out that slow is normal speed fast food like pav where slow will come and stop at the end and if we meet then the middle has been found very good. Next if we will talk in this cord case and especially it means that if your penis is only in this. And from the number of note, that lower part, Yaara Clock of Ministers started, put the part special, the next one of fast came on Facebook, if it did not seem, it stopped in the open loop, then the one that came in the middle, where it got slow, where the slow stopped, our order. Middle is very good, I have written here slow is power metal and playlist, now I have become a quad-core editor, I have taken the and playlist, now I have become a quad-core editor, I have taken the and playlist, now I have become a quad-core editor, I have taken the steps that here we have supported whom in a party, first of all, what will we do on digital, will we joint the list, mod, slow, equal to head and fast. Equal head ok now what will we do while fast not quite fast if not equal to null and end fast ka next9 222 Lalit America will run this world slow speed and fast will run fast speed ok and in the last and we are left with He was killed slow, so this year it is medium, it has been confirmed that no one will see any problem that we have taken the last one, so it is very good, so all of us here, whatever we have written, until the decision is taken. Next thing is that we will join it, what is all this, understand that we have to reverse this lesson, it is slow, we have to reverse this lesson, it takes us events, this number here is going to be equal to this folder, I will tell you. I am coming and showing the relationship between the two, so how are you running the code, students, you may benefit from it. Okay, what did we mix, what did we do, we did this devotional stuff, what did I say, make it temporarily unavailable, put local next temporary, I have come, slow connect. Followed by doing the next of the middle crops, do the previous one. Now this dry one is the next one, which has to be pointed, we will grate that point and point it with the tap, which is our previous, we had sized the previous one with the tap. There is no problem here, no one has any problem, so now we have it here, we will get this movie, here what we did to the previous which is pointing to it, what did we do to the tap, now we changed the slow on the previous and attempted Tamil Nadu If you put slow then slow put it in the previous place. Hello and put temporary in place of slow, then here comes the previous. There is no problem in slow coming here. Now slow is anal. The value of slow is last but those who are next are the ones. If the tap goes back then we will press Ismail. He came out and we have put it outside that the next one on the clock is controlled by the printer, which means that now wherever it is pointing the tap, break it and Leave it with this previous one, so if we add 's' then for the ultimate it will be ' add 's' then for the ultimate it will be ' add 's' then for the ultimate it will be ' A', 'Okay' and 'One has been there', 'Every pass' has become two A', 'Okay' and 'One has been there', 'Every pass' has become two A', 'Okay' and 'One has been there', 'Every pass' has become two lists, one has become 'Finally one' and 'two lists, one has become 'Finally one' and 'two lists, one has become 'Finally one' and 'two here' and one 'This has become one and 'toe' for sure, no here' and one 'This has become one and 'toe' for sure, no here' and one 'This has become one and 'toe' for sure, no problem for anyone. No problem, let's write in the exam, don't worry, how is it happening, Sapna will understand, in this case, how are the festivals and other ones, what are the slow ones, here your middle of course is included in all the cases, the middle note will come, but this is the decision point. When we had decided that we should keep one more note in the front part, then what we had decided was that check this case and release the phone's slow front, slowine1 is not hurt, so what did I do? Sloka has been made one ahead, there is no problem till now, there is no problem, the previous one is Aloo Fresher Nurses Size Kya Azhar, what is Lok, whatever is there, it is not a tap, but if Sloka is next tap, then you will not be able to access the files, it is okay, the direct level point. Will run that if you post the slow connect as previous then it is correct that the one who is pointing to it next will press it and will put it here ticket on tap then subjects people have appointed national flags development by taking the previous Khilta open so here is the final list Number apna vansh 2nd become three now we can compare it ok next chapter note that means if we have some idea what we are doing in the murder case and what to do in it that is middle let's accept slow here So that a party of one will be formed and this will become a part. Okay, what have we done to reverse, then by doing reverse ultimately, the slow stops here and after making a list of ours, let us name it as fast track. Its Namdev fast, just everyone's name, its Ustad Singh reference, there is nothing fast and slow, there is no problem, till now we have done the code, we have proven it till now, what we learned was to do the middle point, we have to fold it, now we have to reverse it, fold it a little, if China is being discussed in the session but at the time I thought how to order then mute the slow completely because they want there is a note star in the text on the front, the code to dance by and revert is every For someone, we got the metro from here, we changed it to day and when finally its index will come, after doing day, it is pointing slow, okay, the first one of this one is kept intact, I assume it is fast, meaning that if it is this. It should be seen that Ayodhya came back far away in English, what is one two and three pointing to it? Fast, okay now scientists have come, one and two is pointing to it, okay, it is just a name left, now that order is not English cancer. Now we court him, he is given a pizza gift for a month, if it is considered fast, if there is hardness, we told him in the award, what to do was to set slow, we are traveling ahead and gas, if fast is not equal to tap a and they are fast. Kajol is next, that tap has come, what will we do in this case, will we shift to this world? Next, on exploitation, just make a list, Dad, it was written in it, we will put it in previous, has the party been nominated on exploitation, will I talk about Luthra? Till this world and hereafter is next percent then boil slow and slow next so simple night satta matka can be muted and put in it that in the first store we will put Mata temple type temporary sloka next step what was that sloka Next is pointing, point to it, is n't it previous, put it in slow and slow, put it in time, so simple ticket, and in the last, everything is done, until only if the next verse of the verse is tap 50, if Not Equal To Na brought by applying this type of which people will be joint next, social with previous and what will we do in the last, will we put in fast, what is the gold channel, this is us in it, what is our next brother fast, got it every year, now We will compare, it is very simple, as long as slow is nominal and fast is also nominal, there is some element in both, we will compare, if the value of slow does not match, we will return the value of fast, we will extract both falls and apps. What is the weight of 5 ton in this case, both of us have matched, it was a match that we will move ahead, now first has come here and slow has come here, what have we matched, both of us have matched, we are very good, now slow has come, tap back and fast here. Okay, when both of them go back, we will brake the tractor and return here. A proof notification, if seen here, fast here, protect against changes, the other one is super fast, compare it. If seen, I am the first here, the day has come, here is slow. When it came, I sent the computer, then it's okay, now both of them will face next, then tap this and also this tap. When both the drains have come, the best one has come, then he takes it and will do the search. So come, you must have understood this as if we To rob the pen and duck deposit of both and both are half of one, if it is seen in the case of another, one has more which does not matter, then the expenditure towards both of them will be matched first then if they match then it is okay no. If this is done then we will fold the pension and move ahead in the match, then we will check both of them, otherwise I will move ahead in the match with this point. How long will it take for both of them to have an element percentage, if even one goes out, they will demonstrate because We will be matching the rest of the things, pin code it, finally, it is very simple, if we look at it, then we will boil it until both slow and fast are president, so what will we do now, the gas slow value is that if not matched, then fast key will be added. By value, we will wear the falls, okay, Apps slow is equal to slow, next and fast is equal to fast, next will return the tax, now let's show that there is no mistake, if there is a mistake in writing something so big, then subscribe, now we have to compare both of them that this I liked it and could have done more if you take a little care that I will show it to you. I am working on writing it in English. If you really liked the video then please post it in India. Soda, I liked it was good. Padha raha hai to mera audition kaps hota hai and aapke achcha karo ye main office chahta chahiye but I think you should also take care of Baroda I need your support to jhalar 10 min tak dhak hai
|
Palindrome Linked List
|
palindrome-linked-list
|
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_.
**Example 1:**
**Input:** head = \[1,2,2,1\]
**Output:** true
**Example 2:**
**Input:** head = \[1,2\]
**Output:** false
**Constraints:**
* The number of nodes in the list is in the range `[1, 105]`.
* `0 <= Node.val <= 9`
**Follow up:** Could you do it in `O(n)` time and `O(1)` space?
| null |
Linked List,Two Pointers,Stack,Recursion
|
Easy
|
9,125,206,2236
|
1,047 |
hello everyone let's solve today's lead code question remove or adjacent duplicating string we are given a string s and consisting of lowercase English letters this question wants us to remove author Json duplicate letters we are going to do this duplicate removers honest until we don't have adjacent duplicated letters let me show you an example we are given string ABB ACA and because BB is adjacent duplicated we remove these letters and then strings are concatenated then a and a becomes adjacent and they are duplicated so we remove these A's again the final string becomes CA we can solve this problem using a stack we are given string as and we have a stack we are going to iterate string s and we'll check each character we can add on if condition to weather those text top is the same character or not if we have a non-empty stack and the if we have a non-empty stack and the if we have a non-empty stack and the current character and the top character are the same we pop the top of the stack if not we push the character on top of the stack in this second example we add character a On The Stack and we add Z On The Stack and we add X on the stack but this time we have another X and it's the same on the top here so we pop X on the stack and reiterate the next character Z is the same on the top of the stack so we pop C again and we trade the next character y it's not the same on top of the stack so we push it to the stack and we return the final string a y from the stack okay let's call it we divide a list variable SDK stands for a stack we iterate the input string as on each character C if we have a non-empty stack and if we have a non-empty stack and if we have a non-empty stack and its top character is the same as current character C then we pop the top of the stack if not we push the current character C on the top of the stack after all of the iterations we make a string from the remains of the stack and return it these programs time complexities because of n because we process each characters in The String once the space complexities are so big or when because we use a stack that can grow up to string ranks n I hope it was helpful and I'll see you soon bye
|
Remove All Adjacent Duplicates In String
|
maximize-sum-of-array-after-k-negations
|
You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them.
We repeatedly make **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**.
**Example 1:**
**Input:** s = "abbaca "
**Output:** "ca "
**Explanation:**
For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ".
**Example 2:**
**Input:** s = "azxxzy "
**Output:** "ay "
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
| null |
Array,Greedy,Sorting
|
Easy
|
2204
|
199 |
hey what's up guys is Nik why'd I do tech and coding stuff on Twitch in youtube if you want to see any of that just check the description I have everything there I do all the Lika problems so I have a playlist and I have almost all not almost all of them but I have a ton of them on my channel so just go check that out if you like getting these explained to you the one we're doing right now is called binary tree right side view so given a binary tree imagine yourself standing on the right side of it return the values of the nodes you can see it ordered from top to bottom so you can only see the right side of a binary tree and they want all the nodes from top to bottom so like 1 3 4 now what I didn't realize until I looked at the solution is they want what they technically want is all of the rightmost notes so you're not only looking at the right side because you could be looking at the left side as long as it's the rightmost nodes so they don't technically want the just the right side they want the rightmost nodes at each level of the binary tree so just be aware of that when you implement this solution also I looked at these solutions down here for DFS and BFS obviously all you have to do is Traverse to some kind of traversal and grab the rightmost node at each level which this likes these use hash maps to do that where they measure depth we've done problems like this and then basically just only put the right the rightmost node in if you check the hash map and at that current depth there hasn't been a node put into it yet and you recurse down the right side so you can do it that way actually what I found interestingly enough which I think to be the best solution is this reversed level order traversal you're basically this is just a cleaner solution in my opinion where you just basically have these data structures and you do a level order traversal except you visit the right node first and then the left node first and you add these nodes in and basically you have a for loop and let's implement it right here and you'll just explain it as we go so what we're gonna do is we're gonna have a list of integer which is what we're returning we'll call this result is equal to you ArrayList and we're also gonna have a queue of tree nodes called queue which we doing a lot of problems equals new linked list and then we'll do cute I'll offer route like all these other problems too if root actually first will do we'll do a check if we're equals and all like all these problems we return result because then we have nothing to work with here okay that's fine now all we have to do is while queue is not empty then we will do a we'll get the size of the queue and this is basically why I think the solution is better so you get the size of the queue and then all we have now is a for loop so it's basically we're doing a level order traversal a reverse level order traversal we go right and then left note on to the queue and we pop a note off each time except we have this for loop right here which goes from 0 up until size so Y is less than size the increment I and then when the only reason we do this is that so we can get the rightmost note at each level so each level we're going to do this for loop as we traverse and if I is equal to 0 that means we have the rightmost node because I will be 0 when we have the rightmost node because we're doing the level order traversal in Reverse if I equals 0 then all we have to do is well first we'll pop off the current node like list node current node is equal to Q dot pol not pop up but pull the current node then we just do current node dot Val gets added to result so results I add current node dot Val so we have the current node dot Val to the result and then we obviously do queue if the current node right value is not equal to null we were add the right node to the Q so Q dot offer current node rights and same thing for the left side if current node left is not equal to no we offer current node dot left and then all we do at the end of this is just return result and it should work first try and then I'll explain it one last time q dot pol what's the problem here tree no cannot be to convert it into list node sorry tree no you have to make sure I'm getting mixed up I'm doing all these problems like a million problems today so okay there we go see how it works there we go so basically what we're doing is we're adding the right notes to the queue first so when you add the right node and then the left node to the queue the right notes gonna be the first to come out because the queue is like a line to get in at the back and then the first one in is the first out FIFO first in first out so you get into the queue first the right node gets in first so it's gonna be the first out so we have the right node coming out first and since the right node is coming out first the right node will be pulled the first in our when we go through our for loop from the beginning of the queue size to the end of the queue size while the queue is not empty so when I is zero that means that's the rightmost node because we put the right notes most note in first so when I zero we just add that value to the result so at each level we're doing this for loop and each level when I equals zero we just add that value to the result and we have this resolved way at the end which just contains all of the rightmost nodes at each level and I think that is one of the easy most simple solutions compared to bread for breadth-first search and to bread for breadth-first search and to bread for breadth-first search and depth-first search where you're actually depth-first search where you're actually depth-first search where you're actually having hash maps and kind of keeping track of the depth and doing get calls at each level I like the solution a lot better so let me know what you guys think of these solutions what's your favorite and also link that one that where I got this from EIU Lee I think or something like that I'm gonna link this solution in the description so let me know what you guys think in the comments let me know if you have a better solution and thanks for watching check out the other videos see you guys
|
Binary Tree Right Side View
|
binary-tree-right-side-view
|
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_.
**Example 1:**
**Input:** root = \[1,2,3,null,5,null,4\]
**Output:** \[1,3,4\]
**Example 2:**
**Input:** root = \[1,null,3\]
**Output:** \[1,3\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
116,545
|
110 |
Hello friends, welcome to this channel, today our day is 84 T code challenge, so let's go straight to the screen and start today's question. So what is today's question saying? Let us understand the number of today's question. The name of 11 question is Balance Binary. Look, first of all, this question is not very important, here it is given in an easy tag, but this question is very important and many concepts are going to be cleared from this question and we are going to discuss about Balance Binary Tree. We will definitely do it, but our Height of Binary Tree question is also going to be covered here, okay because I had not made a special video for Height of Binary Tree, so in this video we will cover it specifically, okay, so first of all let us understand. What is a balanced binary tree? Let's go straight to our board and here I have made two trees for you. A balanced binary tree is a tree whose every node follows the rule that its left is the difference of its left height minus its right height. This is the difference which is it should be less than and less or equal to which means it should be less than equal to which is the absolute difference of left height and right height means it is absolute a twenty and I write it as absolute difference which is This means that the difference between the left height and right height of each node is very important for each node. The difference between the left and right height of each node should be lesson one, meaning it can be zero or it can be one. There can be only two values and nothing else like if we check this one here is our root node, what is its left height, one, what is its right height, two is the right height, so if I find its difference. So what is 2 human or not? So if this one is true then it is fine. Right now we cannot call it balance because we have to check every node. Here if I go to four then this one is true then I go to four. If I take out the left and right height, what will I get, the left side is also zero, the right side is also zero, g 0 minus 0, what is zero, then that too is falling in the category of zero and one. It means the root note, so it means all the leaf notes are there, they are obviously the balance of all of us, so I can say for this also and for this also I can say, yes, obviously, but what about F, now let's check F on its left. Find out the height and find out the right height. Left height is one. Right height is also one. Left height is right height of both one and one. What is 1 myve? So this is also a valid one. So if all its notes are balanced by following the logic of binary tree, it means this. If we follow the following rule then this is a balanced binary tree then we can say true for this is a balanced binary tree I hope so you understood the definition of balanced binary tree but what about this tree let's check this tree ok this is The tree is a balanced binary tree. No, see, let's check all four nodes. First of all, we found out its left height and right height. What is the left height? Tooth and tooth are left height. Our right height is also our th. So 3 minus 3, what becomes zero. So this node is following us. Okay, this node is following us. This one is the true node. Are all the other nodes also following us? Let's check for this. If we check for this then They don't put ticks in it, they are just checking by putting circles like this, what is left hide, what is two right hide, what is zero, right hide is zero, what is its 2 minus 0, what is t and this is not failing property, so right here if someone If even one node is not following this tree, then what will we call this tree? It is a false tree, it is not a balanced binary tree. Okay, so I hope you have understood very well that in what way we have to balance. We identify the binary tree, so like we have identified the balance band tree, how will we identify a tree, see how we have to approach, first let me go back a little so that this thing of ours is removed, okay So what do we do for this, let's do a little bit, for now we will assume that we know how to calculate the height function and we have some function which can calculate the height for us and give it. We will discuss the height function in this video. For now, you just have to zoom a little bit with me that we know the height function, how the height is calculated and we have a function which calculates the height function for us, so what do we have to do, see, in this we will discuss two approaches, first. We are not going to code with the approach we are discussing. We will code with a better approach. What will be the first approach? We will go to node 1, travel all the way, take out the left hide, take out the right hide and then check that we have got the left hide. Whatever will come out and we will keep checking the difference of absolute difference left height minus right height and if it is greater than equal to two then we will be greater than one then what will we do from here we will return false otherwise we will check further then this We will go to note 1, in this we will ask for left height and right height. Okay, we will approach in this way, meaning here also we will go to left height and then right height. So for every node we will have to ask for left and right height. Okay, so I have given the code for this. I had written it for you guys, okay look, here is its code, okay, so I said, if we do this for this node, do this, see how it will happen, first of all, don't write, we have used left mouse button for this. Left Hat is ours, we have come out, Right Height is ours, we have come out right. Now minus w is our n and there is no greater than w, so we will not return false from y, it means that our y's nut is absolutely correct, right node is absolutely correct, we have ticked it. Done here, okay, what did we do after this Bullion, now we told the left note that you also check, then I told the left that you also go to check, then left, now answer one will come from here, look, answer one will give me this. Okay, so now the left is checked, a new function is called for the left, it also calls its left height, right height, its left height comes out to be zero, the right height comes out to be zero, the difference between the two comes out to be zero, which is not greater than one. So what did he do? Now see the answer. Not only did he make a return fall from here, but he also called his left. Now look at his left because it is tap, his left is also tap, his right is also tap because he called his left. And called both the right ones, both of them gave true answer, this one also gave true and from here also true came, then if both its left and right are not null and after that, true and end of true, what will be the answer one? Okay, so something like this, answer one got true, third answer one is true, answer two means the right tree is saying, you also check, so it means this one also gave true, that's why it is true now. Look, get it checked, now the answer to answer two will come from here. First of all, for six called for its left height, which is one, and right height, which is one. It is okay, it means that A is being called again and again. I took out both of them. Will the difference come, will it come to zero, if not still then what will happen, this will call its left for answer one and it will call its right for answer two. Now look at the single note, you know the balance. If it is true then it will represent true two, from here also one will come true, then what will come in answer two also, true will come because both are true, now answer one and answer two are also true, if it is true for both, then finally This one should also be true, this question will be of this type, okay, this question will be of this type, but what is the problem in this, it will not be submitted, it is not that it will not be submitted, submit, but now see how much work we have to do in this. How many times to do it, why did we have to do it so many times? I went to every node and found out the height. Now the height. I went to every node and found out the height. Now the time complexity of finding the height is and because we go to every node and find out the height. So what is its time complex? So, ultimately, what is our time complex? What is our time complex of this code? This is the time complex of our time complex of traverse because we are in every If nodes are diverging then of n * or we are in every If nodes are diverging then of n * or we are in every If nodes are diverging then of n * or of n s, then this is not time complex o of n s, we do not have a good time complex city. Is there any way we can do this in off n, so I can answer this. If you ask me, I will say yes, we can do it o We can do it in Off A also, now to do it in Off A, we will first have to understand our height function because the solution of Off A is hidden in the height function itself, okay though. This is the solution of this question, this will also be submitted, okay, now we will see the height function, which height function is used here, we will also see the height function, we will understand the same height function, now the right time has come, so I am the first one. Where if we give height function then this is our height function. Look how height function is written. If we said simply that if our height is null, root is null then return zero, obviously if it is not null then height will be nothing and what we have said here. He said, bring the height of the left, bring the height of the right, meaning see what is the height of the left, what is the height of the right, we have got these two heights, which of these two is the maximum height, what is the max height, then the total height. How much will it become a tooth, okay, in this way, our height means a general perspective, now we will dry it, then we will understand well why I was saying that the height function is very fine, so we will get its height. If we take something like this then we will get its height. Now look at it by drying it a little. If you understand this height function and how it is working internally, then our question will be solved very easily. I know, the video is getting a bit long. It is a very small question but it is very important to understand. It does not matter if the video gets bigger, it is important to understand. First of all look, I would number this line A & B & A & B & A & B & C. First of all, let us look at this note. From here on the note, it said, call on your left, meaning AA, call on here, okay, now is this a tap, no, we are checking the six of the six, look, we are checking the six, now the call is on six. Six called to his left. If Six called to his left then it was Null. What answer did the A line have? If Six called to his right also then it was OK. Sorry. A would have zero because if it is Null. So what comes zero, what also comes next to B, zero comes, now I have A and B meaning left and right height is zero, then what is the maximum of zero, what answer did the zero and C line return, see what height of six was one, sis itself. If there is only one node then it will give only one, so what answer did Lee get? See what I wanted to show is that each note is getting its own height left and right height. But look again now when we call for its B line, its B. For this line, call B line tomorrow, we have now controlled it, this third note has a root tap, if not, then now its A line will also get a call. A line said, brother, you call this one. Now look at the line, we can guess the leaf notes which means we have just seen how if we write one white note, then the answer is one near the A line, one near its B line, where will this B line be? There is one leaf node, so obviously what will it return? It will return only one. Okay, this one has also returned one. Look at each node here too, what has it returned? It has found the height of its left and right. Now what will be the maximum of both of them? The maximum of both of them is one. Look at the float, if you get the float done for yourself, then it is done, so the height reached from here is T, it is okay, something like this, G means, one has come to the left height, one has come to the right height, two, what is the maximum among the two? The maximum out of one and two is two, so the answer becomes 2 + answer becomes 2 + answer becomes 2 + 3, so this was our height, we had to check it in this way, but we took the height, why did we take it? Look, here is the main thing I told you in between. Told that every node has its left and right height, find out the height of left and right, these also have their left and right points, these also have their left and right, every node we have left and right and we have a balance binary tree. I also have to calculate the left and right height for each node. Okay, if we have to do this, then if I do some chain here in the height function, then what can be my work? Yes, I say yes, to understand how it will happen, let's move ahead. In the code, first of all I have to write the height function. I write the height function as public int. Do not tamper with the height function. Write the height function as it was. It is okay, after making some changes inside it, I used to return it as int. Let me return, I say, if our root is null, then return zero, obviously it is correct, now I said, get int left height, how will the left height be calculated, just call the height function and call root dot left. Do this from here, after that call int right height and call the height function again call it with root dot right and now return math dot max find out the max of both, after finding the max leave height comma. Write height and whatever answer comes in it. If you sent it then we would have found out our height. Otherwise, we would have found out the height. We would have written 'il to height' function and even called the height function. written 'il to height' function and even called the height function. written 'il to height' function and even called the height function. Every time we would have got every answer. If there will be a left and a right for this, then do n't I make a Webble on this, which I made a global Webble, say I, or do we call it the balance factor, I kept the balance factor two until we kept the true balance factor true. And as soon as I got left and right height, I said if left height or math dot absolute left height minus right height if it is greater than one then you false my balance factor. Give it and return it from here Return my balance factor to the balance factor Okay, maybe not yet, some may not have understood a little bit, some people may have got it, some people may not have got it, but no problem, now I am here. Now we will run it, let's run it once to see what it is saying, okay, so look at this chain, now first of all let's talk about its time complex function which runs in o of n and we have Just put a check here on the balance factor and if we do n't do anything extra then if its time becomes off then o offv * o1 then what will happen to me o offv * o1 then what will happen to me o offv * o1 then what will happen to me o off n will remain so our work is done in o off n how come it didn't happen? I didn't understand, keep patience for two minutes, everyone understood, okay give a little time, everything will understand, okay, those who have understood, they have already understood, those who did not understand, no problem, keep patience, when you have understood this much, then you are till here and this much If you have understood, then you will understand even more will come, it will come, okay, just trust, okay, so now see, let's not make a tree, four, we said, five, keep it here, six, keep it here, seven, and okay, let's keep it here. We are fine, this is the only number of trades, now we have kept the balance factor and balance factor as true on Y. I will make both of them true, one in our balance fee and one in unbalance, we will make true in both. First of all look at our height call now. You will say, why did you take out the height? Hey man, the height was for the balance vector, we don't need it, okay, first of all we called the height, okay, there is the press button, here is the control, now there is the control, okay, let's say A line. Let's call this the B line. Okay, let's call it the C line. And this is a check with us, so we will do it when the A and B lines will run. From here, the A line called, who is on our left? Okay, now on our left. Left will also call A line. First of all, because right side is not null. Look, because if left is null, then what will it give? If it gives zero, then it will call B line. If B line will be called K, then what will happen if root dot right is called? Okay, right has been called, right will also call his two calls a and b, but what will these two give him, one will give him because there is one here, so he will give one, okay, F has given his zero and one, okay he has given zero and one, now look here. This will be checked from math.absolute. here. This will be checked from math.absolute. here. This will be checked from math.absolute. First of all, if 0 - 1 is greater First of all, if 0 - 1 is greater First of all, if 0 - 1 is greater then obviously one will come in the absolute value. If 1 is greater than 1 then it will not be able to fall. Then again it sent the height. Next it came here and It has sent the height above, it has sent its height here, so what will it send the height, it will send the height to two because one got the height from here and from here one came to A. Okay, so look, right now we have found the height only but This route of ours is checked. This one is also checked. Okay, now see, it will call its B line. Called the B line. Now it will call its A and B lines. Look, if it has called on A then If there was a tap on B then it was a tap. Obviously if there is a tap then what is the return? This one will also get the answer of zero. If both of them have zero answer then here A and B have come. If the B line is already running, then obviously the balance factor will be a my b 0 min 0. What is 0 greater dan w? If it is not there then it could not fall, it just returned the answer zero. What is bigger than zero p? This also returned the answer, now look very carefully, it is okay, A and B line is one, here also there is no, okay, 1 is my zero, again A and B line is checked again, see every route is checked. Every nut is being checked to see if it is spoiling the balance factor. 1 What is Meave? Returned the height from , Returned the height from , Returned the height from , which we do not need to go because we are not finding the height, so its height which was returned to, look, its height was only 2, okay one minute, from y came t and nut and wpsy. When I returned, its height was not the maximum, so it went like this, but about if we take a case where we do not have balance, then once we take this type of case, it is fine and sometimes we take this type of case. If our tree is not in balance then how can it stop and something like this is our tree. Again we created a balance factor, so we created a balance factor whose value we kept true. Our tree was the last time it was true, so the tree returned again to the maximum. First called height is still route tap, there is no our call right now, but they said, let's convince the left's hide in the left's hot, the left panel tap is lying, if there is a tap then what will come near the a line. If I call this A and call this B, then the answer that comes near the A line will be zero, okay, zero has come, very good, now it called its B line called here because there was no root tap. So it will also call its A and B lines, a will call its A line, it will call its A line on tap, it will obviously get zero, its A line will give zero, its B line will then call again here, every line is getting completed. Continuing to circle, the B line again called to the right. After the call to the right, it again called to its A and B. This is also a tap. When I called A, I got zero answer. From tap, I got zero answer. Obviously zero answer from B also. If both are zero, then look at A and B. Till now, only this one has been received, then chalk A and B line for this. If the line is running, then left G. Mine ji could not make this mistake, it returned the bus, returned a height near B, ji, I hope you understood, now look, the control has come to it, A and B line has moved, so now on Y. Checked it was minus 0. Greater than and it does not happen. Otherwise it could not spoil the balance factor. It just returned its height from the C line which was its height. Now look carefully whether this one is correct or not. Now butter will spoil the A and B lines on Y. Butter is any minus 0 greater than W. If yes then set the balance factor to false. See, this node has spoiled our work, meaning here we have spoiled the balance factor. It was also found out that it has also returned its value. We are not concerned with the amount that will be returned. Okay, after that below we have found the returned balance factor. Look at the value of the balance factor. Okay, so we have returned the false value from here and see that Look who was doing its falls, look, from here the left height was zero, from here the right height was 0 and it was 2, so this is the one who spoiled the balance factor, all the rest were fine, so we came to know this thing, okay. Our balance factor is bad here, so in this way we have solved it in OFF A, so I hope you must have understood very well in this case, if you have any doubt then you can go to our telegram channel and ask. See you guys. From tomorrow we will discuss the next question till then thank you
|
Balanced Binary Tree
|
balanced-binary-tree
|
Given a binary tree, determine if it is **height-balanced**.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,3,3,null,null,4,4\]
**Output:** false
**Example 3:**
**Input:** root = \[\]
**Output:** true
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
|
104
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.