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 |
---|---|---|---|---|---|---|---|---|
310 | hello everyone welcome back to my channel today i will introduce the analytical question minimal high trees and i will use typological to solve this problem from the description we can say we have a tree and it is a direct graph and each two node connected in one path so that means this graph without any circle connect and then from the tree we can say there are a node as an input it just shows the connection of each node and in this question we need to find which node could be the root and then this string has the minimal height and let's take a look on the example one so we have four nodes the node zero and one connector one two connector and one three connector and there are four possible tree and the second one we can say this is the minimum height because they're only how the one the hit one and the others with the h2 so how could we solve it by topological so first they we save all the paths into a graph and save each node we count the indegree of each node the way save the integrate save the node with integrate equal to 1 into the queue and we use the queue to iterate the graph in the end address of node would be the result so let's take a look on the code so first of all we need to create a graph and we also need array to save each node's in degree so let's build the graph from the input of h we need to save both nodes into the graph because this is our direct graph and then we create a queue we iterated the integrand and then we try to find the node based in degree one so let's do the topological for each loop basis to check how many nodes with how many nodes in the same level so we need to create a variable to save how many nodes in the queue and before the queue we create a list to save the node we added the current one into the list iterate the connections of the node and if we found it in the degree and away minus 8 from the in degree if we found the integrate is equal to 1 we save the cooler queue before each loop away create a new list and we and instead of save it to the result we save it to this list and after this loop we save the result to the list and so at the end of the topological the result is which is a node we found and the nodes can build the tree with minimal head let's run the code this is hashmap the time complexity and the space complexity is o n and n is the number of the notes if you like this video please subscribe me and give me a dance app and thank you for watching | Minimum Height Trees | minimum-height-trees | 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.
Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between the two nodes `ai` and `bi` in the tree, you can choose any node of the tree as the root. When you select a node `x` as the root, the result tree has height `h`. Among all possible rooted trees, those with minimum height (i.e. `min(h)`) are called **minimum height trees** (MHTs).
Return _a list of all **MHTs'** root labels_. You can return the answer in **any order**.
The **height** of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
**Example 1:**
**Input:** n = 4, edges = \[\[1,0\],\[1,2\],\[1,3\]\]
**Output:** \[1\]
**Explanation:** As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
**Example 2:**
**Input:** n = 6, edges = \[\[3,0\],\[3,1\],\[3,2\],\[3,4\],\[5,4\]\]
**Output:** \[3,4\]
**Constraints:**
* `1 <= n <= 2 * 104`
* `edges.length == n - 1`
* `0 <= ai, bi < n`
* `ai != bi`
* All the pairs `(ai, bi)` are distinct.
* The given input is **guaranteed** to be a tree and there will be **no repeated** edges. | How many MHTs can a graph have at most? | Depth-First Search,Breadth-First Search,Graph,Topological Sort | Medium | 207,210 |
252 | and then you have to check if a person can attend a meeting so which means I uh in this case from 0 to 30 right so this is zero this is 30 and this is five this is 10 this is 15 this is 20. so you want to know if there is an interval that can I mean there's a person who can intercept with all of the interval right so basically we need to reward uh we need to just sort the array so we have to sort based on the first index so again this one two four right and then Seven Ten right 7 10. and then this person can attend all of the medium and this is because you can attend this one and then there's a break and then you can turn this one right and then for this one the zero and thirty right so it takes over 11 I mean there are two interval overlap with this one right so uh basically like this question is supposed to be like super simple so after you sort right so I just have to check so you just have to check the starting time and ending time right so I'm gonna take two interval all of the computer so I'm going to take this one and this one so I'm going to say okay is my ending is my first ending right which is what which is greater than the second starting right so which means everything about intercept right all right so let's start holding so I'm going to say for in I put one I listen to rows a length and then I plus one so just want to make sure I soaked first index and then I'm gonna come here so it's my interval so 5 minus 1 is the first one right first ending is my first ending greater than the current one starting I will return post and then in this case I'm going to return this group so and run it okay so let's submit uh so let's talk about the time in space so this is going to be a time and this is also the time so this is all the fun right and this is a noggin so the time is a login and this is uh I mean they're the space complexity is constant within allocate any variables so all of one for the space I'm not going for the time so this is a solution and talk to you later bye | Meeting Rooms | meeting-rooms | Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** false
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** true
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 106` | null | Array,Sorting | Easy | 56,253 |
44 | Hello Hi Science Students Questions, Monthly pension is available by liking Adityanath, If the details of this pack abs were white part complete, then the pattern has been made for graphic's reference, thank you, special program, Tarak Hain Mountain, National football team's practice session in its struggle character, from Zauq electronic media friend. zanot10 only and only anti sequence subscribe 559 then click on subscribe to subscribe I am on 10 friends NRHM Payal rogue not warred because it is not warred over cost question subscribe definitely subscribe and subscribe this Video subscribe question mark question Mark Pimple last checked for the last fiscal deficit only take essentials and if you were not a subscriber of this suite question mark video channel of many countries then on this occasion 30 to 8 minutes if you subscribe that you are what warriors money name They Give Controllers Question Patton There Are Five Questions Mental And The Horse On Back Subscribe Button Show Steady Stream Of The Country Husband Is Wondering The Observer That's Why This Turtle Problem Subscribe A Flying Officer Shopping Dynamic Programming It's Very Hard To Understand Why The Destroyer Dharana Svabhava or else and then you use my questions in the examples and Vikram se contact example wash this mask only religious program this article only here to earn valor etc economic ruturi matrix regret field at this time when school subscribe questions page final Subscribe to ki by hawaii na mix kar meaning of the english translation for in the australian shepherd ne my it is completely way less time a to values into flowers from som vs time a to values into flowers from som vs time a to values into flowers from som vs pair is destroy reference anti-stress patan distic president anti-stress patan distic president anti-stress patan distic president please subscribe Karo Mere Sath Office Amazon Ke Pathak Subscribe And Financial Condition 100 And Witch Proven Fatal MP3 MP4 210 And Spinal Column Specific Ki Kausar Partner Jyoti Patel Point Par Hatim Subscribe August Month Kicks Off Subscribe Love U G I More Than 250 Followers The Hem Of i20 Phal And juice forms the water column on this forest profile pic playlist to right side doing this pattern all subscribe presents subscribe our subscribe still 2014 yes - 134 222 aaj tak aapke print yes - 134 222 aaj tak aapke print yes - 134 222 aaj tak aapke print unauthorized turnoff - page not difficult viral unauthorized turnoff - page not difficult viral unauthorized turnoff - page not difficult viral extra ko subscribe to Flash Lights Notes Platform So Helpless Between for watching this Video then that I will keep it partner question mother while doing soldiers force partner question wangdi se 600 candy crush subscribe a that pragya hai ma'am size andra se investor edison important tips all difficulties for students in all The Benefit For Certified Subscribe Must Subscribe To Channel Subscribe Must Subscribe To Subscribe Must Subscribe To Tomorrow Morning Notifications Tractors Tasty And Of I - Kar That Fixed At The Starting Of I - Kar That Fixed At The Starting Of I - Kar That Fixed At The Starting Of - Man Of - Man Of - Man Why Not Bhi Can Gate And Matrix Liye Is Chief Combine the deal of so that fixed floating touch tractor subscribe - - tractor subscribe - - tractor subscribe - - that their fans after and in the morning were so improved this will remain straight return gift subscribe - panchayat next subscribe - panchayat next subscribe - panchayat next question subscribe don't forget to subscribe and only - subscribed this video only - subscribed this video only - subscribed this video Recent Yes Parshad Stress subscribe and subscribe the Channel subscribe to main sirf patan half rate minus one this fact is the name of IPL that can be given by name off side - but subscribe this Video plz subscribe Channel Please subscribe and subscribe the Arrest Subscribe To Hello Hi - Mangne - Mangne - Mangne 16 To Make Maut Hai Subscribe Must Subscribe My Channel And Subscribe Channel Subscribe A Rich Kusum And Example Sanchay Ko 10 Saal Dharma Hotspot Phir Haar Channel Must Subscribe Swift Spots And Did Not Match Subscribe To Atif Aslam subscribe and subscribe Now Question A I only and there functions based power for now according to the control officer to do subscribe my channel subscribe note subscribe and subscribe ki aset to aaj sandwich cfab unfair loop fast subscribe and subscirbe subscribe and subscribe the Channel Please subscribe and subscirbe Subscribe How to work on water Sara Script Author Aegis of strength of this question on Class 10th Main 10 Director Subscribe BJP Ko Subscribe Must subscribe and subscribe that this PM oil that you have only Mere and Basic Notifications for Temples Page for All Elements Subscribe Ki Yas Side Sari Ho Gayi Hai Restroom Gloves Vikram Sathi Name List A Gay Hai Question Maa Ki Dastan Quid Subscribe To Ki Tiger Is From Aap Without Introduce Embed This Value Only Most Wanted subscribe and subscribe the two and subscribe to that I have done that Manav Bittu Rajput System Dushwaris Shekhar Labs Ki Omaze Subscribe Eggs A & B Hui Notice Full Forms And Subscribe Our List Subscribe Eggs Paytm Ne Question Mark subscribe and subscribe the Channel Please subscribe And subscribe The Amazing spider-man And subscribe The Amazing spider-man And subscribe The Amazing spider-man Which Story Full Vidyalaya From Your Tests A Specific Of The Finance Form Second Final Them Is Quite Eccentric A Person Should Not Be Used To Appoint You Operation Adham Editing Servi Three Cases 8 - Friends Triangle Participate In 8 - Friends Triangle Participate In 8 - Friends Triangle Participate In Order That In The Question Mark on specific artist sperm in all cases pair getting volume diner ten subscribe must subscribe and please subscribe and the water for patan exist subscribe se fold art festival with banner2 subscribe to and subscribe and share subscribe to a picture of Tables Cancer Represented By 30 Months Stress Can All Subscribe Please Like Share And Subscribe To | Wildcard Matching | wildcard-matching | Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:
* `'?'` Matches any single character.
* `'*'` Matches any sequence of characters (including the empty sequence).
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "\* "
**Output:** true
**Explanation:** '\*' matches any sequence.
**Example 3:**
**Input:** s = "cb ", p = "?a "
**Output:** false
**Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'.
**Constraints:**
* `0 <= s.length, p.length <= 2000`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'?'` or `'*'`. | null | String,Dynamic Programming,Greedy,Recursion | Hard | 10 |
1,748 | hi my name is david today we're going to do number 1748 sum of unique elements this is an easy level problem only code and we're going to solve it in javascript so you're given an integer array nums the unique elements of an array are the elements that appear exactly once in the red return the sum of all the unique elements of nums so for example we get a numbers array with one two three two the output is four because there's the unique elements of one and three that only appear once we can't use two because we repeat it and we add the values of one and three and we get four so that is what we need to do so how we're going to solve this is that first we need to create a variable to hold this output value so create some variable to hold output and next we need uh we need to keep track of all the unique uh elements in this array so creating a hash table is a great way to organize this so we create map variable and then with this we're going to keep track of how many times it's repeated so we can say tell if it's unique or not so after that we're going to loop through nums array and inside of this loop we're going to create a condition to see if the map the current index value of that value is the current index value of the array is inside of the map if it's not in it is inside of the map object if it's not in it we add it and set it to one that's the key that's the value so that is going to see if it's not in it we're going to add it to it so the first time we see that number we're going to add it that value and set it the key value equal to 1. and otherwise else we increment the value of that key so we see this number against twice so when we do this one 2 is there twice the value is going to be 2. so what we need to know what we need to focus on is that the key values that have a value of one so after that we're gonna loop through the map object and inside of this we have to create a condition to see if the key value has key has a value of 1. so if true we're gonna add the sum by the integer of the key since the key will be a string and lastly you will return sum so to put it in code we first create the variable that sum and it starts off as zero and next we create the map as an empty object we loop through the nums array so for that num of nums and inside of it we will have to create a condition so if map the num is not in it if we're seeing this value for the first time we add it and set it equal to one else we increment this value so this will get create us the map of all the unique values all the elements and how many times we've repeated so next we have to loop through the object map object for let key in map okay so when we do this we only have to take the value if the map num the map has a key value of 1. so if map.key 1. so if map.key 1. so if map.key is equal to 1 which is what we need we have to add the sum by the integer of key and lastly return sum great so our time complexity is that we're going to oven because we'll create we'll looping through this nums array and the space complexity will also be of and since we're creating this map that's proportional to how long this gnomes array is thank you | Sum of Unique Elements | best-team-with-no-conflicts | You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array.
Return _the **sum** of all the unique elements of_ `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,2\]
**Output:** 4
**Explanation:** The unique elements are \[1,3\], and the sum is 4.
**Example 2:**
**Input:** nums = \[1,1,1,1,1\]
**Output:** 0
**Explanation:** There are no unique elements, and the sum is 0.
**Example 3:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** 15
**Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100` | First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on. | Array,Dynamic Programming,Sorting | Medium | null |
1,266 | hello hi guys good morning welcome back to the new video this video we're see the problem minimum time visiting All Points although it's a easy problem and it is very intuitive also but it can be a way that you might get confused on how to approach these kind of problems which are kind of ad hoc and no algo or something is being used so it has been asked by Apple and that's a good thing and that is a bit frequent also so yeah it's worth to look at now what the problem says is that in on a 2d plane of just points now what we are given is we have n points for sure and it's in the coordinate basis which is X XI comma Yi we have to return the minimum time in seconds again we have to return minimum time in seconds to visit all the points in order given by the points again we have to visit in the order itself and also minimum time in seconds which is required now how the move movement is from one point to other point it is that we can move vertically uh one unit move horizontally one unit and move diagonally also one unit now we have to visit the points in the same order as they appear as it was stated earlier also in the same order as they appear and again uh you are allowed to pass through the points that appear in the later in the order but these do not count as visited again it is saying that you are allowed to pass a point that later in the order but these does not do not count as visits which means that if you encounter some point which means pass through the point that appear later in the order which means right now I'm passing through a point which might appear later in the order but still when that point chance will come as in let's say P1 P2 P3 while traveling from P1 to P2 if I'm traveling via P3 it doesn't count that okay I have traveled P3 I will have to travel from P2 to P3 for sure when I will be traveling so it is as that uh let's say in P3 might come in between but still it is not counted its chance will come when it is about to get counted cool so for example it's the best example they have given we travel from 1 which is 1A 1 to actually 3A 4 again we want to travel in minimum possible time again I would have said okay 1 2 sorry 1 2 3 4 5 from traveling from 1A 1 to 3A 4 I would have used 5 Seconds of five as a time but still I can travel this in 3 seconds 1 2 and 3 you saw that is nothing but you tried your best to travel diagonally for sure some whenever you want to travel anywhere you travel that diagonally first so as to travel the minimum distance and you know one thing even if I travel as horizontal it's a 1 second even if I travel vertical it's a 1 second even if I travel diagonal it's a 1 second so for this portion it is taking 3 seconds again from 3A 4 next is - 1A 0 again I'm traveling in order of - 1A 0 again I'm traveling in order of - 1A 0 again I'm traveling in order of points itself and you can see it's a straight line you can just travel diagonally down and thus it is giving us a 1 2 3 and 4 seconds for here 3 seconds for here ultimately it's a 7 Seconds that's an answer now one thing for sure you might have seen by this example itself is when you ever in general in real life also whenever you want to travel to a point you try to travel that diagonally as much as possible the same will happen and the cost is also same even if you travel horizontally or vertically or diagonally the cost is always one so one thing is for sure my first preference is to travel dally and then whatsoever it is either it can be a vertical or it can be a horizontal I can just try travel in that way now comes the interesting part that one thing I have to only make sure is that how much time it will require how much minimum time it will require to travel from a point P1 to a point P2 because the same I have to repeat for every Point as my only task is to figure out the time needed for my traveling from my01 to point 2 now the best example for us is this point1 and this point 2 because for sure for this point 2 to point3 you can see it is diagonal so we can just easily say that whatsoever is a diagonal time here you will see 3 - 1 4 - 0 so 3 - of -1 4 will see 3 - 1 4 - 0 so 3 - of -1 4 will see 3 - 1 4 - 0 so 3 - of -1 4 minus of 0 both are giving me as four and you will see that X I have to travel four as you can see X I have to travel four y I have to travel four ultimately I'll take the minimum of both of them or basically you can also say maximum because both are for sure equal so anything I can take when I am directly and only traveling diagonally so that I can take anything I can take because it is only traveling diagonally now comes the interesting part is how will you do for the situation as I told that first is to travel always diagonally now whenever I have a point 1A 1 can I just say that okay 3 comma 4 is other point so for sure if it had to travel diagonally only then it would have traveled this up till 3A 3 it would have traveled diagonally 3 comma 3 it would travel only diagonally or I can easily say if I have this coordinate as 3 - 1 is 2 so it is saying I traveled 3 - 1 is 2 so it is saying I traveled 3 - 1 is 2 so it is saying I traveled horizontally 2 4 - 1 is 3 it is saying I horizontally 2 4 - 1 is 3 it is saying I horizontally 2 4 - 1 is 3 it is saying I traveled vertically 3 what you can see is this three I can break it down to two and one right two and one now when this is broken as two and one you can easily see that two it is traveling diagonally and remaining one it is traveling horizont yeah vertically here in this case it is traveling vertically but it is very easy to infer that whatsoever maximum value is now in this case maximum value difference maximum value is 40 y it is actually three it can also be that X is maximum like X is more but it is inferring that the common part which means this common part is used to travel diagonally and the remaining part is used to travel vertically so I can say 2 + 1 is vertically so I can say 2 + 1 is vertically so I can say 2 + 1 is actually the answer or I can also say that ultimately 4 - 1 which is 3 is also that ultimately 4 - 1 which is 3 is also that ultimately 4 - 1 which is 3 is also the answer because it is a summation of diagonal plus vertical so I can just say that in this I'll do a 3 minus of Min -1 that in this I'll do a 3 minus of Min -1 that in this I'll do a 3 minus of Min -1 4 minus it's a minus one sorry 3 - of 1 4 minus it's a minus one sorry 3 - of 1 4 minus it's a minus one sorry 3 - of 1 or 4 minus of one whatsoever is the maximum value just give me that maximum value but Arian that can be negative also right if you are just moving to some other coordinates so yeah that can be true to so simply take a absolute of this and take the maximum and that will give you the minimum time travel from point 1 to point 2 because you are choosing to travel first diagonally and then remaining points is either horizontally or vertically and that will be for sure included in the difference itself cool let's quickly see that how we'll code it we'll simply go on to all the points and simply have a maximum of absolute difference between their corresponding x coordinates and y coordinate and whatever is maximum we'll just take that particular value let's quickly see that uh firstly uh we know that we want to have an answer uh we will also have points size because it's easy for us to travel now I want to have a difference between two consecutive points so um I can just iterate starting from the point one now for sure that I want to increase something in my answer so I'll just say take the maximum of uh now maximum I have two options uh first is the x coordinate difference uh which is nothing but points of I of0 and points of IUS one of 0 and second is the y-coordinate difference which is y-coordinate difference which is y-coordinate difference which is absolute of points of I and 1 minus uh points of i- one and one now when this points of i- one and one now when this points of i- one and one now when this portion is done simply return the answer because I am by this I'm trying to choose either vertically or horizontally as maximum difference value and that will make sure that I either traveling diagonally and then either hor or vertically cool thank and yeah the time is actually o of N and space is O of one time o of n because you are traveling on all the end points and space is O of one because you not using any extra space at all cool see you guys bye-bye | Minimum Time Visiting All Points | minimum-time-visiting-all-points | On a 2D plane, there are `n` points with integer coordinates `points[i] = [xi, yi]`. Return _the **minimum time** in seconds to visit all the points in the order given by_ `points`.
You can move according to these rules:
* In `1` second, you can either:
* move vertically by one unit,
* move horizontally by one unit, or
* move diagonally `sqrt(2)` units (in other words, move one unit vertically then one unit horizontally in `1` second).
* You have to visit the points in the same order as they appear in the array.
* You are allowed to pass through points that appear later in the order, but these do not count as visits.
**Example 1:**
**Input:** points = \[\[1,1\],\[3,4\],\[-1,0\]\]
**Output:** 7
**Explanation:** One optimal path is **\[1,1\]** -> \[2,2\] -> \[3,3\] -> **\[3,4\]** \-> \[2,3\] -> \[1,2\] -> \[0,1\] -> **\[-1,0\]**
Time from \[1,1\] to \[3,4\] = 3 seconds
Time from \[3,4\] to \[-1,0\] = 4 seconds
Total time = 7 seconds
**Example 2:**
**Input:** points = \[\[3,2\],\[-2,2\]\]
**Output:** 5
**Constraints:**
* `points.length == n`
* `1 <= n <= 100`
* `points[i].length == 2`
* `-1000 <= points[i][0], points[i][1] <= 1000` | null | null | Easy | null |
4 | welcome to SF job slab we bring you our possible solution of interview portion including the most efficient one and today we will see how to find a median of two sorted arrays of size M and M so let us understand this portion with an example so let's assume if we have these areas where we have element values 6 9 15 and 39 in array a and we have two 10 31 65-69 in Arabi and this arrays are 31 65-69 in Arabi and this arrays are 31 65-69 in Arabi and this arrays are already sorted so in this case our median would be 15 and if we have these arrays as an input then in this case our median would be six point five so I guess question is pretty much straight over so if you have understood this very well so you can pause this video for a while and you can solve the problem with yourself first or else less continue for the solution before you go to the solution I want to tell you that we are going to cover this problem in two different part in this part or we are going to see all possible solution so it is my request you to all if you want to see the most efficient solution of this problem then please do watch this video till the end and in the second part we will see how to code in the interview for this problem as we have to find a median then it is very important for us to understand what is a median first and what are the key properties we have to keep in mind while looking for the median so let's see that first so let us assume if you have some sequence number like this and we have to find out what is the median of disciplines the first thing first we have to do is we need to sort this sequence first and then after sorting if our sequence size is odd then our median will be in the element which is placed at n plus 1 by 2 'the element so in our at n plus 1 by 2 'the element so in our at n plus 1 by 2 'the element so in our example you can see that the size of the sequence is 9 so basically the 5th element will be our median so 5th element is this 10 but if the sequence size is even then in that case medium will be the every job and by 2 and n by 2 plus one element okay so for even case let's assume if you have a one more element here 11 then after sorting our shipments will arrange in this increasing order where the fifth and sixth element we have to take the average of the fifth and sixth element which is 10 and 11 which will come as a 10.5 so in this which will come as a 10.5 so in this which will come as a 10.5 so in this case our median will be 10.5 and if you case our median will be 10.5 and if you case our median will be 10.5 and if you observe very closely then what this median does is the median will divide the sequence in two equal halves so if you see in this case you will have a left sub sequence where the size is four and you will have a right sub sequence in this also you will have four element right the same case when we have the even size sequence so in this case also if you see that the median has divided our sequencing two equal halves where the left side you will have five elements and in the right side also you have five elements one small correction here this is 56 anyways and just people so this sequence is in increasing order so this is pretty much obvious that the element value which is there in the right sub sequence those values will be always greater than the element value which is there in the left sub sequence right so finally we can summarize our discussion into these three points so if we have to find a median then the first point is we need to sort the sequence first and then based on the sequence size we have to get the middle element of the sequence and the median will divide our sequence into two equal halves so remember these three points now let's get back to the question now we will take this inputs in our further discussion and let's start with a basic approach first then we will see how we can get the median value as in 15 here okay so in basic approach what we can think of that we can create new AIRAID let's name it see in which we'll add all the element of a and B one by one so let's start adding the element value of a and once we'll get over with array a then we'll start adding all the elements value of B then as we know that through finding out median we have to sort the entire sequence first and then as we have size here is nine and then we will use our formula so here and is hard that means our median will be there at this place right means our median is stripped element which is nothing but Krypton here this is a good start but the problem here is we are creating a one new array while C which is consuming extra space and the second problem is time complicity here we are doing a sort operation so any good sorting algorithm will take n log n time complicity so for this approach and complicity will be order out n plus M log n plus M right just because in question it is given the size of a and B is eminent so total element we have M plus n in the same way space complicity have order of and plus M so to optimize our solution from here definitely we have to think better than n log n time complexity right that means we have to think of this stage whether we have to do a sorting or not I mean we would have done sorting if we would have had both array a and B in unsorted order but here we have both array a and B in sorted order that means we have to simply merge them in such a way that the final segment should be in sorted order and if you remember that this kind of logic we already have used it you know in Malad right so now we will optimize the same logic over here so let's merge this is same as what we do in Mashhad we'll pick one element from a and one element from B so here we will be picking six and two and we will take minimum of this two and we'll place that into our Odyssey so two will come here and then we will pick minimum of this two element six and ten so six will be placed in second position after which we'll pick minimum of nine and ten so nine will come here like this we'll keep on repeating our process and at this point of time as we have reached a last element of a then whatever the element we are left with in array B we will put all the elements one by one at the hand of the C and now if you see a we have a sorted array C and after which as we know that the size is nine that means our median value is 15 and if you think about the time complicity so if you have so that we have is can only once bow that is a and B so that means the time converse field would be order of n plus M right and just because we are creating a new array because of that we are still consuming space and plus M so this solution is far better than the previous one and because we have optimized the time complicity over here and now to optimize further this time people think about space complexity do we actually need this obsolete space so let's see one situation here where is 1 2 3 4 and B is having element 5 6 7 8 and let's assume if this is a our left subsequence and this is our right subsequence and if you calculate the last element of left subsequence which is 4 is actually lesser than the first element of the right subsequence right so once you get to know about this condition we will immediately get to know that the elements of right subsequence is greater than all the elements of the left sub sequence now think that do we actually need extra space to figure out median here no right just because in this case our median would be 4 plus 5 by 2 which is 4 point 5 so from this observation we can clearly see that we have to always look in to the last element of the left sub array and the first element of the rights of area right so this was all corner case now let's see standard case so let's suppose if we have our sub arrays like this where a 1 to a 8 is a part of array E and B 1 to B 10 is a part of our led and remember this array is already sorted here total numbers of element we have 18 that means each sub array will have 9 elements and as you can see that we already have our left and right sub area the red element is a part of the left sub area and the green element is a part of the right sub array so in step 1 the first thing first we have to do is we have to calculate the last element of the left sub array right so in the left sub array if you see then the last element will be the maximum of a for na be Phibes because again this starting from E to a fourth is the sorted and B 1 to B files all also sorted so if you'll merge that using a merge technique right so in that case the last element of this will be the maximum of a 4 or B 5 okay that is pretty much fear and now in the second step we have to figure out first element of the right sub array which will be the minimum of a 5 and B seats again with the same much logic and now in third step we need to check this condition if this condition is true and now we can find a median bit using the standard formula you total size is even then we have to use the max of F would be PI plus me know if I be 6 divided by 2 if the size is odd then we have to return match of a 4 B 5 why we are returning here max of a 4 B 5 because in that case the size of the left sub array will be 1 mol then the size of the rights of in it ok so if the total size is 9 then we will have 5 elements in the left sub array and will have a 4 elements in the rights of it okay so that is pretty much obvious that the last element of the left sub array will be the middle element of the entire area right and if the condition is not satisfied then in that case we have to move our max of a 4 B 5 towards right side so let's assume if a 4 is a maximum in this a 4 end d5 so you can see that now a 4 will be the part of the right sub array and just because we have to maintain the equal size so because of that the B 6 which was the part of the right sub array now that will be the part of the left sub array okay then again we'll repeat our step one process means the last element of the left sub array will be maximum of III and b6 similarly the first element of the right sub array will be the minimum of F or n b7 and now let's see some other scenario as well so if our array and B will have these elements so in this case you can see that we have a lots of array containing elements from both a and B but in the right sub array we have only elements from array B so in this case so everything look the same the only difference is no while calculating the first element of the right subtree then we have to return B body in the same way we can encounter such kind of scenario as well where the lots of array will have all the elements from array a and the right sub array will have a elements from both array a and B so in this case in step one we have to return a seven enough for better understanding let's understand this process with an example let us assume if our input array a is this and array B is having this elements so as you can see that the length of array is 10 and length of array B is 6 which means our left sub array and right sub array size will be 8 so at the beginning I am dividing our survey race like this so what are the elements is towards left side of this boundary is a part of blood sovereign and the elements which is right side of this boundary line is a part of rights over it and now let's start our process here so in step 1 we'll be calculating max of 79 and 9 which will return 79 and second step we will be calculating Minos 51 and 15 which will return 15 now we will check it is lesser than so it is not 79 is greater than 15 that means this 79 should be part of the right sub array so let's do that so we have reduced one element from a and we have added one element from B right and now again we will calculate a step one we have to calculate max of 72 15 this will return 72 and from the right side we have to type in me knob 79 and 39 which will return 39 so again 72 is greater than 39 so we cannot find our median at this point of time that means we have to sift 22 towards right side and again we'll calculate max of 69 and 39 which will return 69 and from right side will calculate min of 72 and 42 which will return 42 so here also the condition is not ready satisfied that means again we have to accept our boundary towards left side and now let's calculate again max off and 42 this will return 42 and from right side again me know 69 and 49 so this will return 49 so here the condition is getting satisfied here 42 is lesser than 49 that means at this point of time we have divided our errors in two groups every group will have the same size and the element value of the right sub array will be greater than the element of element value of the left sub array that means now we can find a median over here so we'll apply the formula here and the total size is even that means our median will be average of 42 plus 49 by two and now if you think about the space complicity over here so as you can see that we have not used any extra memory so it's paste complicity here is constant and now let's analyze our time complicity here so what we have been doing here starting from the beginning is that we are looking for a number which can satisfy our condition right so that's why you know we started from here 79 but this pair was not getting satisfied so we jumped to 72 and then we jumped to 69 and here also the condition was not satisfied so we jump to 10 so here you can clearly see that we are moving towards left linearly right and this moves we can do for many times we can do this many times let's say if size of B is M then we can move like this one by one in M times that means time complexity of this is order of min of M comma M and now the question is can we optimize our performance better than this so the answer is yes we can do that by just because here we have to notice one thing that we are searching element on sorted array and as we know that most efficient way to search any element on sorted array is through binary search so instead of doing a linear search over here now we will be finding our element through binary search so let's do that so this was our initial situation where our condition was not satisfied so now instead of moving linearly towards left side now what we will do we will be a jumping middle element of dis away okay so middle of this happily is ten so let's move our boundary from seventy nine to ten and then we need to calculate max of 10 and 42 which we'll return 42 and if we need to calculate min of 69 and 49 so this will return 49 and now you can see that our condition is getting satisfied over here then we need to stop our operation at this point of time and if you think of time complicity over here so it will be order of o log of min of M comma hat and this is our optimal performance of this problem I hope that you liked this video and if you do so please share this with your friends who is especially preparing for the interview and through comments please let us know which kind of questions you want us to cover in our next video thanks again for watching this video | Median of Two Sorted Arrays | median-of-two-sorted-arrays | Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Output:** 2.00000
**Explanation:** merged array = \[1,2,3\] and median is 2.
**Example 2:**
**Input:** nums1 = \[1,2\], nums2 = \[3,4\]
**Output:** 2.50000
**Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5.
**Constraints:**
* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* `-106 <= nums1[i], nums2[i] <= 106` | null | Array,Binary Search,Divide and Conquer | Hard | null |
1,938 | hey what's up guys this is chung here again so this time i'll lead code number 1938 maximum genetic difference query uh so this one is a pretty difficult one like to be honest it has some many a few small sub problems we need to solve first okay so we you're given like a rooted tree right consisting of unknowns number from 0 to n minus 1 and each node's number right denotes to its unique genetic value basically the root the node number is its value and the genetic difference between two genetic value values is defined as a bitwise or right so this is a pretty common problem type of problem bitwise or okay and then you're given like integer array parent because we're gonna need we can use this one to build like a tree right and then you're also given like a red queries right where the queries has two values the first one is the node right and the second one is a value so for each queries we need to find the maximum genetic difference between the value of and all its parents of the current node including the this node it itself right and then we want to return this answer right after each query so basically what does it mean it means that you know uh first you're given like a tree right and then in the form of a parent and then you're given like a queries so for each query what we need to get is that you know the first one is a node right so this one means that you know from the current node all the way back to its parent right then we have like different values along the way right and the and we won't get the maximum bitwise or right between this value in the queries and all the values uh on this path right to the root that's why you know so this is the tree we have here right and then the queries we have is 0 2 3 2 and 2 5. so the answer is 2 3 5 because for root 0 right i mean there's nothing right for root 0 it's uh there's only one node right we can use which is two basically zero x uh b twice x or right to two equals to two all right that's why we have two but for three right as you first three uh we have three nodes that we can use which is three one and zero right among those three nodes i uh the biggest value we can get it is this one is because the it's one with a difference of that's going to be the 2x or one basically the value is two here right and then the best we can use is this node which is one equals to one which is three sorry equals to three and the third one is two and five right so for two and five we have two one and zero we have three notes to use right and an amount of three ones i think i believe we pick two because 5x or 2 equals 7 which will give us the biggest one right so that's basically the description of this problem right and then we have some common like uh constraints right i think those are pretty common ones and the value is also this one right okay so for this one you know and every time you know every time when you guys see a b to wise x or plus a bunch of queries we need to solve you know i think the first thing we should always uh think about consider the beat uh try or the beat prefix tree because you know the beat prefix 3 can give us like a very uh i think all of constant time to query to get to query the uh the values the biggest value among all the available numbers in this case is uh in this case it's all the parent nodes including the node itself right and for those who don't who doesn't know what the bit prefix tree is that you know maybe i can give you a brief introduction here you know for example we have you know like i said we have a bunch of numbers uh along the way we want to compare right among those numbers we want to efficiently quickly find which one number can give us the best or the biggest uh xor value with the current value right um so how can i where should i start you know so first we need to convert each of the numbers to its bit value so let's say we have these two values here one zero a few numbers here okay and then we have 0 1 0 and then we have another one 1 0 right there could be more right so those are the available numbers okay and our current number is what our current number is this one let's say the current number is 0 zero one so this is the current number we're trying to use and we want among we want to find the biggest number right that can get which can give us the maximum value here right and how should we do it i mean obviously we want to check the values bit by bit assuming we only have like five bits in our case right so the ideal case is what ideal case is like this ideal case if we have a number is this one zero right this is the ideal case because this will give us what this will give us uh one right which is the maximum possible number we can get right but obviously this one as you guys can see this one does not exist in this set right but you guys see the pattern here so basically you want to make we want to get as m as many ones as possible right and okay so which means that you know we won't get as many ones as possible and we want to get at the ones can give us the biggest value first because right so which one uh which bit can give us the biggest value we obviously is the one from the left side this is the first one we want to get right that's why you know uh what we want to check that we want to see okay if there's any number that has this bit equals to one right if it is and then we know okay at least we can get what we can get 2 to the power of 4 right which is 16 right so basically if this one if we have a number who has the value bit y bit value equals to one for this one no i know we at least i can get 16 right and the reason we want to use this one first is because you know if there's a one if there's one has a bit value equals to one here we will definitely use that number because you know otherwise if this one is zero even though everything else is equal to one right so what's this value this is 15 right 15 still smaller than 16. that's why i want to gradually pick the ones from the left right so now we see okay so we have one right so there's a there's one here there's one there's actually there are two numbers that have one for this bit okay how about the second one second we're also trying to see if there's a one here but you know since we already picked this one here you know after the one uh both of them have value zero right so which means what so which means this the second one is not possible because even though we have a we have one here but this one coming from the zero right which we didn't use because we picked the ones we this which is the one we picked those two numbers with the ones here that's why we have to use zero here right so which means zero is not possible how about the third one uh what we're looking for is a zero do we have zero yes we have zero here right that's why you know we have what then since we have this one we can have like uh two to the power of two right if we keep going right so this the next one is what the next one we're looking for is one right do we have one here right we have one here which is this one because you know since we have already followed this path now this one is not available anymore we have to go with this one right that's why we have another of one how about zero yes we have zero that's that this is uh it's one right so that's basically the uh the values we can get right and this is how we use the uh the binary fixed tree you know because the way binary uh sorry not binary or bit be the prefix trace like this we have a root here so for roots right so each root can only have possible either zero or one node either basically either one node or either has no node zero or node has one so for this one you know we have one here right so that's why you know we have one here okay and then we have zero so let's define the left one is always zero the right one is always one then we have zero here okay and then next one is one right so we have one here and then next one is also one okay and then the last one is zero okay so that's how we insert the first number into this uh bit uh try right and then the second one is 0 1 so we have 0 and then we have 1 right and the next one is also 1 last one is 0. right the last one is this one 1 0 zero one so we have one we have zero and then we have zero in this case right and then we have one and then we have zero all right so that's how we build this uh bit uh prefix tree and when it comes down to uh how do we how can we use it right like i said we start from this root right and we traverse we check we're looking for one right for the first one okay so that's why you know we'll go here right because we have one and then from the one here right we're also look so the next one we're also looking for one right but we don't have a one after this one we only have zero right that's why you know we'll move to zero and notice that we only increase uh accumulate the answers when we can find a match right because otherwise you know this bit will be zero means there's no value right to be added so that's why we have zero right because we don't have anything right so we have zero and the next one is what next one is also we're looking for zero in this case right that's why we'll go here right so that's why we're coming here and then the last one is the next one is one right and then the next one is one and then the last one is zero that's how we traverse this one down the row right to get the uh the maximum possible xor we can get right okay so that's the uh the basic idea of the prefix tree you know i uh i hope you guys uh understand how it works okay so given this one right the next problem is that how can we find this kind of uh basically candidates right we can do the x word um so let's go back to the uh to the problem right as you guys can see right the uh the queries is for the current for the node right and so the brutal force way is that for the current node we want to find all the other parents nodes and then we add all the parents nodes into the uh into know just a bit try right and then we just do a query on that but if we do that do it that way uh for each of them to create here right to find all the parents notes worst case scenarios we need an untime right and then for the queries here you know it's going to be n times n right going to be n square time complexity for that's why you know we cannot use that because the with this constraints here i think it will most likely tle right that's why we have to find like a more efficient way to do the query right so what we can do is that you know since we have a tree structure here right i mean we can create we can do the query along the way while we're tr while we're doing the dfx reverse of the tree here so what does it mean it means that let's see we have everyone knows dfs right so we have dfs here so dfs we have a u here right every time when we visit a u here right we insert we're going to insert this one into the pre into the bit of try the prefix tree and after df has finished we're going to remove it we're going to remove the u from the prefix tree because you know for example for this one right so when we have 0 1 and 2 right so once two is it's finished processing and then the next one from one is going to be three right but at this moment let's say two has already been added right to the prefix tree now when we're processing three here we don't want the two to be we need to remove two from the previous three because obviously for three we have we only have three one and zero we don't have two that's why we have to find the efficient way to remove the two from the prefix tree right so how can we remove it uh a trick is that we can keep a count for each of the node in the prefix tree and every time when we insert we increase that the count by one and when we remove we simply just uh do a decrease that okay and then later on when we try to query the prefix tree we also need to check if the count is greater than zero right if it's zero then we know it there's a value there this bit has a value right from some numbers okay and that's that right nice as you guys can see so for this one we can simply just uh piggyback on this dfs traverse right and then to calculate the queries right basically you know what i mean is that you know every time we have like a u here you know after inserting here we can do something here so what we can do because at this moment right everything for this u for this number u here for this node u here has already been inserted all the patterns have been inserted into the prefix tree that's why you know from here we can do the query and query for this u right and we can query for this u for all the queries that has this number has the node equals to this u right so let's say for example we have three here let's say we have three two i know there's another query three five there's another one of three six right so at this moment right we can i can answer the query for all three queries because of this three here let's say u is equal to three at this moment right because at this moment like i said everything all the parents of three have had already been added to the prefix tree okay and right and after that we also need to remove it for the u because here you know after answer the queries we're going to also do a dfs right of v here with the children of u okay i think that's the basic idea here right so and yeah i guess then we can start coding uh i think the implementation is a bit long here so but i will try to make it short uh so first you know from not for me i always prefer to create a note for the prefix tree you know uh self okay self dot children okay have children equals to this and i have self dot count right like i said we need a count and oh and i think another thing i forgot to mention is that you know for the prefix for the bit prefix tree uh how many digits we want to uh we want to check right that's the number of digits we want to check depending on the biggest number in for this problem right because you know for example you know previously we only have like five digits right because you know i'm just using this one as an example but for this one as you guys can see we have uh 2 times 10 to the power of 5 right so which means that you know we need prop probably we need 10 to the power of 18 to cover everything right because this one so what's i think this one is three some something i don't remember the exact numbers but i think 2 to the power of 18 can cover uh this big range here right because obviously we won't have like enough base value to cover all the values here right and so uh so where shall we start um okay so first one is the root right uh let's try to implement the prefix tree here uh so for this one we have since we need to do both the insert and the remove so i'm going to use this one as a update so we're going to have number and we have a value here right so basically this number will when it comes to when it's insert this value will be one right when it's removed this value will be a negative one okay current equals to root right so for i in range of 17 uh minus 1 right uh because you know like i said since we're trying to when we're trying to create the prefix three we're trying to create from the leftmost bits bit value right which is this one right that's why when we do the insert we want to do it in the reverse way right we want to insert this one into the prefix three first that's one because only that only then we can just uh after the root the first the next child will be the left most digits right that's why we have we do it in a reverse way okay and like i said since the uh since 2 to the power of 18 is enough that's why we use 17 because 17 to 0 is 18 right so the b divided it's like this so this is gonna a little bit manipulation here right we uh do this one do here n of one that's how we get the left most not the leftmost the this number of this bit value of the at this index has this position right and then it's like the standard uh prefix three implementation right template if this one not in the current dot children right we uh we create this child node right because the node of itself right and then we uh currently goes to current.children dot bit current.children dot bit current.children dot bit right and then in the end don't forget to increase the count by this value right because um yeah and then the next one is a query right grave number so this one similarly as this one oops i can uh this one i can copy and paste this the structure is the same but this one is different so now okay so we also need the answer here right the answer is going to be 0 here and so this time we need a target right remember the target will be the reverse value of the original value right which is uh which that's why i do a x or in the end that's how we get the target and for this one we do what so if the target is in now this time target is in this and this one and remember since we have a count here and current.children dot target dot count is greater than zero right that's when we will increase the answer right by this value okay and then answer equals answer.children.target answer equals answer.children.target answer equals answer.children.target right else if it's not there right uh we can we will not do the answer we'll not increase the answer but here we'll basically do the x square this one right because at this moment if this one does not exist obviously the other side must have must exist right because we have already populated that because you know if since there's always like a path to the end right so if this one does not exist then the other side has to exist right because there has to be a path follow to the end to the leaf right if this one's not there the other side must exist that's why we can safely uh assign the current with the is the target actual one okay and again so this part you know if there's no count here right so this one is enough but since we have this uh counter here so which means that you know even though the this path exists but if this node even though this node might be it might exist but the count could be zero because it could be uh we add it but now then later on we remove it that's why we have to check both of the two things here okay and yeah so that's it right and i mean simply we in the end we return the answer oh sorry uh this one uh yeah so this part is not needed right so that's how we query the bit prefix tree okay cool so and so that's the prefix tree and the rest is what so let's try to view the graph okay um well actually it's true it's not a graph right trace like this so we're going to have default of the list right and then we also need to find the root value okay so that's why i need to define the root value it's going to be a minus one okay and then for i dot parent right in enumerate of parents okay uh if the parent is equal to minus one then we know okay so the current this index is the root gonna be what they're gonna be i because later i'm going to do the dfs we need to start from the root that's why i use this one right and since we already have a root here i need to use a different variable name and then the tree dot parent all right dot append i right so that's how we build it build a tree and then the next one is what the dfs right so let's do dfs here because later on we're going to do a dfs uh going to be dfs of the root value right and then we return the answer oh we haven't defined the answer yet uh the answer is okay it's here so we have the answer it's going to be the zero of length of course okay so that's the answer right and then return the answer later on right okay now the dfs so we have a u here right u and v here so first uh every time we uh enter the note here we're gonna update right we're gonna insert basically gonna update the u with one right and later on we're gonna remove it right u minus one right that's how we and then let's finish the dfs first so we have d and then for v in uh tree of u right we do dfs of v right so that this is the dfs template right pretty straightforward and like i said on top of this one right before doing this now we can answer queries awkward basically all queries for you right and okay yeah in order to do that i think we also need to create like a dictionary uh between the note to the queries right because if this uh this node here could have multiple queries that we can answer right that's why uh let's see um okay let me create another dictionary i'll just call it a node to query it's going to be another dictionary right so for this one index and we have u and value right in enumerate of course q e r i s so the key for this one obviously is the is a the value itself right and then we need to append two things the first one is the index second one is the value right because we need the original index to update the answer right okay and so let's go back here now we can answer the queries so for index and the values in node 2 queries of u right so the answer of this index equals to the query of the value right and yeah i think that's it right uh okay let's try to run code finger cross okay accept it nice let's try it run it again okay cool so this one passed but as you guys can see this one is it's almost tle you know um i don't know i think that's how this problem the test case was given and this maybe it's because it's going to be harder for python you know i believe if you use c plus or java you may get a faster runtime but for python this is as i mean the best i can do i guess almost tle um so let's take a look at the time complexity right so here right so the update and queries so this one is like what 18 right as you guys can see right so this one you can think of as an off one but it's anyway it's an o of 18. and so for the dfs right so for the dfs and for this kind of queries here uh so how many queries we have this queries here the queries is this one and the uh so the node is let's say n right and this one is m okay so because we have this many queries we when you down answer that's why we have this photo here but anyway but all in total so what we have m plus n right we have m plus anything we need to answer and on top of this one we have 18 right times that because in total the dfs right the dfs in total will traverse endnotes right and among all those kind of introverts traversing will answer m queries for those for this many nodes that's why in the total we have m times n and for each of them we're going to do either query or update and either query i'll update the time complexes of 18 that's why this is the total time complexity right uh yeah i think that's it right i know this one is a long one um i don't know just to recap right so first thing is that you know every time we see this bitwise or and a bunch of queries always try to use the prefix three right at the beat prefix three and then we try to build a bit freak street bit uh prefix three uh with the count right so because we for each queries we want to only we need to make sure the bit the prefix tree only can only include the parents node for the current node that's why uh we also need a count to also help us to identify right if this node has a value has a number associated with it or not okay that's why we have two we have update right we either increase or decrease okay and once we figure out the prefix tree the next thing is that you know we need to use the dfs right to efficiently traverse all the nodes while also a lot while traversing the tree we also want to answer the questions the queries for the current node that's why we have this structure right so first we have dfs and i for every time we enter a node so we update we insert into the prefix three and then later on we remove it and then in between right we can answer the questions for all the queries for this node okay and the rest is just a bunch of oh i'll have to answer here return here the right is just a bunch of like uh miscellaneous stuff right to help us do it to finish to accomplish our goal right um yeah i think that's it for this one and thank you for watching this video guys and stay tuned see you guys soon bye | Maximum Genetic Difference Query | minimum-operations-to-make-the-array-increasing | There is a rooted tree consisting of `n` nodes numbered `0` to `n - 1`. Each node's number denotes its **unique genetic value** (i.e. the genetic value of node `x` is `x`). The **genetic difference** between two genetic values is defined as the **bitwise-****XOR** of their values. You are given the integer array `parents`, where `parents[i]` is the parent for node `i`. If node `x` is the **root** of the tree, then `parents[x] == -1`.
You are also given the array `queries` where `queries[i] = [nodei, vali]`. For each query `i`, find the **maximum genetic difference** between `vali` and `pi`, where `pi` is the genetic value of any node that is on the path between `nodei` and the root (including `nodei` and the root). More formally, you want to maximize `vali XOR pi`.
Return _an array_ `ans` _where_ `ans[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** parents = \[-1,0,1,1\], queries = \[\[0,2\],\[3,2\],\[2,5\]\]
**Output:** \[2,3,7\]
**Explanation:** The queries are processed as follows:
- \[0,2\]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.
- \[3,2\]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.
- \[2,5\]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.
**Example 2:**
**Input:** parents = \[3,7,-1,2,0,7,0,2\], queries = \[\[4,6\],\[1,15\],\[0,5\]\]
**Output:** \[6,14,7\]
**Explanation:** The queries are processed as follows:
- \[4,6\]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.
- \[1,15\]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.
- \[0,5\]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.
**Constraints:**
* `2 <= parents.length <= 105`
* `0 <= parents[i] <= parents.length - 1` for every node `i` that is **not** the root.
* `parents[root] == -1`
* `1 <= queries.length <= 3 * 104`
* `0 <= nodei <= parents.length - 1`
* `0 <= vali <= 2 * 105` | nums[i+1] must be at least equal to nums[i] + 1. Think greedily. You don't have to increase nums[i+1] beyond nums[i]+1. Iterate on i and set nums[i] = max(nums[i-1]+1, nums[i]) . | Array,Greedy | Easy | 2329 |
162 | you guys it's just everything go in this video I'm going to take a look at 1 6 to find peak animun a peak annamund is a name and that is greater than its neighbors we're given an input array noms we're no adjacent numbers are equal so there must be a peak because we are asked that the minus 1 and the next number will be minus negative infinity so they will be they were only these only case that they were the no peak in iment is that all the numbers are same but we that's not possible so there must be a big array may contain multiple Peaks we can return any of them mm-hmm so one two three one well we mm-hmm so one two three one well we mm-hmm so one two three one well we could just loop through the elements and the found and check if it is greater than neighbors but we are asked to the solution must be a lot logarithmic complexity well log then it should be something like binary search let's analyze these so the condition of this actually is the key point right mm-hm suppose if we're doing something like binary search we choose the middle one and what week you found well we if we compare the number between its Labour's let's suppose there are two numbers okay the one there will be no peak numbers this is minus infinity left one is infinity right so once the number like go up go bigger like to then there must be a pig in a minute right because once you go up you must go down to infinity so once there is an upward slope let go up then there must be a picking them to the right if downward then again yuning's there will be picking them into left right so yeah that's it we can use binary search let's start equals zero but in the coolest unint that's one Wow okay let's say if start equals to in if noms middle if equal then we compare the previous one if it is equal then we don't know if it's not equal okay and that's good now just me plus one can be the next one suppose something like one two three now we pick two in the middle now we have found our slope go bigger so a peak point Kahneman must be to the right one there must be one to the right okay so we start set to an even plus one the other case up to the end so now we go to three and three the others say finally we get to the same element then it must be the P Kinnaman right why because like any fear if these last elements yeah it's big if not that look like there is a four back to okay so go up okay now - three two to okay so go up okay now - three two to okay so go up okay now - three two right now we choose the number is three go down so end will go to 2 right so it will end at what end the star begin it and we start on okay start beginning means start is the possibility of the picking image and is the possibility okay if we go up then means the not possible not it's not pick an event super case here huh wait a minute doh - so we check huh wait a minute doh - so we check huh wait a minute doh - so we check three two against two and three this is downward so and okay and they said to - downward so and okay and they said to - downward so and okay and they said to - so now we got two three okay start is it is got four we got it's a three four and then three four so start for yeah start tasty adamant so we return start yeah we're accepted and the time as we are asked to its long and please find a research space constant okay that's all for this problem hope help see you next time bye | 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,752 | hey yo what's up my little coders let me show you in this tutorial how to solve the leadpro question number 1752 check if array is sorted and rotated let me just explain an example what we need to do basically imagine that this is our input array if we sort this input array this is what we will get so one two three four five check offer is sorted but also check if it's rotated so with the sorted array we also need to check if it has been rotated and when you rotate you just basically select like a random value x we don't know what it will be equal but in this case they explain that x is equal to three which will mean that you rotate the array by three positions so from the sorted array the first value will be moved to the right by three positions so from here we will go one two three after we rotate the array one should be here which is correct then the second value elsa moves by three positions so one two three then two will be somewhere in the end and yeah two is somewhere in the end with the middle element if you go by three positions we do one two okay there's then that's the end of the array so we will do like three and they'll appear here in the beginning of the array and four will go away so this value which is correct five will go to this value which is also correct so this array has been sorted and rotated by three positions and if the array has been sorted and rotated we just return true if it hasn't been sorted and rotated in this case we need to return false this is basically what we need to do guys how can we solve this problem efficiently without actually sorting the array and trying to rotate by the possible amount of uh positions let's think about some patterns okay imagine if x is equal to zero it's like the base case let's say in this case if x is equal to zero it means that we basically don't rotate the array because we rotated by zero positions which like will mean that we need to check if this array if the original array is just sorted if it doesn't rotate it we just check only if it's sorted or not but if x is not equal to zero but it's equal to like a positive number which is greater than zero what it would mean for us then it will mean that like if the array is indeed has been sorted and rotated it will mean that like somewhere you have like two small arrays which are both sorted and elsa the last value from the second array is not greater than the first value in the array this is basically the pattern and this is the conditions for which we need to check in order to identify if the array has been sorted and rotated in case if x is not equal to zero okay let's just code it guys okay guys so we create the integer to basically increment our counter and keep track of in how many places the values are not sorted if the counter will be greater than one at any point we just returned false straight away because it will mean that this array is not sorted and rotated at the same time but if you just find one place where the current element is basically greater than the next element in this case we'll increment the counter but if you will not find any other places where this condition applies in this case you incremented only one and only once and will not return false here in this case we'll iterate through the four array and we just will return true in the end but there is one very hacky thing here so we just we don't just check for the next element but we also do like i plus one and then mod the by the length of the array and what does this mod actually do okay let me explain you guys so if you start with the first value at index zero we do i zero plus one which is equal to one so we do one mod five because numbers of lengths is equal to five because there are five elements and if you do uh one mode five you basically get one then if you will go to the next element so i will be equal to one i plus one plus i is equal to two if you do two mode five you also will get uh two if you do like three mod five we get three if you do four mode five we get four but guys if you do five mode five if you get zero and what does it mean it means that like when it will iterate and will be at the last element and in this case i will be equal to four and if you do four plus one it will be five and we do five mod five you will get zero which will mean that like we will check the element at index zero so we compare this element with this element and in this case basically we will iterate through the four array and we'll check if there are two sorted sub arrays and the last value in the sorted sub array is not greater than the first value in the array and yeah it's basically equivalent of checking if the array has been sorted and rotated at the same time and if at any moment this condition will apply twice we just will return false otherwise return true this is basically all what we need to do so if i run the code now it works if i just submit guys if i submit i get hundred percent simply as that guys i hope it was clear and you understood everything please guys make sure you subscribe to my channel to not miss a lot of videos which are going to come soon and guys challenge your friends to see if they can solve this question or not then leave in the comments section the comment like saying which little question you want me to solve next and i will see you next video guys good luck | Check if Array Is Sorted and Rotated | arithmetic-subarrays | Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`.
There may be **duplicates** in the original array.
**Note:** An array `A` rotated by `x` positions results in an array `B` of the same length such that `A[i] == B[(i+x) % A.length]`, where `%` is the modulo operation.
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** true
**Explanation:** \[1,2,3,4,5\] is the original sorted array.
You can rotate the array by x = 3 positions to begin on the the element of value 3: \[3,4,5,1,2\].
**Example 2:**
**Input:** nums = \[2,1,3,4\]
**Output:** false
**Explanation:** There is no sorted array once rotated that can make nums.
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** true
**Explanation:** \[1,2,3\] is the original sorted array.
You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100` | To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic. For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic. | Array,Sorting | Medium | 413,1626 |
1,344 | hello and welcome today we're doing a question from week code called angle between hands of a clock it's a medium let's get started given two numbers our minutes returned the smaller angle in degrees formed between the hour and the minute hand example given our 12 minutes 30 we output 165 and here there could be two possible angles one between the minute hand and the hour hand or since we know that there are 360 degrees in a circle 360 degrees minus that so if this is X this angle between these two hands we could also output 360 minus X whichever one is the smaller of those two example 2 given 330 we output 75 degrees example 3 315 we output 7.5 degrees so we can 3 315 we output 7.5 degrees so we can 3 315 we output 7.5 degrees so we can also output decimals given 451 55 degrees and given 12 o'clock we output 0 because both the hour hand and the minute hand are at position 12 and constraints I'm kind of blocking this but our minutes are always between 0 and 59 and hours are between 0 and 12 so this is essentially just a straightforward math problem we want to return the smaller angle in degrees between the hour and the minute hand all we have to do is change the hour and minute hand into degrees to subtract and return the smaller angle and that would be our output so for minutes we have minute degrees equaling well how many minutes are in a full circle there are 60 so minutes divided by 60 and multiplying that by 360 to get degrees for the minute hand and we're dividing by 60 only to multiply again by 360 we can easily just do times 6.0 and I'm can easily just do times 6.0 and I'm can easily just do times 6.0 and I'm doing point o because we saw that we could output a decimal so keeping everything to float for a quick sanity check if there are zero minutes 0 times 6 is zero degrees if there are 30 minutes 30 times 6 is 180 we have our 180 degrees so we're going over here and same thing for our degree how many hours are in a full circle that is 12 so power divided by 12 and multiplying that by 360 to get our degrees but there is something we need to also keep track of the hour isn't sufficient because if the hour is 12 it's pointing right here we want zero degrees right but if it is 12:30 our degrees right but if it is 12:30 our degrees right but if it is 12:30 our hand is actually moved and according to how many minutes there are so we need to somehow combine the minutes and the hours and then convert that into degrees so what I'm going to do is first convert few minutes into hours and all the hours into degrees how many minutes are an hour 60 so minutes divided by 60 this entire thing is then going to be divided by 12 and then multiplied by 360 to get our degrees but there is still one more thing that we want to keep track of we reset every time we hit this zero mark if we get 360 we want to reset to zero degrees again so with the hours we also want to do mod 360 because as you can see here if we are at 12 o'clock we want to be zero degrees not 360 right so even at 12:30 we have our 12 minutes 30 so at 12:30 we have our 12 minutes 30 so at 12:30 we have our 12 minutes 30 so this is 12.5 divided by 12 a little bit this is 12.5 divided by 12 a little bit this is 12.5 divided by 12 a little bit over 1 times 360 we are over 360 but we want to reset each time we hit 360 which is why we do mod 360 and now all we have to do is return the minimum between our angles so return the absolute value of mini degree minus our degree and absolute value because the our degree could be ahead of the men we really No so this value or 360 minus that value right here so you can also wrap these into another parentheses run code accepted let's submit and it is accepted as well and time complexity this is just a constant operation math this is of one constant time same with space we just have constant variables so this is a one time and of one constant space if you have any questions let me know it down below otherwise I'll see you next time | Angle Between Hands of a Clock | maximum-equal-frequency | Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_.
Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** hour = 12, minutes = 30
**Output:** 165
**Example 2:**
**Input:** hour = 3, minutes = 30
**Output:** 75
**Example 3:**
**Input:** hour = 3, minutes = 15
**Output:** 7.5
**Constraints:**
* `1 <= hour <= 12`
* `0 <= minutes <= 59` | Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1. | Array,Hash Table | Hard | null |
1,675 | friends welcome to code Sutra in this video we'll be discussing about lead code problem number 1675 minimize the deviation in an array in this problem we are given an array for example this particular array and what is deviation it is the difference between the maximum element and the minimum element what is the deviation now the deviation is 19 but we have to reduce this deviation how can we reduce this deviation we can perform two operations one is you can pick up any odd element and you can increase the odd element that is multiplying it by two for example this one can be multiplied by 2 and this can be converted to 2. again you can pick up this 3 and you can multiply it by two that is one approach the second one is you can pick up any even element and divide it by two for example 20 becomes 10 and again since it is an even again you can perform the operation so let us dive into the intuition of the problem and the approach what's the intuition is say here it was one right now we increase the two so can this 2 be increased further no right why it can't be increased because any odd number once it is multiplied by an even number it will become an even number and you no longer can increase for example if this is the given array can you increase this any element of this given array no right why because all the elements in this array are even for example if we multiply the odd elements of this array by 2 . now can you increase any element in . now can you increase any element in . now can you increase any element in the array no right so this will be our maximum possible value of any element in the array so now none of the elements in this particular array can have a value greater than this so we have solved off of the problem that is any value we now know the maximum value of that what is the second step we have to do is to reduce the maximum value right so the idea is to minimize the gap between the maximum and the minimum value now we have increased the minimum values now the other option is we have to reduce the maximum value so how do we do that we pick up the maximum element in an array and we divide it by 2. again what is the maximum element of this array again it is 10 and we will divide it by 2. now can we go any further no right because this is an odd number and we cannot divide it further by 2. see here we do have an even number we don't want to care about that why because our maximum element cannot be divided by two so what is the answer in this case the answer is 2. so can we just follow this procedure and return the answer that is we will do all the steps then finally we will return the difference between the maximum element and the minimum element can we do that no right why we can't do that I will show you with an example for example this is 3 and this is 5 we have multiplied both of them by 2 that is we got 6 and we got 10. now let's go on to do it what is 10 by 2 will be 5 again what is 6 by 2 is 3. finally what is the answer is 2 but let's go on very carefully we had 6 and 10 actually become 5. now observe very carefully it is 6 and 5 and what is the answer now the answer is 1 why because this is the minimum possible value that we can get right so the idea is that every step that we are dividing the number by 2 we also have to keep track of the answer for example 1 in this case what do we keep track of the answer initially it was 4 now that we have 1 which is actually lesser than 4 will be updating our answer so that is the additional step that we'll be doing and one more thing see at every point we are finding the maximum value and we are divided git by two so what is the data structure that we'll be using here the data structure that we have to use is a maximum Heap or a priority Cube why because it's very easy or it just takes constant time or one to get the maximum element from in heat so that is what we will be doing we will be using a Max Heap to accompany this okay now let's discuss this step by step approach the first step is we will add all the elements in the priority queue but before adding that remember we have to convert all the elements into its maximum possible value that is if it is an even number we can add it directly or else we will multiply it by 2 and then we will add it also we have to keep track of the minimum elements while adding because this is a maxi we cannot go and directly get the minimum value so we need to keep track of the minimum value ourselves what is the third step that we'll be doing while the maximum element is even we will divide it by two that is what we were doing here right while the maximum element is divided by 2 divisible by 2 we were dividing it by 2 but don't forget you have to again add it back to the priority queue that is what we are doing but with addition to that we also keep track of the difference between the now maximum element and the minimum element at every point and also we have to update the minimum value at every Point finally we will return the answer so let me take you through the code so before taking you through the code please do subscribe to our channel uh we do here discuss the patterns and not just the problems for example if you have carefully listened to this problem and if you are aware of the maximum and mean Heap these are the problems you can go and solve it straight away actually these are actually two of them are hard level problems and two of them are medium level problems but you have understood the concept of minimum and Maxi you can directly go this and solve this problem what is the concept is very simple at every point we want to find the maximum value or at every Point what we are trying to do is sort the array right so if you know this particular pattern it is very easy to solve these four problems let me dive into the code what we are doing is we are initializing a priority queue why collections.reverse ordered because this collections.reverse ordered because this collections.reverse ordered because this is a Max Heap okay maximum priority queue that will give you the maximum element now we are adding all the elements into the priority queue one by one that is if it's an odd number we'll multiply by 2 and we will add it and we are keeping track of the minimum element at every point then once you are done with this what we do we get we just Peak them in maximum element and we see if it is divisible by two or not for example here this became five right we no longer can divide it any further this also became Phi so we no longer can go below this so that is what we are trying to do until and unless the maximum element is divisible by 2 we are going through the while loop and we are pulling it and we are again adding Top by two back to the priority queue but we also keep track of the answer and the minimum possible values finally we'll be returning the answer thank you for watching the video please do like share and subscribe | Minimize Deviation in Array | magnetic-force-between-two-balls | You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].`
* If the element is **odd**, **multiply** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].`
The **deviation** of the array is the **maximum difference** between any two elements in the array.
Return _the **minimum deviation** the array can have after performing some number of operations._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 1
**Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1.
**Example 2:**
**Input:** nums = \[4,1,5,20,3\]
**Output:** 3
**Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3.
**Example 3:**
**Input:** nums = \[2,10,8\]
**Output:** 3
**Constraints:**
* `n == nums.length`
* `2 <= n <= 5 * 104`
* `1 <= nums[i] <= 109` | If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible. | Array,Binary Search,Sorting | Medium | 2188 |
1,063 | Ajay Ko's management coding on the site So today we have to do number of balance sub address this question 21 What to do then name will get a chance There will be some elements in it Reverse proposal 132 So what to do in one question Basically all the sub balance surveys have to be rested If there were four such tights in the morning, then the first bandh should not be bigger than any of the elements coming next. Okay, this should not be bigger than any of the elements and for example if I share all the addresses in the morning 138 hands free. Tattoo and toe, a single person will be all over the world, okay, if we look at this survey, the first one is closed, if the rest is not bigger than any number, then this is also correct, okay, two guys got the cut, I am the first one in this morning. It is not bigger than any number coming next. Okay, so this is also viral. The only guy next is the invalid. If you look at Vishal Savere, then take this first element. One of the remaining elements is Monkey Two and if it is bigger than that, then this is wrong. Done okay and the last ignorance one guy would be velvet 12345 so there were five velvet savers in this okay so let's see the example if you don't in that 1425 three if you had got this then all the episodes starting one time one this is velvet One still one 1142 also one 114 125 and 1425 three plate diet all this white time lived that first Vrindavan Remaining was not smaller than anyone till was not bigger than anyone that is okay if that again that single guy will have to The first number has come, the coming ones should come next, Ankita, giving even, it has become bigger than this, it means it is not in balance, it has gone wrong, okay, let's write further, now it is about to change, so 425, this value cannot be tight, it is closed, Jhala was not bigger than this but it was two sevada, this is also wrong and it is also wrong for 253. Okay, if we look at the one starting with two, then two is correct. This cigarette is 125, you are Pavitri Devi carat, so it is not bigger than any of these. is tight at the end five 183 EFA which is it became bigger than the next one number this is wrong free this absolutely that in this whole 123456789 10 11 which is actually another one and if here because of these two 121 So if we go back this much time, it is closed on 221, it is not bigger than any of the elements coming next, okay here Lebanon or without value and equal to like this, then the right thing is okay, in the first comparison, it is bigger here. Or if it is equal to two then it is correct, it should not be boiled like you will succeed, you will fail, you will go wrong, okay, so the question was, now call this, you can check it as soon as you get the ad, how can you install it, plus it looks tasty, that in Australia. This was done last morning, it is okay to take out the first person, the quota should be equal to all the others or it should be equal to this one, let's do two, how far can it extend, how two or the only person, after the correct sa two, an elder son is tight here. It is still available because if it is increased to 1 liter later, then after 242, you can see here that there is a number about you which is great, subscribe to it and 876, if one person's reminder, then full credit. So how far will we actually be valid, I have 420 value or from that onwards if I subscribe here for this digit, then you can subscribe, it can become ghee, so see this here and after that. Ok, how to process, its small can be made and here is one ok lattu can only be made, ok, how many digits can be made, how long can it wait, its small is here, there is no editing smuggler, so this is complete One can also own and one-day and this is complete One can also own and one-day and this is complete One can also own and one-day and test and then share to A so let's see this decision. If I talk about becoming 4K smart about how to work, then here is the free white ship kitne bane valid hai work but when will These two together are coming to 251 and 205. Out of these Force for Banna, none is valid, we will pour one, see here, I can stop my work here, I have to do my daily point hr element, all of them can subscribe. Okay and this is me, then subscribe to all the upcoming ones later and so the same message has come, the pipe will also melt after drinking, free mode is closed, there is no one here, okay, so three sticks straight, this will go till the end and further. I have pipes let's take that one you try to do with pipes and this is the alliance 59 This is correct scholar form 595 This is also correct I got it in the condition that the first stop tax value should not be that I someone now take this right and here So now this is 20 minutes next on okay let's see once how we can do this through induction that if I have come out of all here zero one two three four five six seven 8 that if for four you know That friend, there was a smallr on Riya, okay, so you here the index reel of saliva jarad scholar value - index reel of saliva jarad scholar value - index reel of saliva jarad scholar value - 02, so three is basically telling you something completely or you can go till November three and how to write pottu oil and 425 tight one more. Write on 548 but these three temples are being built here, its current affairs and rally are fine - don't do this also affairs and rally are fine - don't do this also affairs and rally are fine - don't do this also and you can subscribe using 'Pitra Lag Rahein' and complete it. can subscribe using 'Pitra Lag Rahein' and complete it. can subscribe using 'Pitra Lag Rahein' and complete it. Well, if it is not there, then there is no meaning. Also valid model limit is not tight for this if I read somewhere that spa treatment here is a 1111 - 21806 see 1234567 and if there is 1111 - 21806 see 1234567 and if there is 1111 - 21806 see 1234567 and if there is no element I can fix the length subscribe element will be found for the element but here Listen Pem Log Light So what can we do here like we have done before Next Greater Element on Bright Okay so this time we are going to use pretty much the same programs, if you haven't seen then you will get it in the gender description now. Okay, so let's take the stress crispy, what do we have to do, so by the way, if you want to find this modal element, then you can use the extract on the directions, travel in this dress and travel with this, you can extract it from both, okay What are we going to look like? We will cover it the way we did the Next Greater Element online right hand. We will travel in this year and we will remove those brothers who do not require us to check. Okay, complete Gautam. What is going to happen is basically a strike, we are ok, first of all I am going to work for the last Sawan, 600, there was no smaller element here, pride, so ay in flight was considered after this, here is the eleventh index. We will keep this quarter inch and the value here - it is this quarter inch and the value here - it is not my government to keep the soil value, okay, I have just kept it here for viewing, okay, so its small size Banda Dahi 11 Index Pratha - Infinity, so Dahi 11 Index Pratha - Infinity, so Dahi 11 Index Pratha - Infinity, so write its minimum index here. Okay and then this guy is the one who is the 10th paintings screw okay who is the next monkey who comes next guy is no we are traveling through this okay 6 will check this basically check who is this 600 value in the track To your tank index indirectly or directly say so this guy go and check this is this he saw that the size is he is not bigger than me then there is no smaller than there now I want this volume un tight this is not the case then pot it From here this guy was fired and now there is no one in his small early stages means there is no requirement to do any chatting ok if there was no question then we will withdraw the cash eleventh index got Lavanda 1615 Ismail And this is non-inducting this is non-inducting this is non-inducting and has value, so we will keep it here, okay, the next round has come, what else will we do and basically it is lying in the track, we will check the next to-do list, okay, that lying in the track, we will check the next to-do list, okay, that lying in the track, we will check the next to-do list, okay, that one is not there, that too has been chopped, Jhaal Chop. Did it and then now there is no one in the style means there was no one with space then we will consider these flight ones 1190 it is smaller and it itself is affected by 8 and research and value now basically look there is no report of doing these two settings If you see a guy like this going into this dress where he is looking for the smaller element then if the hole is smaller then for 6 if the pixels are smaller than that then the for resolution will be smaller right to calculate it from these days This requirement will not be required, basically we had seen this logic chair on natural treatment, so let's see and also got the description of insight, drink water, it will cook, 8 injections will be visible on strike, fiber is also going and chatting with it, he is the one after me. If there is a small stop, then it will not become 80. This is cancer and put it on some tracks. Let's put the seventh in the next value. Let's click on five algorithms here. What did I do? I was the only person who came. He saw that there is one behind the strike. If he is younger than that then his answer is here Hans 72 died of cancer and he blew himself up from this or write again that we take the work from here, see what to do, first saw it on this track Six index is lying there and if there is no value then big value police checked this article there is no postmortem if it is not known then redwrap it and remove it from here tight basically what were we doing now this pick of this track is not inducing behavior Okay, the value of pick was one more than your current value, so we referred that guy, here five current one, so you and strike pick nine were placed it and not, stopped the next guy 1705 is also not difficult. Is this difficult, so I have typed Greater, so what have you done? Okay, the previous one has become Virat. Now we have the requirement to check from only one person, Siddhi. We saw that strike pet is next for value. Its use has been stopped. 8 minutes tight means keep locking all the guys, here Looper keep locking everyone and after this, whichever child's young cricketer will be this master element. Okay, so here you will get your small Valentine's Day. Yes I small inducts will be behind the track and Africa is guaranteed so we will accept the length okay what to do after this so here before we have never seen that you should have got more and now we keep so basically this is what I have done What was the index of the modeler - index of the current, so many are made - index of the current, so many are made - index of the current, so many are made right, so here we will add some more answer forces on it, this is the index of the model - but the current index is fine, so - but the current index is fine, so - but the current index is fine, so share it. Amazing that till now we have spoiled everything. I have done what all the work has to be done and on the last it has some time effect. This work has to be done on this track dots I. Okay, so let's implement it and see that we have to do elastic travel. Right on the last step will start and IS GREATER THAN IF IT GOES UP TO 200 SO OK WHAT SHOULD BE THE CURRENT VALUE OUR NAME [ __ ] OUR NAME [ __ ] OUR NAME [ __ ] KI AND BY THE PACK KE KEE BANDA HAI BACK DOT CIGARETTE NOW 0 KI AND TAKE CARE PICK I HAVE A VALUE MEANS UP TO ONE DOT PICK ON THE NUMBER IT IS BIGGER Or is it equal to the current value then turn it off Okay Baba it will be done and then we will do our work small index now by default name start length that if there is any guy left in my step practice is great 210 for respond one It will be 626 WhatsApp, my dear, now you can adopt it here that this is how it got small indexing - but it came that this is how it got small indexing - but it came that this is how it got small indexing - but it came and then after putting it on the track on the field, after washing it and acting it came, then this work is completed, midding is done from here, I am speeding up, the character is levering. Especially cancer and this course work is being done on it. Let's see the time complexity of Ramesh. Okay, let's see how much time it takes to calculate. Check the thread. Well, a little before this cute but time Intercity Express Salim. How to calculate so if I have a function and the interval was equal to 204 so this day's tour and travel agent I plus here one more loot here if this is going from zero to J also less Ben10 or Now let's ask if this is also a parameter, then we will get a variable, so basically it is fine, let's write for this portal - Adhya honi chahiye thi write for this portal - Adhya honi chahiye thi write for this portal - Adhya honi chahiye thi main tere ko 12:00 loop hai, that end time main tere ko 12:00 loop hai, that end time main tere ko 12:00 loop hai, that end time is going on and inside look time is going on. And here I and there, some consistent work is being done. Okay, so what will be the time complexity of this entire court, how do we decorate it? The value of I will be 0a, so what will happen to K is that this will not be 0, JJ will be that zero. The right will go from 0 to KK, the right will go from zero to cricket and every time a contract worker of semen comes in tight, then if I write in the time returns directly the tweet in which I write, then this will be the work of K Times of C1 and we can remove it too. I know that this is the whole people, he will unite K Times and is going to do semen's work every time, it is okay, when Bigg Boss was zero, K's work was done, this is Times Lucknow Asiwan Ka Aayi, Jab Hogi To K If there is a semen test for the content of the youth of Times and Ka, then there will be creative work. The value of semen will grow like this, the value will come - it will go till the end, it will stop tight and value will come - it will go till the end, it will stop tight and value will come - it will go till the end, it will stop tight and even in the end - CEO, if this much work is going to be done, even in the end - CEO, if this much work is going to be done, even in the end - CEO, if this much work is going to be done, then how many times will it happen? This much work has been done, call me, what should I do, the value means the total number of times it was running, but each time it has reduced. Cricket, today's time, soldier's time, C's, WiFi Plus's time, CEO 5 Plus's times, CO's, this is how the endtimes went. It will be difficult if I remove this End Times Where Times COAI and this Contest Monday now, then it is time to take the End Times decisions where N and Ki are both parameters of my input. Okay, that's why Israel is this Year, we apply all the methods here, so if we look at this group here, the values of I if we look at this group here, the values of I if we look at this group here, the values of I were babbar and minus one, so how much work did we do inside, if I look at so many people before this one, then this one So who was this right here, he is becoming a teacher and we have trained him, here we have presented the stars on the Pandit, here is the mathematical calculation and the tractor alam has also opened to put it, okay, all the work can be done by oven story or speak. Yes, this content and some of it is fine and the quantity will depend on this look. How many children will these people have? This look will work only when there is a person on the track and also this is the condition rule of the rallies. If this is the condition then it depends on the condition. So we ca n't bring Agri. How many times are these people going to run on? Right, they are proud that this loop will run only once or will run once. Okay, now we have done how many more, we have done one work or one work is hard copy. When the value of i becomes minus 2, then again I cannot give an in-depth review. Therefore, it can be said cannot give an in-depth review. Therefore, it can be said cannot give an in-depth review. Therefore, it can be said that it must have happened in the last few years and Sita must have been touched at the end minus 3. As the i grows, it will become a challenge, so let's assume i20. Z It's been a while since a person like this if I also cutlet how I went before I had added endtimes to all of them this time if I add all of these then I know that I have to add endtimes a Adding tight end times by doing plus b plus c plus d like this but I don't know what is their time, okay if you look at the year condition and look back at the WhatsApp message, if I had given it, you would have found someone in the track. Let's also pop it. All right, if this condition falls then this task will not happen and the loop will not run. Okay, so let's take a look in my entire code that I have reinforced the element in the track only at one place in the entire court. Have done end here and this line runs total end time, so you can say that there can be maximum elements on this track. Okay, if I can have maximum elements on this track, then this loop is Also maximum and temperature can mean that the sum of all these is that the director of lesbian equal to bank, it is not surgery that elements were inserted 1234 by doing this and all of them passed tight, it is not like that, it depends on above, so now someone Also, if you look at the time, then either there will be no one on this track of yours or there will be no contract in the set or then it will not happen that internally we will go tight, so A+B+C these people, the tight, so A+B+C these people, the tight, so A+B+C these people, the number of times an accident is going to happen, it is always from the end. This will be the record of garlic. Actually it should be and minus one. This is because when you last played Law of Attraction, you put value on this track and after that you never sinned. It's fine. If you look at the complexity of this one, now Govind will give all the less. Values on doing are that Govind will give all the less. Values on doing are that Govind will give all the less. Values on doing are that less Daily Quiz 2nd end is coming so if we look at the year condition then now you can say that N request O A plus B plus C It will be something like this All the people have left Okay so it is off bank workers Overall If it is complete then it is okay then Congress is such a mess, this is the solution that if you have learned something from this video then definitely like it or try our channel so that you do not do this in such videos. Thanks for watching. | Number of Valid Subarrays | best-sightseeing-pair | Given an integer array `nums`, return _the number of non-empty **subarrays** with the leftmost element of the subarray not larger than other elements in the subarray_.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1,4,2,5,3\]
**Output:** 11
**Explanation:** There are 11 valid subarrays: \[1\],\[4\],\[2\],\[5\],\[3\],\[1,4\],\[2,5\],\[1,4,2\],\[2,5,3\],\[1,4,2,5\],\[1,4,2,5,3\].
**Example 2:**
**Input:** nums = \[3,2,1\]
**Output:** 3
**Explanation:** The 3 valid subarrays are: \[3\],\[2\],\[1\].
**Example 3:**
**Input:** nums = \[2,2,2\]
**Output:** 6
**Explanation:** There are 6 valid subarrays: \[2\],\[2\],\[2\],\[2,2\],\[2,2\],\[2,2,2\].
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `0 <= nums[i] <= 105` | Can you tell the best sightseeing spot in one pass (ie. as you iterate over the input?) What should we store or keep track of as we iterate to do this? | Array,Dynamic Programming | Medium | null |
1,710 | hey hi my name is today i'm trying to solve the july the new month juliet coach new challenge so the question is maximum units on a track and the question number is one seven one zero so the problem is came as a liquid easy so the problem is given there the vector of vector has been given which has a uh the given uh data of the box type and i have a uh track size as an integer format and we'll have to return the maximum number of unit that can put uh onto the uh truck so basically let's take an example so there is an um list of list or the vector box type has been given so first part that is one that is the number box and the second one that is the number of unit per box has been present so the two of two has the same uh the first the number of bugs that is two and the number of unit has been present that is uh also two and the third one that is the number of blocks that is three and the number of units per box that is one so if i've been taking all of them and in that case the number of unit will be here there are some of them so basically that's eight so how i'm trying to solve that let's make first round then after that i am trying to implement my logic as a coding format first of all i am taking the input basically one and three then two and then three and one so what is given there basically i need to short according to the number of unit has been present as a reverse format but i am trying to reverse so basically i am trying to reverse because of i need the maximum number of unit i need the max number of you need in my truck so that's why i am shorting the array sorting the array resp with respect to the unit per box so uh i wrote down the uh list of list so as a reverse moment so there is no required to short there but if the any and the vector breaker has been given in that case we'll have to first short according to the reverse format of the number of unit has been present there so after that reverse format has been present so first i will check and also the track size is that is four so first i will traverse the ready and check there basically the number of box in boxes that is one and the in unit will be that is three right now and i am uh initializing a variable first there is the uh taking that the answer format so first i will check that number of box is greater than or equals to not first so basically the format has been fulfilling so in that case i am adding the value with that unit into multiply with the number of box number of blocks into the number of unit so you need so 1 into 3 so that will ends uh 0 plus 3 that is basically the 3 and it will deduct the number of blocks from the track size that is four minus one that is three right now and the answer is updated to three and second case in second case that is now that is 3 is greater than or equal to 2 yes 3 is greater than or equal to 2 right now i am adding the answer that is answer is equals to 3 plus 2 into 2 because i am taking that both of them both so that will answer the region 7 so and the unit reduced to it is 3 minus 2 i am taking the 2 box so 3 minus 2 that is one and after that right now so answer become seven so i have only one in it i have only one unit so i can only take the one top box only so one into one that is one so seven plus one that is eight so basically i am trying to there uh as i updated that and then after that as well as when the that condition has not been fulfilling in that case i am updating with there the answer and then after that i will as possible return the answer so basically the time complexity is order of in log n where n is the number of uh list and that means not number of lists that is the length of the list and uh i am not taking any extra space uh so basically that the order of one is the uh space complexity so i am right now trying to implement there first we will have to make an custom comparator okay and return the key of one open that is the basically the uh greater than format uh if i've been taking that's the uh shorting will be reverse format so first i will short the error box type begins not end and cmp that's done and now i'll initialize the answer variable for auto i up box type now type basically that is the box each box here i have been taking the for each loop basically so integer inbox is equals to boxer 0 and integer unit box unit per box is basically box of 1 if the truck size is greater than or equals to number of blocks in that case answer will be updated to inbox into unit box and after that the track size will be updated to minus of inbox and else case there is a terminator i mean that condition in that case the answer will be updated to the truck size into the unit bar box and after that i will directly return the answer and suppose you have been all the returning uh i mean travelers in the array so after that is also an option because in some condition uh truck sales has been much more bigger than the capacity of the box type so i in that case um the after all traversal that will be returning as an answer so i am right now trying to run my code to check if any compile time issue or not yeah it is accepted in the run code i am trying to submit ads got accepted thank you so much foreign | Maximum Units on a Truck | find-servers-that-handled-most-number-of-requests | You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`.
You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.
Return _the **maximum** total number of **units** that can be put on the truck._
**Example 1:**
**Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4
**Output:** 8
**Explanation:** There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8.
**Example 2:**
**Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10
**Output:** 91
**Constraints:**
* `1 <= boxTypes.length <= 1000`
* `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000`
* `1 <= truckSize <= 106` | To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add. | Array,Greedy,Heap (Priority Queue),Ordered Set | Hard | null |
126 | today we will solve a problem called world ladder and this is the second version of this problem so feel free to check the first version also so here we have a number of words in a list and we have to reach from word one which will be called the starting word and then end word so we have to reach from here to here and there can be multiple paths so it's not really a ladder it's like a graph and there can be multiple paths so uh the paths have a length so if we have multiple cities let's take some practical example city a b c d and we have to go from city a to d then maybe we need to go like a to b to c then c to d so this path has a length of 3 but maybe there are a few more paths a to c to d so this path will be two length and next let's say a two b and b two d this will be also of length two so there are two parts of length two and one path of length three so we are interested in the shortest one and there are multiple such paths so we have to return the list of all those paths so here instead of cities we have words and we have to transform one word to another and let's see some rules so uh if we have a word let's say abc just three characters in this word then from this word i can go to either a b and some wild character here i am writing asterisk or maybe a asterisk c or asterisk b c and this asterisk can again take multiple values so here the meaning is that just one character in the word is changing so from abc we can go to abd abe abf so just one character change is fine similarly ac acc adc and so on so you get the idea so we are allowed to go to a word w one two w w2 where there is a change of just one character and this word w2 will be called adjacent to w1 because there is a path between these two and these two will be said to be connected so in a graph we have notion of connected nodes so we can only go to connected nodes so if 1 2 3 4 is there from 1 we cannot go directly to 4 we have to go via 2 so from any node we can only visit its neighbors or adjacent nodes and in the terms of words this is what it means so now let's come to the problem so we have one starting word so this is the starting word that i was talking about this is the destination which we have to make and it will it can contain a sequence of words so words means nodes so it will denote a path so hit from hit we can go to we cannot go to dot because if you compare hit and dot you see that t matches but this first character does not match second character does not match so there is a difference of two but we can have a difference of at max one and these words the neighbors have to become from this list so these are all the nodes of the graph or here in this problem it's the list of words so starting is hit that is fixed ending is cog that is also fixed so we have to reach from hit to cog so from it which node we can take if there is no node which we can take then we will return an empty result there is no path so in the graph terms if this is a graph uh and this is the starting node s and there are a few other nodes and these are connected among themselves and let's say this is destination but s is not connected to any of those so no path exists from s to t similarly if no such word exists in this list then straight away return this empty list also here the adjacent word should be of the same length so it's not that abc is a word and then a b is a word so we can go here because this is just one character difference no the length should be same only the value can be different so this we have to keep in mind and it's given that you don't have to worry about this length difference that will not be in the input so from heat we can go to hot because there is hit hot so the difference is just here all the two words are same so we can go too hot from hot can we go to any other world from it no not no dog no other word from hot we can go to uh dot is one because there is just one character change and lot is another one so you see a graph is forming lot and any other no from dot we can go to dog and no other word from lot we can go to log from dog we can go to cog and from log also we can go to cog and this is the final word so we don't need to check further if we go further and maybe there is another path that will be longer so if even if uh from log there is some other word uh let's say talk and from talk there is cog so this path will be longer so we will stop once we process this so let's draw the graph from this so it is there let's draw the nodes hit hot dot dog then we have lot then we have log cog now it is connected to hot so there is a edge between these two hot is connected to a lot and dot then dot is connected to hot and lot and similarly log is connected to dog and cog and dog is connected to cog and log is connected to lot so this is the graph we are talking about so starting node is given so this white node is the starting one and this is the final node source and destination so this is a simple graph problem we have to find the shortest path from source to destination and there can be multiple paths of the same length same as the shortest one so we have to find all such paths so from s we go to hot from hot we can go to either dot or not both so you see we are proceeding in breadth first search manner so we start from a source we go to all the neighbors so just one neighbor so we come to heart from hot there are two adjacent neighbors dot and lot so these two comes next uh so let me redraw here so we have hit from hit we can go to hot from hot we can go to lot and dot if there would have been any other adjacent node we would have listed that also because this is the first node in the path the result this is the second node these two are candidate third nodes and we don't know from maybe from one of these we don't reach the destination so we will not include that but these three are all equidistant from this so we are wasting in breadth first such manner this node then its neighbors all the neighbors that are one unit distance from here then all the next neighbors this is level 0 level 1 level 2 and so on and let's say destination was here and there are multiple paths leading to this at level 4. so shortest path will be of length 4 and there are multiple of those so we don't need to check further below this so this is what we are doing so this is clearly a breadth first search so uh if you are not familiar with breadth first search i would recommend to check my uh video on breadth first search before coming to this because you can understand it but while writing the code you may get stuck so the idea is that we push the source to the queue so this node is listed the source here then we see all its neighbors and we push all of them to the queue so we pop this node from the queue and then push all its neighbors so at any time point of time so this three nodes are in the queue these three nodes are at level one now we take a counter that three nodes are there so we run a loop for i equal to zero to two uh keep popping them and keep pushing the neighbors to the queue so uh these white ones will be pushed after this yellow ones irrespective of whether their neighbor of this one this second one or third one but we have already taken the count what was the count before we started uh processing the next level that was three so for the next three we know that we are processing the earlier level now when this loop ends these all three will be from the queue and only level two nodes will be there in the queue again we will take the count and then keep pushing that so that elements are traversed in level by level in order so this is the essence of breadth first search in sort now here we are doing the same thing and then from lot so dot and lot and dog n log and then we have cog and this is essentially the two parts so we have to return here hit hot lot log cog this is one and hit hot dot cog so a list of lists so this is what we have to return so how we are doing let's start again so we have initially a list of words which contains uh so this it's given that this initial word or the end word may or may not be in this list it may be or it may not be so we will create an exhaustive list where we include all the words or we can skip the first one because this will be the first word that will go into the queue so no need to insert and then pop back again but we can do that for completeness so let's create a bigger list so hit hot dog lot uh cog and 2 4 5 and then we have log and dot so this is the exhaustive list so we will keep them all in a hash asset or unordered set in c pluses because we will be need to check access or find some words so we can keep them in a set and then what we will do we will pull out the first word and put it into the queue so now queue contains hit and in the queue we keep track of the running path so when we are at hit we are denoting all the paths starting with whose first word is hit we are extending this path until the last node is cog so this is a running path we are maintaining all candidates running paths so till here it was hit then when we reach here we have hit and hot so all the paths have to start with these two words only this is the only path now here we have two paths so this will fork two different parts that we need to keep track so after this level when we reach this level we will have two paths hit hot and lot and also hit hot and dot these two are running paths path one path two so we have to process this entire thing and we will we need to extend this path so when we are extending it we are only interested in the last word because this path is already built and what next word can come here so we have w1 w2 w3 in a path p and we are looking for what is the next word that can come here so we will only be comparing the last word in this running path and check what are the neighbors of this w3 and we will append all of those so let's say first word is w3x second word is w3y third word is w3 z these three all are neighbors of w3 so this path will result in three more paths and we have to process all of these maybe uh some of these lead to the target some of these does not lead so which whichever leads to the target that will be part of the answer so you see uh we are keeping track of a running path this you have to keep in mind while writing the code and we are extending it extending the path based on the last word so that it forms a sequence w one two w two to w3 and so on so initially hit is there in the queue then we run we write a simple bfs code while not q dot empty till the queue is not empty keep doing it so uh we have path which pop it from the front so get the front and also pop it so now hit is removed so this path is denoting hit and this is not the complete path it's the incomplete running path so currently it has just one word but this will get extended now we pick the front and we see what are its neighbors the same thing we do in normal bfs we pop a node and then look for all its neighbors so we will better to define a function find neighbors in the code and we will pass a word and this word list and this will return a list of all the neighbors or you can write here also but better to create a separate function so this find neighbors will return so its neighbors are hot and nothing else just one so we will append if this is multiple words then just see here so hit hot has two neighbors lot and dot so this path will fork into multiple paths the same as number of neighbors so currently it has just one so the new path will be uh hit and hot and this will be pushed to the queue so now q has hit and hot now again q is not empty so we will pop this one so now path contains hit hot and this is popped so this one is gone next this is the path so we only check the neighbors of last word we are not bothered about this is already a semi path so what are the neighbors of what those are the candidates which can come here so again we will call find neighbors it will return uh heart has neighbors lord so these are neighbors lot and dot so two neighbors this time so we will have two new paths so we will insert all of these two in the queue again so q is here empty but we have not went till the end of this while loop so before reaching here again these two will be pushed in the queue so the new path will be hit hot then lot so this will be pushed to the queue here and hit hot dot this will also be pushed now the queue has two parts hit hot lot and hit hot dot these two are in the queue so again q is not empty so this we will uh first remove the first path so p is hit hot lot then we will find the neighbors of lot which are dot and log but dot we have already here so when we process a no label we also remove all the nodes which we just processed so here uh when we included this lot and dot into it and we are now ready to go back to the beginning of this loop before that remove this lot and dot from the this list so dot and lot removed similarly in the beginning it was removed next hot was removed so that we don't reach to that node again in the next level so it's okay that it's ok to be like this so this is node 1 node 2 node 3 node 4 node 5 and let's say this is also connected so it's ok to have reach this node 4 so we can reach this node 4 from multiple nodes in a previous level so once we process this we have to remove this four once we have processed both otherwise if we just process two and remove four then we will never find this edge so once you process all the nodes in a given level you remove all the nodes which we just visited so we will have a visited error also which we will remove from the list so that next time now 4 is gone so in the next level when we reach 5 we will not include this edge because from 1 to 4 there are two parts of length 2 so there is no point in reaching 4 with 3 edges that will never be the shortest maybe from 4 we are reaching the target so this path the white one this is 5 let's so 1 2 4 5 this is a path of length 3 similarly 1 3 4 5 but if we allow this edge also here this one then the path will be one three five four maybe make it six this length is bigger so that's why we are not bothered about this length so as soon as we uh process all the nodes in a given level remove all the visited nodes from the list so that we these are never discovered again these are already listed uh so dot will not be included here since we would have removed this dot after third level or second level so dot will not be here so uh log will be here just one neighbor and the next we will pop this one the second path so it will be hit hot dot and then dog so now these two are removed from the queue so q is now again empty and now we have processed again a new label so we will remove which words log and dog from the list so this list dog and log are removed now in this list just cog remains now again these two are in the queue so the queue has hit hot lot log and hit hot dot dog these two paths are in the queue so again the queue is not empty and we have also not reached the end word so you will see that we will later keep track of whether we have reached the target word or not using just a boolean flag now we pop the front element so path is hit hot lot log so what are the neighbors of log we will search in this list so we will find cog just one neighbor so we will append just one neighbor and push it to the queue and next one and also since this is equal to the destination we can now be sure that next level we don't have to process this is the last level we are processing so this is removed from queue next this one is popped hit hot lot dog next we find neighbors of dog which will be cog so you see why we are not removing uh this in between we remove the nodes only after we process all the nodes at a given level because there can be same thing multiple paths from previous level to a given node if we remove after wasting this first one we will never discover the second one so again it will find a neighbor just one neighbor cog so we will just append cog and again uh we will add this so as soon as we reach a destination the last word we add this running path is now complete so we will add it to result similarly again here cog is reached so again we push it to the result so in this case two parts will be there so you get the idea now once you are comfortable with this reasoning why this is so we are ready to start the code so let's implement our logic so you can go through a few more examples so in this case the path is empty there was no path from heat there is no neighbor of it here or a heart is never then we can go to dot then dog a cog is not in the word list okay so cog is not in the word list therefore there is no valid transformation sequence so if the last word is not there then again it cannot be formed and begin word does not need to win the word list okay so that should not affect anything what we have seen now uh we will need a function to find the neighbor so first let's complete that so that should return a list of neighbors or a list of words and words are string so vector of strings find neighbors so this should take from the word and also this reference to the word list so how do we find one ways that you pick all the words in the reward list one by one and start comparing so that should also work one another way is that uh using this logic so what we were seeing here you have this one so we were saying that this asterisk character so first we are replacing the first word with b c d try all the letters so these are made of small english letters so we can try replacing all of those and then match whether that word exists in this list or not so we said that we will convert this to a set so that searching is easy so instead of vector we can have an ordered set of this one and here we will create non-ordered set and here we will create non-ordered set and here we will create non-ordered set otherwise searching in this vector will be one by one you so first we will replace the first letter with all the letters in english alphabet smaller letters then the second letter third letter and so on and then we need to restore the word back so that's why we are saving what was the earlier character you so what we are doing here so we replaced first character with letter a so this word the new word is different from the original word by just one character and we then find whether it exists in the word list or not if it exists then it's never and if it does not exist we do nothing then we replace the second character again by a to z we try all the combination and again the third character in the word by all the combination and then find in this has set and finally when we are done with it we restore that character back otherwise the words will change now we have the function ready we are ready to write the main function so result is a vector of a strings then we will need a cube so this is the running path initially just in the begin board all the parts will start with this node and this will get extended and fold forward into multiple paths then reach to end this we have to keep track when we reach end we add that path to the result and also we don't proceed further to the next level and remember we need to remove all the nodes once we are we have processed all the nodes at a given level we will remove all the new words that we reached or included in the path so this will we will keep track invested now the normal bfs thing while not q dot empty so this loop so initially we find how many nodes are there in the queue if it's let's say five then this loop will run five times and it will also be pushing the neighbors back to the queue so we will not be able to segregate which one was from which level but before starting that pushing any node from next level we keep track of how many nodes are there in the queue that's how we process all the nodes at a given level together and then after this loop this queue will only hold the nodes at the next level and again we will find the size and again so this helps in processing the nodes level y level so this is the path we can write p for path running path which the same thing we used in the explanation so this is the running path or prefix of the path not the complete path ah then q dot pop and then the neighbors of the last word here in this running path last word author not back the last word and then we need to pass the word list not this vector but this set so that this function is faster if we find in the vector again it will work but it will take off and time here it should take lesser time since it's a hash set so these are the neighbors so if there are three neighbors we will append all the three words to this path so this path will grow and it will break into three more paths but if there is just one neighbor then the number of parts will remain same so uh so we have to append all the neighbors all the words in this list at the end of this path and then push them all to the queue so vector string new path so this is the current path you can write current path or just path so here it's just a copy of this path then we have to append and we also have to push it to the queue and so this neighbor was included this neighbor j was newly included in this running path so once we are finished with all the nodes in this level we will remove it from the original list and this is which we keep track in this widget and this is unordered set so it will not allow duplicates if a node is reached from multiple nodes this will be inserted only once you cannot remove more than once anything from a list so visited dot insert this neighbors j and one more thing we need to keep track of maybe this neighbor's j was the target word or the end word then if we don't keep track of that if we don't compare that we will keep processing it till we reach the maximum level so we have to also check whether uh that is the case or not so if neighbors j is equal to end word then this should be added to the result so result dot push back this new path and this is the complete path now also we will make this reached end equal to true and once we process all the nodes at this level we will check whether reached end is true or not if it is true break out of this while loop so we are pretty much done here uh we need to come here so the ending bracket is here uh and we need to remove these so now we have removed the nodes that were just visited in the previous level so that we don't reach there again with a longer path and then uh widget also needs to be cleared otherwise it will have unnecessarily hold elements which are already deleted and finally we return the result and let's see if it works uh it's a long code so don't get too worried if you get some compilation issues in the beginning push back new path is a vector of a string and result should not be this you can see the return type it vector or vector of a string so vector of a string denote one path it's a vector of those paths spelling mistake uh hit hot dot dog cog yeah so it seems to be fine and the solution is accepted here so you can try in other languages also it's a very long code writing in python and java again would take maybe 10-15 more minutes maybe 10-15 more minutes maybe 10-15 more minutes so if you have any better solution you can share your comments thank you | Word Ladder II | word-ladder-ii | A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _all the **shortest transformation sequences** from_ `beginWord` _to_ `endWord`_, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words_ `[beginWord, s1, s2, ..., sk]`.
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** \[\[ "hit ", "hot ", "dot ", "dog ", "cog "\],\[ "hit ", "hot ", "lot ", "log ", "cog "\]\]
**Explanation:** There are 2 shortest transformation sequences:
"hit " -> "hot " -> "dot " -> "dog " -> "cog "
"hit " -> "hot " -> "lot " -> "log " -> "cog "
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** \[\]
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 5`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 500`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
* The **sum** of all shortest transformation sequences does not exceed `105`. | null | Hash Table,String,Backtracking,Breadth-First Search | Hard | 127,2276 |
284 | hello everybody this is larry this is day 25 of the august record daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about dave's farm i have some like allergy stuff yeah tree allergies what am i gonna do my choice problem is peaking iterator design an iterator that supports the peak on an existing elevator what's an iterator just okay so that you're given an iterator and you're basically trying to do a layer such that it um it has a supports a peak function that's okay that's basically um hmm what do you want me to do iterated oh i say this is what this is okay i mean this seems pretty straightforward it's just about you know pre-caching one answer i you know pre-caching one answer i you know pre-caching one answer i suppose um and that's basically the idea i think so it should be okay um it's kind of a tricky thing to um conceptualize around to be honest because i think iterator is definitely not necessarily a beginner's um thing i mean it i guess it's like beginners but it's not necessarily like i don't know uh so i think being able to this and this is maybe somewhat it's not specifically language specific but it is um like understanding of your language will help a lot you know technically this is not how you do iterator in python but yeah we'll live uh yeah and then now what do we want to do okay so first we keep track of the iterator but this is all implementation so i'm gonna instead so i don't have anything like overarching talking about it i'm just going to go over it as we solved them uh also uh my neck still hurts a little bit so bear with me as i maybe struggle a little bit in uh in agony but oops okay so peak what we want so what we want to do is create the next item right so maybe something like next item is you go to iterator.next iterator.next iterator.next um i don't know if i want to write it this way but conceptually something like this right let's just say maybe uh peak cache is you go to uh self dot peak maybe someone like that i don't know what and the idea here for us is just that we already have self.iterator right that we already have self.iterator right that we already have self.iterator right um so now we want to do um okay if it has next then this we said this is you go to well next object as you go to um next is you go to self.iterator.next um next is you go to self.iterator.next um next is you go to self.iterator.next so now we get the next element and then in the peak cache we just set it to the next element um yeah i mean i think it i was going to do something like an explicit has next flag but maybe this is fine and then else self.peak cache is self.peak cache is self.peak cache is you go to none because it doesn't have an x right and then now that's pretty much the idea here or i don't know about like this naming but maybe uh check next uh p cash peak maybe i don't know naming is hard so definitely absolve yourself there peak okay now that we have that ready peak then is just returning um let's see let's peek without moving the pointer i was just curious what happens if there isn't uh the next element so okay well i guess it just assumes that there's always a next element okay all calls are valid so okay so then that means i sell that peak cache and we can just return this it will just be the next number uh the next then is just uh result is to go to self.peak result is to go to self.peak result is to go to self.peak cache and then self.um cache and then self.um cache and then self.um you know do the thing where we repopulate it and then we turn result and then has next is just return self dot peak cache is not none right because if it's not none that means that we have a next element that we can fetch um you can of course separate this into two explicit variables you like um here i'm a little bit lazy today maybe uh hopefully this is good uh okay so this is wrong why is this one seems like this is mostly right except for the first next oh is next supposed to return wait hmm oh i think i just messed up here because i think i wanted this to write a different way so i wrote this thing but actually what i need what i just needed is this but because this returns none it actually flushes the first thing to none uh but this is why you test code because you know silly things like this happen and of course this isn't type safe because this is python so it was harder to spark than maybe normally but as you can see this is good um yeah i mean is that good i guess technically we didn't test the thing where we have has next return true but i feel like this is mostly what i want so let's test that really quick and let's give this a minute apparently i did it about a year ago hopefully this is right yes 755 everybody uh cool uh just to go over the thing i mean i don't think there's that much to go over um this is go everything is all one this is all one because just return variable this is technically of one in the sense that everything else other than the cat this functions of one this function technically speaking you don't know the cost of getting the next i object in the iterator it may take a while there may be some amortized cost but the extra cost would be all one so this is you know the same as the iterator itself um so yeah it has next is obviously all of one so yeah so everything is over one maybe some ammonization with respect to whatever the original iterator is you can think of for example if this was like next permutation or something like that um i mean i guess this is always intimate but if you have an iterator that returns all the permutations for example it we might have an over n where n is to the size of the collection in terms of the running time in the worst case but amortize all one or something like that right but even then that's just depends on the iterator so this is not your responsibility per se so this is going to be close enough everything outside of the original function cost is all one so yes i'm super happy about this uh that's all i have for today though uh let me know what you think i'm gonna lie down and just rest my neck uh oh people problem so take care of your posture i need to do something about anyway stay good stay healthy to good mental health i'll see you later and take care bye | Peeking Iterator | peeking-iterator | Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations.
Implement the `PeekingIterator` class:
* `PeekingIterator(Iterator nums)` Initializes the object with the given integer iterator `iterator`.
* `int next()` Returns the next element in the array and moves the pointer to the next element.
* `boolean hasNext()` Returns `true` if there are still elements in the array.
* `int peek()` Returns the next element in the array **without** moving the pointer.
**Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions.
**Example 1:**
**Input**
\[ "PeekingIterator ", "next ", "peek ", "next ", "next ", "hasNext "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 2, 2, 3, false\]
**Explanation**
PeekingIterator peekingIterator = new PeekingIterator(\[1, 2, 3\]); // \[**1**,2,3\]
peekingIterator.next(); // return 1, the pointer moves to the next element \[1,**2**,3\].
peekingIterator.peek(); // return 2, the pointer does not move \[1,**2**,3\].
peekingIterator.next(); // return 2, the pointer moves to the next element \[1,2,**3**\]
peekingIterator.next(); // return 3, the pointer moves to the next element \[1,2,3\]
peekingIterator.hasNext(); // return False
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 1000`
* All the calls to `next` and `peek` are valid.
* At most `1000` calls will be made to `next`, `hasNext`, and `peek`.
**Follow up:** How would you extend your design to be generic and work with all types, not just integer? | Think of "looking ahead". You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google's guava library source code. | Array,Design,Iterator | Medium | 173,251,281 |
1,095 | hello everyone welcome to my you programming club today we will be solving another daily El Cod Challenge and the name of challenge is find in Mountain array so it is mentioned that it is a interactive problem uh you can recall an array you can recall that array is a mountain array if and only if the following condition satisfies so there should be at least three elements in the array and basically there should be a peak element in the array there should be element I such that before that particular element uh the till that particular element the array is in increasing order so from 0 to I you can see that the array is in increasing order and after that the ARR is in decreasing order so two adjacent elements cannot be equal here the equality is not mentioned here okay so something like this could be there till a particular index let's say I the are should be in increasing order and after that it should be in decreasing order so given a Mountain array return the minimum index such that mountain array. get index equal to Target if such an index does not exist you should return minus one okay so you cannot EX access the mountain array directly you may only access the mountain array interface so Mountain array interface will be containing two methods one will be Mountain array do get Returns the element at index K okay and another will be Mountain array do length Returns the length of the mountain array so your submissions making more than 100 calls to this particular function Mountain array. getet will be just wrong answer also it is mentioned that any solutions that attempt to circumvent the judge uh will be resulting in disqualification let's have a look at the constraints according that uh we will be forming our solution so the length of mountain array is ranging from 3 to 10 to power 4 elements and the target is between 0 to 10 to^ 9 and the mountain array do get index will range from also range from the same range in which the target is 0 to 10^ 9 okay is 0 to 10^ 9 okay is 0 to 10^ 9 okay so we will try to solve this particular problem in the most optimal way possible so without further delay let's see how we will be solving this problem so to solve this particular problem what we will do is since there is a limit on get function so we should try to write most optimal answer that we can so if we have to search in this particular Mountain array then instead of linear search will require you at search linear search will require you at Max order of let's say n calls where n can be the size of your Mountain array n will be your size of mountain array okay so to reduce the number of calls to get function uh you should use binary search that will require you at most order of L and calls it will be uh little more than that but uh the order Remains the Same so it will reduce your number of calls so this is the most optimal solution I can think of as of now which will be there but you may ask the array that we will be given will not be in sorted form so it can be something like this uh 3 4 5 and then let's say it is 4 3 1 so as you can see the whole array is not sorted but uh I would say is that this portion of array and this portion of array these two are sorted the whole array is not sorted I know but uh these two are sorted uh it is sorted in decreasing order and this one is sorted in increasing order binary search can be easily applied here we just have to find the peak element for Peak element also to reduce the number of FS number of calls to get function uh we can use binary search so in total how many binary search will be used uh one then two and then three so three binary searches will give us the index of the Target or I think the smallest index is mentioned given a mountain array you have to the minimum index yeah minimum index you should return minimum index okay so let's try to implement the solution those of you who are not familiar with binary search I will be providing a link of uh an article describing what binary search is can explore that link and you will be able to understand the problem in a much clearer way so this particular article will be provided to you link of this article okay here it's uh mentioned in that how B search works and it implementations in various languages so let's move back to the problem let's try to implement it first of all we will find the peak element of the M array finding the peak element of aray we are using binary search on the search space comprising of indices of the M AR okay and one thing I would also like to mention is yeah I think it's fine let's proceed uh let's declare the left and the right ranges of binary search first of all let's capture the size of the mountain array let's shorten this name m ARR will be I think fine okay so the limit is only on the get function okay not on the length function but we are using it only once okay and then last index from zeroth index to last index we will be searching and this is just a standard binary search with some little twixs here it is to be noted that I not uh allowing left to be equal to write since I will require at least two elements to make comparison what will be the comparisons I will uh tell you along the way so we will find the mid index which will be nothing but left plus right minus left by 2 this uh left + right minus left by 2 is nothing but + right minus left by 2 is nothing but + right minus left by 2 is nothing but if you simplify it left plus right all divided by two this is just to avoid integer overflow okay and yeah so we will be comparing the mid element and the element at the mid index and one element next to it if let's say the element at M index m r dot get mid index is lesser than m.g mid m.g mid m.g mid index + one so the next element very index + one so the next element very index + one so the next element very next element to the mid index then what we will do is left of your range will be shifted to Mid index + one range will be shifted to Mid index + one range will be shifted to Mid index + one so why we are shifting the left of your range to Mid index + one so consider range to Mid index + one so consider range to Mid index + one so consider this case if let's say you are here this is your mid index and the element next to very next to it is greater than this so to find the peak element you should be moving in this direction so to move in this direction your left of your range will be shifted to your mid index + + + one okay that's why we are doing so and also uh let's Define a variable Peak index basically initially it will be having a value of let's say last element okay you can give it any value it will change so Peak index will be will also be this mid index + one since we index + one since we index + one since we are uh required to find the integer of the peak index so this particular binary search will be to find the index of B element in Mountain array okay and yeah let's proceed further and if that's not the case and if let's say you are in this particular region okay so if that's not the case and your mid element or mid index element is uh it uh two elements cannot be equal so this will be that uh your mid index element is greater than uh this particular element which is nothing but mid index + index + index + one okay the uh you are in the decreasing you are in the on the uh descend uh not on the Ascend part so you are in the decreasing part then you will uh what you will do is uh El if array of mid index M or Mountain array do get mid index or we can avoid the call of get here we can just use else only since it is well understood that you are trying to implement a condition something like this so just to avoid this call we are using else okay uh this get what call I talking about the a call of get function okay and since we have are not uh we do not want to lose mid index it uh it can be our Peak index why it can be our Peak index uh because uh this particular condition that we are checking also satisfies for the peak index uh this element will be uh greater than uh the uh very much next element to it so uh array of I will be greater than array of I + 1 because after the than array of I + 1 because after the than array of I + 1 because after the peak element uh the array will be in a decreasing Trend okay so that's why we are doing so and so we will just store your right will be mid index not + one only mid index not + one only mid index not + one only mid index okay and then what you will do is uh we will try to find the peak element index in right part first you can choose left part first also that will not matter uh by using binary search in uh right part will be comprising of uh which will consist of or comprising of indices uh from Peak index size minus one okay so let's define Let's uh redefine the values of left and right so your left will be now pick index and right will be having value of size minus one okay and in this particular part we are not interested in comparing two adjacent values so we will be using the condition left equal to right okay and we will be uh using a standard binary search implementation without any Twix so let's solve the problem uh first we will be finding our mid index which will be nothing but left plus right minus left by two uh if you are still not able to understand why I'm using this condition I think it should be mentioned in this article why they use why we use this particular condition mid is equal to as you can see this particular uh way of finding the mid is also used here so I think it should be mentioned in the article if uh it's not there uh please ask in the comment section I will be more than happy to answer uh with further elaboration so we are done finding the mid index and then we will search for the Target uh yeah Target if your let's say mid index value is lesser than Target value then what you will do is oh first of all let's check if uh mid index is having the value of Target or I think it's fine we will check it at last so left will be shifted to Mid index + will be shifted to Mid index + will be shifted to Mid index + one okay and then if that's not the case and if your let's say value at Mid index happens to be greater than the target then you will shift your right to basically uh in these two cases you are just reducing your search space okay so mid index minus one it will be and as if you have hit the target if you hit the target then you will return true or not return true uh you will be returning the mid index so this will be the index of your target okay and similarly you will do uh binary search to find the Target in left hand side if it's not there in the right hand side okay we can just copy this binary search and we try to find the peak element in the left side of peak element by using binary search in left part which comprise of the indices from 0 to P index okay so these values will be changing instead of peak index left will be at your zeroth index and right will be at your P index I think rest all should remain pretty much the same I think we have done a mistake here uh since we were doing binary search in the right part we should have uh considered that it is in decreasing order so we should reverse the signs only then it will give you correct answer so I think uh you understood that uh why we are reversing the signs because this binary search we will considering for the increasing array so to uh accommodate the decreasing array we are reversing the signs uh this one is correct for the increasing array okay so your right will be pointing to the P index and then yeah pretty that's pretty much it I think uh at last you can return any value or if it's mentioned that if answer does not exceed you should return a particular value let's check uh yeah it's mentioned then you should return minus one if the target is not existing so we will do as the problem ask so we will return minus one I think there is one brace extra in the implementation that I have used yeah uh we have implemented these two binary seches inside the first binary search anyhow uh we will Rectify that by moving it out of these two binary searches will be moved out of the first one so this is your first binary search and these will be the other two binary searches so let's try to submit for the sample test cases it's giving some compilation error okay here I by mistake took at n minus one which should be size minus one so for one test case it's giving incorrect result I think I found out the mistake here we are getting wrong answer uh because we are finding the occurrence of three here this particular occurrence we are finding but we should be giving this answer so we should be checking in the left part first instead of checking the right part first so order really matters here I thought the order will not matter but the order matters so left side will be checked first left side of peak element first uh because uh we have to return minimum index of occurrence of Target value okay so let's try to submit again for sample test cases as you can see it's getting EX accepted now so the mistake that we did was Finding for the right part first so you should be finding checking the Target in left part first in order to give the minimum index possible of Target occurrence so Target can be existing here also and it can exist here also as you can see in this particular example or sample test case three is existing here and three is also existing here so this is the your Peak element so it is existing on the left part and the right part if you uh do binary search on right part first then you will give the higher index So to avoid that case we will do binary search in left part first let's try to submit it for the final evaluation as you can see the solution is getting accepted so the code will be available in C++ and Java both uh and I available in C++ and Java both uh and I available in C++ and Java both uh and I will also try to make it available for Python 3 so thank you for watching if you are still having any doubts please feel free to ask them in the comment section I will be more than happy to answer them thanks | 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,237 | hello and welcome today we are doing another liquid problem on binary search okay so this is the problem find the positive integer solution for a given equation let's see what is the problem statement it says that given a callable function if y function f which have parameter X and Y with a hidden formula and value set okay reverse engineering the formula and return all positive integer pair x y where X Y is equal to function of X Y is equal to Z okay you may return the pair in order okay we have to return the pair in order let's see what is the explanation of this so here we have function ID we don't know in the function which formula is used we don't know okay so the function ID is one and it says that the target value is 5. so here if we send one by one a value from 1 to any number okay that way we'll decide in future in the further video uh the limit of the x or y okay the follower it says that the following positive integer x value of X and Y makes make function of x y equal to 5. X Y X is 1 Y is 4 equal to that gives X Plus 1 that is equal to 5 yeah it is equal to 5 which means it This Is The Answer 1 comma 4 means X is equal to 1 and Y is equal to 4 gives six five for the function id1 let's understand in the both we have for question is saying that we have a custom function which take X and Y and we have to find Target 5 okay suppose we have to find Target 5. let's start let's take the limit let's X start from 1 to n or we can say let's take hundred let's take 100. let's take hundred and why will you start from 1 to 100. okay what it's saying that we call the function click on the function X and Y okay so suppose for first I is X is equal to I and Y is equal to sorry X is equal to 1 and Y is equal to 1. so if suppose let's say that let's take function will give will get some of two number but it is not the case because the function is the rule of the function is unknown okay there is a hidden formula we don't know what is the formula inside the function but it can be addition it can be multiplication it can be division okay so let's we are taking the uh let's we are taking the function will give sum of two number okay so what this one if we call this function the function suppose we are giving one comma one so what it will return it will fit to okay let's check with Target this is equal to Target no this is not equal to Target okay so let's increment the X so let's say increment rights let's take X is equal to 2 now it will give 3 this is equal to Target no let's take Y is equal to 3 now so this will give four so Target this is equal to Target no okay let's take Y is equal to 5 Y is equal to 4 sorry this will give now 5 this is equal to Target yes because Target is 5. it means we record the first pair we got the first pair let's store in the answer stored in the answer we got the first pair okay we got the first pair now we have to actually Store the store in the ascending order okay means in order means we cannot uh actually we have to store in ascending order which means the first means we cannot store like this 2 comma 4 then 1 comma 4 because in the answer here we can see that this is in the increasing order the first letter is 1 then 2 first element is one two and three then four okay so we use this order so for this order we got the for this function we got the Answer 1 comma 4 now after getting the answer let's increment X now increment X call the function increment x is 2 and this will start from one means i y again start from one now this will give three which is not equal to Target now change it to the 2 so this will give four this is not also not equal to Target now make it three now this will give five yeah it is equal to Target so our next pair is 2 and 3 our next pair is two and three okay we got the answer okay then again increment X and increment the X let's see and this y become one again okay now this will give four not equal to okay now I increment the y then 2 then this will give five which is equal to Target this means we got the another pair like three comma 2 3 comma two okay now increase the 4 increase the four sorry increase the X and make Y is equal to X now become 4 and Y is equal to 1 this will give 5. this will get 5 okay which is equal to Target so we got another pair that is 4 comma 1 that is 4 comma one this is for we got the four pair okay now after getting we increase the 5 we increase the X sorry to the five now y become what now it will give six it means they exceed the off it means ah every it means that if we increase whether value of x or y this will give always increasing means a larger number then Target value okay so we have to solve from up to this only okay oh let's solve this problem using binary search concept okay let's take it now here one more thing there is a constraints function ID should be one two nine that is means there are nine formulas okay and the answer will generate from one to thousand between one two thousand and the value of X and Y it up to 1 2 000 okay so we are taking here x is equal to in X is equal to 1 and in y is equal to 1 okay and we are taking the answer we have to return the answer Vector of vector so we are taking this variable that is answer okay now we are looping through from we start from X up X is equal to 1 and X will is smaller than equal to thousand and it will run up to Y is smaller than equal to 1000 okay now let's find int f is equal to we call the function that is custom function dot f that will give X and Y which return any solution let's check if f is equal to Z that is the target value if it is equal to Target will then our answer is equal to answer dot push pushback we have to give the Vector okay X and Y so here is it now after getting the answer we have to increment the X and Y become 1 as we discussed in the explanation okay now if Z is greater than F if Z is greater than f which means that if we say that we are sending 1 comma 2 1 comma 3 1 comma or a one comma one so in this case we are getting two we are getting 3 we are getting 4 and we are getting five okay so up to here the answer is smaller than Target means the answer is smaller than Target so we have to increase the Y okay we have to increase the Y here we are increasing the Y okay so we are increasing the Y so here also we increase the Y okay now else part else if Target is greater if sorry if answer is greater suppose answer is greater here we got the answer that is 6. you got the answer that is six okay so what we can say here we can increase the X okay we can increase the X and make Y is equal to 1 okay or we can break it or break we can break it or we can break it okay we can break it here because there is no use if the answer comes uh greater than this then we can break it but there is an also chance I have it we can break it let's check if you want to break from here check the answer will come here or not return answer okay return answer let's run this okay here we are class solution this is and this and solution okay actually oh sorry for the other okay we got the wrong answer why we are getting long answer so we do not need to actually break it here we can increment the X and put Y is equal to 1 okay let's see what will be the answer we got wrong answer why we are getting romance so let's check our solution okay let's check our solution yeah actually the problem is that here we are checking the if else condition uh okay actually here we are using IF else condition but we forget to give else if here okay so first we this will check this and after this condition if this condition will fail then this condition will run after that this condition Builder okay so we have made a uh the mistake that we do not put there else actually so we correct it now let's run this yeah we got the correct answer okay for two case cases let's submit the answer yeah now we found the characters okay so thank you | Find Positive Integer Solution for a Given Equation | reported-posts-ii | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y) < f(x + 1, y)`
* `f(x, y) < f(x, y + 1)`
The function interface is defined like this:
interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
We will judge your solution as follows:
* The judge has a list of `9` hidden implementations of `CustomFunction`, along with a way to generate an **answer key** of all valid pairs for a specific `z`.
* The judge will receive two inputs: a `function_id` (to determine which implementation to test your code with), and the target `z`.
* The judge will call your `findSolution` and compare your results with the **answer key**.
* If your results match the **answer key**, your solution will be `Accepted`.
**Example 1:**
**Input:** function\_id = 1, z = 5
**Output:** \[\[1,4\],\[2,3\],\[3,2\],\[4,1\]\]
**Explanation:** The hidden formula for function\_id = 1 is f(x, y) = x + y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
**Example 2:**
**Input:** function\_id = 2, z = 5
**Output:** \[\[1,5\],\[5,1\]\]
**Explanation:** The hidden formula for function\_id = 2 is f(x, y) = x \* y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=5 -> f(1, 5) = 1 \* 5 = 5.
x=5, y=1 -> f(5, 1) = 5 \* 1 = 5.
**Constraints:**
* `1 <= function_id <= 9`
* `1 <= z <= 100`
* It is guaranteed that the solutions of `f(x, y) == z` will be in the range `1 <= x, y <= 1000`.
* It is also guaranteed that `f(x, y)` will fit in 32 bit signed integer if `1 <= x, y <= 1000`. | null | Database | Medium | null |
387 | Jhaal 500 Hi I love you doing well 100 grams people are going to start Elbow master sheet is ok and for this I will make a dedicated play list separately ok so this is a very good thing man this is a great practice algorithms and for interview purpose so Ashram, let's see how much we can solve and how much consistency we can maintain and today we raise the first question, okay like I told you that it is very important to learn the festival, so the first topic is the festival's apk file. If you have read this then refer this video otherwise there is also a video of that driver of this serial, you can do it on that page so we will see the first question of first unit character industry re 100 dec o my straight and this is my question of first unit character. Industrial: First of all, the unit character. Industrial: First of all, the unit character. Industrial: First of all, the last video I made was above on time and I had said that time is a very important topic for the purpose of interview, what kind of concept is there on time that when you don't understand anything then come and there is no money in debate. It is applied on everything, it is applied on every question, but the maturity of the questions which is inside the online assessment, which is inside the test, it is solved by SMS, okay so it is a very important data structure at the time. So the key stores our data for the pressure key and this is what we need to know. Okay, so first of all, reading the question, first unique character in the spring gives a spring is finder for not repeating character and returned and foreign delegates did not have any effect. Exist Today - Well, do Exist Today - Well, do Exist Today - Well, do n't put the question first, okay, first of all, understand what the question is by asking only then you will be able to make optimum use of your resources, its ok, otherwise I will give you 500-600 its ok, otherwise I will give you 500-600 its ok, otherwise I will give you 500-600 questions by mixing Saasu questions and that later. Will also fall short, okay Urine Asparagus, you have given me some system, I know the list is okay, I know this is the system, I know, you have given me this trick and my spin is the list and okay, now I have a healthy non repeating character in it, okay. So before that, I will hit Inducts, take 0123 and it is 536, you approach every question in the same way, whatever index you have given to this Tinder stuffing, accept it from your side, then you try something further, Phone Finder. For it's not repeating tractor and first not repeating character see that is repeated aapke not repeated most of which is repeating N T V F ok std od but in this the first character which is not repeating what is l and elected s The President, what will be my return on dowry? It is 208 and if I do not get such an contact then what will I return - then what will I return - then what will I return - One is ok now like see she is my friend this also now in this repeat and more repeat And if it is, I am not able to find any character which is not repeating, then what will I return - I will make 110, ok what will I return - I will make 110, ok what will I return - I will make 110, ok fine, then we will see, how could we approve this question? First of all, I am the first one here. So what will I say, I told you, I will make Christmas first of all. Okay, first of all, I will make one. There is time, then smell that loan, Ponting Chest and I will do it. Agri Care Correspondent has come once. Okay, how many times have I come? Three. Okay, keep me in the team, how many times has he come, once has come, how many times has he come, once has he come, okay, so there is something of mine in it. Now it will be done, I don't know how to subscribe to it, I had asked three questions in the last video, with great love for the prohibition, go and understand it, okay, so this is a, this is my last message, okay, this is my his weapon, what is NDTV COD, we are one If I want to point the first unit character in it, then how will I point the end in the first unit character? Which contact of mine is the President? Zero Intex Service Center, so it is okay, so what will go in my answer, it will come in my answer, it is okay in my answer. Zero will come, okay, A will come in my answer. Okay, so let's try to court him. First of all, what has happened? It happened on time, okay, alert map in unwanted, okay is aroma int okay, take care of me. Myint MP is ok, I have made it, now what will I do after that for ITI course 208 Lenin I Plus Ameer has entertained you, what is my and when is that, what is the size of my spring, the size of is ok and now I am using my skin. I will update on this and get its mapping shown. Plus of MP offices. What have I done here? No, but I have created it in debate. Okay, here I have created a smell. Okay, what should I do now? What should I do now? I have had enough of that. Which of my inductions means look, rather support cricket, that point, the first thing which is unique is the loan repeating, that is this, so what return will we get for it, will we get the induction done, then again I will hydrate on my skin. And ID is equal to zero on the first day, plus, now what will I put this condition inside it, if whatever is mine inside my map, okay, whatever is my character inside yours, its frequency is one, okay, that is what it means. Just look at MP on Facebook, what is there in MP, this is the complete map of MP, what is the help on SFI 100, MP of a lamp of calculus, one and a half inches youth is fine, so if my first character is Apple, then what will I do, Reader. I will get him back, I will get his tax return done and if it doesn't happen for me, then even after doing all this, if nothing happens for me, then I will get him returned - Okay, I hope I will get him returned - Okay, I hope I will get him returned - Okay, I hope you have understood, okay now you are SFI. Instead of 1ST year, there would be ad, so you can use that also, it is not used, this is the only way for us, okay, so let's rank this post and tell us whether it happens while watching the digit chapter or not, and Mike. Udan also submitted, so okay, first of all, what did I do, I made it in my hair, okay, I made it in gas, and then I checked every character, the first event was held on S0, is God in like and comment? What is my size, is it ok MS Word, what is my lion's zero, is it less than my side, how much is the size, calculate here, how much is the size, but the kid is 34567, now the scalp hangs to the manager or again to the poison, how much will be the science, there will be one office. Lead so 8 Mera Shahjahan This zero is my work with add here Now this is what is the zero of mine Okay is such a zero What is my Enter MP4 is full One is mine Yes is a Mere ko first time which was MP of hair I have got the strength that now I have found the first character, what is its frequency, which is not a repeating character, it is ok and who is that one, then what will I return, I will return pal1 and if my Despite doing so much, I am not getting the answer, so what will I return - I will return one what will I return - I will return one what will I return - I will return one and if we look at its time complexity, then its time complexity is stupid, then it is okay, it is stupid, and space complexity. Got soaked in this lead of speech complexity, why did it become a stupid man? Vikash Bihar is using this map to get that power data and process it, so come home, the question is page, thank you. | 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 |
145 | hey guys welcome back to the Advent and this is Nixon today we are going to solve a new problem from lead code it is the 145th problem binary tree post order traversal given the root of a binary tree return its post order traversal of its notes value let me explain this problem guys and before solving this problem we just need to know about what is binary tree and what are all the components available on binary tree and what are the traversal methods available on binary tree if you don't about binary tree data structure please go through some videos about binary tree data structures and then come to solve this problem guys now let us get into the problem initially we will be given a root of a binary tree and what we have to do is we just need to Traverse that complete binary tree using post order traversal methods what is a post order traversal postorder traversal is a traversal methods of binary tree and what is the concept used in post order traversal is nothing but it start it traversing from the left value and then it go to the right value moves through the right value and then at last it comes to the root of the binary tree this is the concept first initially it will be go to the I mean initially it will go to the left of the binary tree and then it go through the right of the binary tree and then it end up with the root value root of the binary tree this is the concept this is the traversal method uh followed on post order traversal method now what I'm going to do is I'm just going to create a universal list and then what I'm going to do is I'm just I just solve this problem using a recursive option so I'm creating a I'm just going to create a new uh recursive function and then I'm just going to Traverse this complete binary tree from the left side and then I'll go through the right side and I'll be end up with the root node this is the concept I'm going to follow now let us solve this problem guys now as I told I'm creating a universal list here yeah now I'm just going to create a recursive function start yeah and then I'm going to check whether the root equal to null or not it's going to return here then what I'm going to do is post order first I'll Traverse the left right side of the binary tree and then just going to Trav the right side of the minary tree and then I am adding the value on the root value adding the root value here what I'm going to do is I'm just call the recursive function here and then I'm going to return the list yeah yes got guys yeah guys anded successful thanks for watching please do subscribe to the Advent and if you had any suggestions please don't hesitate to comment us guys thank you guys bye-bye | Binary Tree Postorder Traversal | binary-tree-postorder-traversal | Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[3,2,1\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of the nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively? | null | Stack,Tree,Depth-First Search,Binary Tree | Easy | 94,776 |
876 | Hello everyone welcome, my channel of D link list is easy level question is ok 76 ok so let's see it is quite popular in my respect company is ok Amazon Microsoft Flipkart Johan me peacock is ok and many more we have not mentioned all of them for you to see So you go to my GitHub wrap, I have mentioned it in the description also. Okay, so let's see the question. It is a very simple question, you must have been given a link list, right? You have to return the middle load. Which is the middle note? Here it is five and it is of OD size. If we take main and size then its middle is two. And if we have to return the second one in size then the second one will become three in this. The middle is fine for us, like we take main, if six notes are 1234 56, then the middle two will go in this, otherwise we have to send it to the other one, okay, we take main, there are punches, one, two, three, four punches, so the medal in this is simple, okay? Let's see how we can solve this. Okay, so see, the first approach is that this will come in your man, and there is a very simple approach too that we take your man, we have given a linked list, one is three four, then it is the best. First of all, what to do is iterate or track it and find out the size. Okay, what will be the size? Keep a counter so that as soon as I come to the second one, I will stop the counter and return it. Okay, so one thing is simple. The process is done, but in this you are paying attention, you are highlighting it twice, on your link list, you list your links and find out what will be the medal element. Okay, so see friend, in the question, I told you the method one in which we What do we do, a slope pointer does that and a fast pointer does that, okay, this is called hair and break toise approach, also called linked list, okay, how can we make it, see, you already knew that slow fast pointer. How to move the slope pointer used to move one step and the fast pointer used to move one step right so slow is here fast is also here right so slow when If you move one point or one step then slow will come here but fast one will move two steps or fast will come here ok sorry fast has come here so now we have come here and fast will do two main It will come here and then here, neither is the slow one here, nor is the fast one here, so after this we cannot move forward because there is nothing else before fast. Okay, so the note on which we are stuck is the note. My sorry, let's see whether it is reducing here or not, okay, our slow was here, fast was here, slow came here, fast came here, we have to face two faces, fast has come out of here, look, we are here. We have stopped and this is also our answer, okay, so there will be a very simple code like this, what will happen is that slow mine will start from the head, okay how long will we run, as long as it is fast, okay, then what will we do, we will increase the slope once. Fast is equal to you fast is next to next and what is the guarantee that it will not break this code will not break because look we have checked that fast should not be next to ok if we go out then we will return slow simple returns slow thinks it Isn't it a very simple question? Okay, but it is popular and you need more of this technique. This is a slower fast technique. It doesn't take up much space, so let's code it. Okay, so the question is simple. It's the same. Linked list is given, you have to find the middle, okay, the solution comes directly, I don't think it will take more time, it is quite simple, what I said was that I will create a slope pointer which will point to the head and a fast point is created which is Will point to fast, okay then what did I say that till the time fast is not equal you have to become one, the one who is slow takes one step and the one who is fast takes two steps, fast is next to next and so on. I told you that we don't have a fast connection, that's why we are using the next infrastructure, right, and in the end, what do we have to do, nothing else, just return it to slow will be automatically pointing to me, so it's okay. Let's run and see the example test cases. You should pass. Submit it and see. Great C have passed. All details video. Thank you. | Middle of the Linked List | hand-of-straights | Given the `head` of a singly linked list, return _the middle node of the linked list_.
If there are two middle nodes, return **the second middle** node.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[3,4,5\]
**Explanation:** The middle node of the list is node 3.
**Example 2:**
**Input:** head = \[1,2,3,4,5,6\]
**Output:** \[4,5,6\]
**Explanation:** Since the list has two middle nodes with values 3 and 4, we return the second one.
**Constraints:**
* The number of nodes in the list is in the range `[1, 100]`.
* `1 <= Node.val <= 100` | null | Array,Hash Table,Greedy,Sorting | Medium | null |
347 | hi hello so today we'll talk about top key frequent element so given an integer ray nums an integer k we have to return k most frequent elements and the answer could be in any order so let's understand with an example so if we have in this example we have three one is repeated three times two repeated two time and three once and they're asking that find tell us two most frequent element we can see one repeated tries two twice and three one so these are the two most frequent elements so we will return the answer one and two let's better understand all right so in this question we have to tell k most frequent elements now what we already know so what is noun to us what we know already we know that there when we have some collection and from that collection kate element is expected so we can go with top k element coding pattern now in this question they have some collection and they were expecting k most frequent elements so we can go with top k element coding pattern let's see how we can go how we can implement that take some example let's suppose this is four two and three four is repeated three time two repeated two time and three is only repeated once so we can see this is three to one and most frequent and like answer should be four and two answer two and four is also correct because order is not expected we already know that for solving top k element what are the steps the first we already talked about that we have to decide min or maxi in second we will consider what are the bases like what are the grounds on which something is considered most frequent or largest or smallest or something third that we have to iterate on it is some iteration so the this is the whole block diagram for top key element if you look here so they're providing us these number of elements and they were asking that which are most k most frequent element you have to pretend to answer this now if we make a map let's suppose we can say 4 is repeated 3 time 2 is repeated 2 time and 3 is repeated 1 time so this is we can see that this is a number and that is its count right and if we can make some like oh the first thing we will decide that either we have to use min heap or maxip so k most frequent element we will use some min here but so the first thing is clear now the second what are the bases what like we how we will order that mean heat or maxi so they're asking k most frequent so that should be the ground for ordering so order by the count we will order by account and that is their expected result so answer by this so that is the answer what they are expecting and we will order by overheat using this count so we will order by count and answer would be expected in this so what we can do we can make some map a map of num and count so let's suppose like we can use tuple but for the sake of simplicity we can see that we can say we can make a class which has now and it has account and we will make a map that map will keep class sorry uh that it will be num count so that map will keep num count and that will be the basis so we will order by this and the third we will iterate as we were doing before now let's see how we can code this question all right so we already know we are going to solve this question using top k element coding pattern and we know the template how we have to use it so first step we will decide either we have to use min heap or maxi in the second phase we will uh we will fill our heap feel heap and keep k element and third we would return required answer now to follow the same step first we will talk about either we have to use a min heap or maxip they're expecting k most frequent element so we will use min heat its ordering is dependent on what we already talked about that its ordering could be abandoned on the count of numbers so we can make a class let's suppose case class num count and the first element would be none and second element would be count so we will make a priori queue of num count and it will be min heaps of ordering by count so we order by account the main heap and now we talk about that we need something that some mapping that says uh that this character has this frequency this character had this integer has this frequency so we will prepare that map we say map that would be nums dot group by identity uh in scala so what is this identity means it's a like a morphism you can say x arrow like arrow goes from x to x again so that is its identity so it means 2 is 2 3 is 3 so they are that is their identity so scala in from that array group them by the identity and then we say map values by size whatever the group size you have we will make the value so actually this will create a map that would let's suppose in our case we have an example of one two and three and that would make our map like this where one says i have count of three two says i have count two and three says my count is on now once that map is ready we will keep on going with the second step we will say map dot for each we will iterate on it and we will say because when we i trade we get num it is a key value we say num and it's count that's a key and that's value so we were saying num and count and here we will say min heap dot and q and we will make our non count class i can save even in tuple but for the sake of readability i'm just using num count so i can say num and count now in the next step we will check if min heap dot size is greater than k if the size increase from the required size of k we will decay and finally we have to return the answer i already told you about uh first thing that like we already talked about that we have to order by the count but we have to return the answer so to currently in the mean heap we have num count so we need num not the count so we will say min e dot map the values with num and make it an array i think i also forgot to ins import because import scala dot collection not mutable now if i run the code that's it thanks | Top K Frequent Elements | top-k-frequent-elements | Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\], k = 2
**Output:** \[1,2\]
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `k` is in the range `[1, the number of unique elements in the array]`.
* It is **guaranteed** that the answer is **unique**.
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size. | null | Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect | Medium | 192,215,451,659,692,1014,1919 |
297 | Hello friends uh welcome to my channel let's have a look at problem 297. she realized and the serialized binary tree this problem or this video is a follow-up for problem follow-up for problem follow-up for problem 652 so here we practice both serialization and this serialization so in between we are going to use recursion here for Simplicity or neatness so this problem asks us to do serialization or deserialization of banner tree so here are two examples for example this example one so it can this is a tree structure and example two is an edge case which corresponds to a null tree the constraints for this problem are the following first the number of nodes in the tree is in the range given by the closed interval 0 to 10 to the power 4 and the node value is in between negative one thousand and positive 1000 so with that said let's look at the code so here we are given a class called codex so this class uh the problem asks us to fill up two methods one is serialized and the other is the reverse the D serialized so here unlike problem 652 we need to also take this serialization into consideration when we do serialization so this actually is slightly more demanding comparing with problem 652 so here first we are going to do serial addition with the help of traversal so here we can use depth first search as in problem 652. so for the first method we're going to do the similar thing as in problem 652. um first I'm going to initialize a result variable which is an empty list so we are going to write a DFS function or a worker to modify this one and then later we do string John on this results list to get the representation of the whole tree so with that overall structure done now let's first look at the hyper function so here I'm going to use the fs again so which accepts in three node that is root and an argument name and then first if not root in other words so we are meeting a mouse so in this case so we can pinch the result with some special string let's say now or none so let's use a comma so this comma is used to distinguish digits so you notice that soon so here let's return if this is the case so otherwise so we're going to um first add this string representation of the node value to the result so this is string let's add root value and then let's also add a comma here so to distinguish digits and then we do the that first search in the left subtree and the restore tree recursively so let's call this function DFS root left and DFS root right so this way after we finish this recursion we're going to get a result a list which can be regarded as a representation but in a list format so then we just need to do string drawing method so as we have already initialized the results variable so we don't need to do here now we just call this function right DFS root so after that so actually we can return the full screen so we are going using string join method so here the separator is um empty string or empty scene so here we get the results so this is what we return so actually here we can add something we can print out the result or this jaunt uh string so this is the serialization so with this theorization method we can write a deserialization function let's do this here um so here we are going to first Define a hyper function which is going to do the split and do building the to build the tree so here and then we are going to call this function and then we are going to finally return this result so first I'm going to define a hyper function so this is the Builder right so first let's undo this one if on Q naught so is um so here Q you can see you can think of Q at the list here before the joining right so if Q naught is um as now so then we are going to do pop left and then we are going to return so the reason here we use this now because lastly place the data into this kind of format where the separator for this split will be the comma right so we just have not with no comma so this is the one step otherwise the first one Q naught will be a number so corresponding to a number let's see um what we are going to do is um we're going to write the root will be our tree node so the value will be pop left so this one or you can regard it as a string so it should be um still okay and then um what we are going to do next is to call this helper function recursively if actually following the here similar way so L will be um helper 2. so because of here we are using pop actually the stage of the um the skill changed right yes hyper q and then we're going to set the root of left to be left and root right to be red and then we are going to return the tree so this is the hyper function so which accepts a list of strings so with this function ready so now what we are going to do first we get to the list right so we are going to let's write it like this so list so we're going to get split so here as we used a comma as separator so here in the separate Direction comma again and then we're going to in order to use pop left or pop right or pop from the right so let's first make build collections on Deck so we can make a deck out of this list and then we're going to make out of similarly we can print the um the queue and then what we are going to do is to return to help her oh Q so this is the ROV of doing the um doing the D serialization so let's first do a check it passes one example now let's look at the generic case it passes all the general cases so here advancing I guess at Melody interesting is that we can change this one to be inch so if we like Let's test again yeah so it also passes so because here we are actually use some tab conversion like here string so here we can reach inch so meanwhile so we can do the print so here you will see the serialization and deserialization procedure more clearly so let's see this is the tree corresponding to this here one two three four five so we're going to get something like this so this is the list before John so if we join we are going to have a string long string like this and then when we input this string format of this list into the destroyalization function or method so after we do this step we do a split so we're going to get something like this right so here if we do not put integer here the value will be in a string format but um in a proper sense maybe it's better to change it to be um integer but you know it's not a big problem here because this um is not very strong in tab so with that stage I guess that's about it for this specific problem so here the thing is that so when we do a serialization we need to keep in mind so this sterilization so because this serialization method depends on how we do serialization so here in both the two methods so we used um recursion so this actually um is very neat or in some sense we actually do some chatting maybe it's through which actually hits some details but if you prefer I'll encourage you to write um the two method in um in the iterative format so for this one it's not hard at all so similarly with some effort writing a recursive format for this one is not easy if we are very familiar with when retreat traversals so with that said I guess that's about it for this specific problem in this video thank you | Serialize and Deserialize Binary Tree | serialize-and-deserialize-binary-tree | Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
**Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
**Example 1:**
**Input:** root = \[1,2,3,null,null,4,5\]
**Output:** \[1,2,3,null,null,4,5\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-1000 <= Node.val <= 1000` | null | String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree | Hard | 271,449,652,765 |
414 | hey everyone welcome back and today we'll be doing another lead code four one four third maximum number and easy one given an integer array numbers return the district maximum number in this array if the third maximum does not exist return the maximum number so in this case you can see here like three to one the third maximum is one and in this case where there is no third element you can just return the maximum so there are many methods to do this but what we'll be doing is just making a set then making that set into a list and then sorting that list and after that we will see if it's its length is less than two three yes if the if less length is less than or equal to two uh then what we'll be doing is just returning the last index otherwise values at la da at the last index otherwise it will be returning in any case if it is larger than three or equal to the third last index so that's it so we will be making a num list and then setting the nums so we can get rid of the duplicates so then after we are done with this we can just sort ok we will sort so if length of nums is less than or equal to 2 we can just return the last nums index value otherwise we can just return nums at the very last so that's it this should work and that's it you | Third Maximum Number | third-maximum-number | Given an integer array `nums`, return _the **third distinct maximum** number in this array. If the third maximum does not exist, return the **maximum** number_.
**Example 1:**
**Input:** nums = \[3,2,1\]
**Output:** 1
**Explanation:**
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.
**Example 2:**
**Input:** nums = \[1,2\]
**Output:** 2
**Explanation:**
The first distinct maximum is 2.
The second distinct maximum is 1.
The third distinct maximum does not exist, so the maximum (2) is returned instead.
**Example 3:**
**Input:** nums = \[2,2,3,1\]
**Output:** 1
**Explanation:**
The first distinct maximum is 3.
The second distinct maximum is 2 (both 2's are counted together since they have the same value).
The third distinct maximum is 1.
**Constraints:**
* `1 <= nums.length <= 104`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Can you find an `O(n)` solution? | null | Array,Sorting | Easy | 215 |
76 | so question 76 of leake code minimum window substring so given two strings s and t of lengths m and n respectively return the minimum window substring of s such that every character in t including duplicates is included in the window if there is no such substring return the empty string so the test cases will be generated such that the answer is unique a substring is a contiguous sequence of characters within the string so in the first example we have adobe code bank and t is equal to abc so we need to find the shortest substring with an s that contains all the values of t so in this there are multiple substrings but the shortest one is bank which is found at the end here containing one b one a and one c and that is the output that we need to give in the second example we have a as the output because t contains only one a the string itself only contains one a so that meets the requirement so it meets all of the values that are in t within the string of s and finally in example three we have an answer of an empty string and the reason for that is t length is greater than the length of s so we will never find two instances of a within a string that only contains one a so could you find an algorithm that runs in om plus n time so let's discuss a potential solution with that time complexity so this is a pretty difficult question and there's so much to take into consideration here and especially with the fact that we've got a hit om plus n time complexity so with this time complexity we can have a trade-off so we can increase our space trade-off so we can increase our space trade-off so we can increase our space complexity in order to hit this time complexity and one great way of utilizing more space to improve time complexity is by using something like a map data structure when comparing two values so we're going to have a frequency map that is going to store all the values of t and the amount of their occurrence so we're going to have a which is pointing to one b which also has one and c is also going to be equal to one right and the great thing about frequency maps or map data structures is they have constant lookup we can say that this map is the m within this time complexity and this n we can actually update that to be s and that's going to be this string right here that we're going to loop through and because we're only allowed to loop for it once a great technique that we can use is the two pointer technique where we have a left and right pointer that way rather than traversing the string multiple times and increasing the time complexity to something quadratic we can keep it linear and compare values together so how this solution is going to work we're going to loop through this string we're going to check at each point whether the value that we're on is within the frequency map if it is we're going to decrement the value associated with that letter and once the frequency map is all equal to zero we then know we have found a substring within the string of s so we can update our minimum window substring so before we do that we need a couple more variables to take into consideration so we need a count which is going to be equal to the size of this frequency map which is three and we also need to declare our minimum window which is going to be set initially as an empty string and the great thing about setting it as an empty string is it takes care of that case where we do not find a substring within the string s because we're going to be returning this so we will return an empty string so let's give this solution a run free at our right pointer we have the letter a is a within the frequency map yes it is so what do we decrement a to zero now once a or any of these values point to zero we can decrement the count because we have found all occurrences of that letter within the substring that we're looking for so we found all the currencies of a so we can decrement the count we only need to find two more letters b and c in order to find a potential solution now we can increment the right pointer so right pointer moves to d is not in the set we move over to o was not in the set we move to b is within the set so we decrement b goes to zero so we found the required amount of b within our string so we can decrement count now so count goes to one and we can increment the right pointer so we go to e is not within the map so we can move along we go over to c is within the map so we decrement c and now c is equal to zero so we decrement the count and we move the right pointer along one more now here is where we have to add additional logic because count is equal to zero we have found all the currencies of a b and c so we have found one a one b and one c those are the requirements that are needed for t within this substring so we have a b and c so we have this as a substring and i say it's adobe c rather than adobe c o because we are going to slice from the left pointer to the right pointer so s dot slice left right is going to give us adobe c because the right value here within slice is non-inclusive okay great so we have non-inclusive okay great so we have non-inclusive okay great so we have found a substring a potential solution so we need to update the minimum window to that solution but we have another issue here we have an empty string here and usually what we do in a case like this is we compare the minimum length of the minimum window with the length of this substring we have but we can't do that here because the minimum window is much shorter than the substring and it will always be the result so we need to create another variable so we have a len variable and this is going to be set initially to infinity so whatever length substring we have as our initial substring it will always be less than that so minimum window will always update to the first substring we find so we can do that now we can update our substring to equal adobe c and now we have to carry out a slide-in window technique in order to slide-in window technique in order to slide-in window technique in order to increment the left pointer to find all possible substrings within this string so while count is equal to zero we check the map if the map has the value at the left pointer so it has a so we increment a to one and if this value increases or if any of these values increase above zero we can increment the count basically saying that we need to find one occurrence of a to find another substring now and we can increment the left pointer so once we have done that we can repeat the process with the right pointer so we can check if o is within the frequency map it's not so we can move that along d is not within the frequency map so we get to b is within the frequency map and what do we do when we find a value within the frequency map we decrement it so b moves to minus one now usually we decrement count but b is not equal to zero b is equal to minus one so we have two occurrences of b within the substring so we do not decrement count because the only value we're currently looking for is a we want to decrement this to zero so we can just carry on we can move the right pointer to a we have finally found a we can decrement that to zero and now we can decrement count to zero we can increment the right pointer and now that count is equal to zero we have found another substring so d all the way through to a here so we have a we have b and we have c we can check if this is less than the minimum window it's not so we'd carry out the slide in window technique we checked to see if this point here is within the frequency map it's not we move it along o is not within the frequency map b is within the frequency map so we increment b so this goes to zero however b is not greater than zero so we do not increment count because remember we still have an instance of b over here so we move the left pointer along to e that is not within the frequency map we move it along to c that is within the frequency map so we update c to one and now c is greater than zero we can increment count then we can increment the left pointer and now we can repeat the process on the right side so is n within the frequency map no it's not so we move the right pointer along right is at c is within the frequency map so we decrement c great that's now equal to zero we decrement count now count is equal to zero so we have a current minimum window substring which is equal to this string right here is this less than adobe c no it's not so we check the left pointer we see if that's within the frequency map no it's not we move along we now have a new substring which is equal to this substring is that less than the minimum window no it's not so we increment the left pointer and we check if the left pointer is within the frequency map no it's not but at this point we have a new window substring ebank is that less than minimum window yes it is so we can update that to be equal to ebank now we check to see whether e is within the frequency map it's not so we move the left pointer along we now have a new substring which is equal to bank and that is less than e bank so we can update that and we check to see whether b is within the frequency map it is so we update b to one b is now greater than zero so we update count to one and then we increment the right pointer and then that is out of bounds so we exit this loop and we return bank so time complexity for this algorithm is as stated in the question o t plus s where t is all the values within t string because we need to create this frequency map and s is all the letters within the s string okay so let's start writing this out so let's initialize the map data structure so map is equal to new map let's loop through the values of t and create that frequency map so that letter t so if the map doesn't have letter then we can initialize it with one so map.set so map.set so map.set letter one else we just need to add to the current value within the map so map dot set letter map.get letter map.get letter map.get letter plus one so that'll populate the frequency map then we need to initialize all the variables so the left and right pointer then which is going to be equal to infinity count which is going to be equal to map.size so map.size so map.size so the map has and the count which is going to equal to map.size map.size map.size so map has a size property which will be equal to free within the first example and then we also need min window to initialize as an empty string and then we can start the loop so while right is less than s dot length we can extract the letter at the right pointer so our letter is equal to s dot right make it a bit easier to read if map has our letter so if the frequency map has the letter at the right pointer we can decrement the value of that letter within the frequency map and then we can do an additional check to see whether that value is now equal to zero we can decrement count if it is and then we just need to increment the right pointer there so while the count is equal to zero so we have found a substring if right minus left is less than len which we will be updating so the first time we check right minus left it'll be checking against infinity so it will have to be updated we'll update the length two equal right minus left so this is the current length of the substring and then we need to update minimum window variable two equal s dot slice and slice from left up to but not including the right pointer because remember we incremented right on line 32 then we can use the slide in window technique and increment the left pointer here so let's extract the left pointer to make it easier to read and let's check to see whether the map has the value at the left pointer if it does we can increment the value within the frequency map by one and then we can do an additional check to see whether the value at the letter is greater than zero and if it is we can increment count then we just need to increment the left pointer and finally we can return min window let's give this a run okay let's submit it and they have it | Minimum Window Substring | minimum-window-substring | Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`.
The testcases will be generated such that the answer is **unique**.
**Example 1:**
**Input:** s = "ADOBECODEBANC ", t = "ABC "
**Output:** "BANC "
**Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t.
**Example 2:**
**Input:** s = "a ", t = "a "
**Output:** "a "
**Explanation:** The entire string s is the minimum window.
**Example 3:**
**Input:** s = "a ", t = "aa "
**Output:** " "
**Explanation:** Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
**Constraints:**
* `m == s.length`
* `n == t.length`
* `1 <= m, n <= 105`
* `s` and `t` consist of uppercase and lowercase English letters.
**Follow up:** Could you find an algorithm that runs in `O(m + n)` time? | Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach.
L ------------------------ R , Suppose this is the window that contains all characters of T
L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T
When the window is no longer valid, start expanding again using the right pointer. | Hash Table,String,Sliding Window | Hard | 30,209,239,567,632,727 |
968 | hello and welcome to this problem number 968 binary tree cameras so as you would have seen i have actually changed in the camera setup a bit instead of the left side my face you will see on the right side uh that's simply because i realized that the way lead code ide is set up a lot of the space is actually taken up by this entire thing and rather you know more focus should be on the coding window and less focus should be on the question wind because once you've read the question you don't need it as much so this is going to be the um set up here of course there is the run code and the submit code button which is hidden but i could just say it and you would know right so uh let's get started so this problem says that given a binary tree very important given a binary it's a binary tree we install cameras on the nodes of the tree right each camera at a node can monitor its parents itself and its immediate children so three things its parents itself and intermediate chip calculate the minimum number of cameras needed to monitor all the nodes of the tree right so you what you're supposed to do is you're supposed to put in cameras you could put cameras on any node and the cameras have this property that the camera can monitor the node which it's on it's like intermediate children like all the children and it's right this is what the camera can do and you want to find out the minimum number of cameras you need to put a given binary so that all the nodes are monitored right so uh actually a simple uh like actually relatively a simple question so uh really like it's basically not a very complicated question this is really a simple question but this function is it's actually gives you a detailed discussion of how you should think when you have problems like these with you know including the children of the node the parents or the nodes are all you know also involved so this is one category of problem i wanted to cover so let's look at this example quickly uh example one now here as you see that um this is the pine tree if you put camera here this camera would uh wait a minute this camera here would make sure that the it's apparent so this is under view this is also uh you know something which is covered so the camera covers this node itself the upper nodes the lower node and uh also so this entire tree is covered by just one camera right so you only need one camera for this tree in the second example you might actually need more than uh you know one camera so let's look at that case so in this tree you could have put camera anywhere here but look at this camera placement if you put a camera here what happens is that uh a camera placed here is covering this thing or this like it's immediately filed its parent camera port here covers its immediate panel and it also covers this now this is actually covered two times and we want to minimize such instances where it is covered two times but it so happens that in this configuration this is the best possible we can get you cannot do anything with one camera because if you put one camera even here these two nodes would be left from being covered right if you need at least two cameras uh you know but to do this so the answer to this is two right so this is actually a very you know it's if you know has you know you have to have two very important observations to handle this problem so this is the structure of the binary tree there is a left there is a right and there is a value you don't need to uh like let's not remove this because i mean it's not needed in some problems it's actually needed a lot but you just need to know left right and so on so like now see in this problem what we need to realize is that you a node can affect its children and its parents this is a very important statement in this problem a node can affect its children and its parents in a lot of the problems the node can only affected children and it is very easy because for it for the tree you know we have nodes which are pointing downwards like for every node we have a left node and a right node and so you could very easily access a left node and the right node you could do it very easily but if you want to let's say given a tree which has like those links how do you access a parent of a word so this actually makes the problem a little bit more challenging and these classes of problems which actually need to you know dealing with parents of the trees so uh there are many techniques of actually doing that you know actually storing keeping things in stacks and storing that but you know one good heuristic when you see such problems is to remember that the way you do it is the way you do whenever you have the you know you from the children you want to go to their parents the best way to do it is do it via efs a depth first search what does a dfs guarantee right so now what happens in a dfs what happens is you start with the root node you go to the most bottom part of it and then by recursively stack calling you come back right so dfs is intuitively one way in which you could go down the tree you could go down to the leaf nodes and from the lymph nodes you can come back right so basically if you don't want to use dfs you could use you could store the parents in some data structures and there are many fancy algorithms and fancy ways of doing it but i think the structure remains the same even if you use a data structure it's like dfs when you're doing dfs it actually uses recursion to come back and it you know back in the recursion actually uses stack right to uh handle this so it's like we need some sort of a storage to actually go you know go back you need some sort of a storage when we have children affecting their parents right in a binary right so uh this problem actually is a very straightforward problem because if you look at this problem what you need to do is you just need to uh go down the tray excuse me you just need to go down the tree and you just need to see okay there are two properties a node can like what are the two properties in organelles there are important don't mind the spelling it might be wrong i'm not an english nerd so the two properties the first property is that it has a camera right and the second property is that it is money third right so the first property implies the second one if the node itself has a camera then it's all it's one area and it's pointed by itself and the second thing is that if the uh you know if the node is monitored then what we get is that we don't need to put a camera there right so you could the combination if this is a all of these are like bulls right these are boots this is a boolean variable and this is a boolean variable whether a node has a camera or is its momentum so what we want to do is we want to make sure we want to place the cameras in such a way that the second variable is monitored is true for all the uh you know the entire tree right and what we do is we actually do a depth first search and when we do a depth first search we need to uh we actually for every node we have this property it has a camera and like it is monitored and what we do is if like so we have you're gone you're coming from bottom up so like yeah so the advantage of this is bottom up right you're filling the cameras bottom up and if you're coming from bottom up you realize that if you have a node for a node if it's if both of its children aren't monitored then that is the only way you can monitor those children is by putting a on that node on the node so we are on the node so the only way you could monitor if both of your children are not wanted then the only way you could put a camera is you know basically why um only way you can solve that is putting a camera and since it's a binary tree you cannot have like more than one parent and things like that this is just one parent the only way those two nodes are going to be wanted is by putting a camera on that node of the parent right the second characteristic is that let's say if um so the second characteristics is yes so if basically the as i was saying the second property is that if like if one of the child actually has a camera then you don't need to do anything you just need you know now that the node in question is monitored right so uh if one of the children have uh cameras then you're pretty sure that this node is moni turd and when you put a camera it directly implies that this node is what is node is morning third right yes um money turd right so see what did you do you if you are at a node and if both of the children are not monitored you have to compulsively put a camera there because there is no option for the kids to get pointed so but by doing that you make the node being monitored and you also put a camera on that node right and if one of the when you are coming to a tree and when you have one uh you know node which has two kids two children or one child and one of them has a you know camera if one of them is actually monitored then uh we what you do is you try to you put a camera there right because you don't need to put a camera there you just see that the node is monitored itself right because if uh like yeah if another children has what then you thought the notice might it's pretty straightforward right here so uh it's just uh you know going back again you're doing a dfs you're coming from bottom to up if you are at a particular node you need to do this for all the nodes so if you are a particular node if both of its children aren't monitored you need to put a camera there and that's how the node and the bit skates become monitored if one of the child has a camera then you just know that this node is monitored you don't need to do anything else right and then you do it recursively for all the node so either of the condition will be true so in both of the cases all the nodes will be monitored right and in this greedy fashion you will use the minimum number of cameras because you're going from bottom up if you're going from top up you need to you know check all the possibilities and things like that but if you're since you're going from bottom up it's automatically greedy it's automatically the fact that you're being optimal at putting cameras right so uh there are many ways of implementing this so let's um a decent way of implementing it would be to have a global variable uh let's say n yeah so uh in this you know scope you say first of all you begin with saying that this is zero the number of camera is zero and you somehow have a function okay this is a view one other consideration needs to be done what if what about the leaf nodes or what about the root node so uh i will actually come to that right so the number of cameras now i'll uh have a variable let's call it uh the uh you know answer variable or let's call this you know s a variable to make a temper variable so this m variable is auto temp uh it takes it gets in this function uh you know cnt cam cameras and this function takes in so it takes in this uh you know what it does it takes in this the this function and it does something let's you know basically talk about implementing this function and seeing what's the most efficient before so um okay so let's have so you know we need these two so we need it to return two variables uh so auto let's not have auto let's have a pair of uh bull rule right so you have this pair of bull attempt the first one says whether the bull leg pair dot first is like whether the camera it has camera and two is like whether it is movement or not right so this is basically the situation of the root node whether the root node is monitored or not so what this will do is it will actually do the dfs from the root there is this external variable called camera it will increase the number of camera like the n camera as and when it finds worth increasing and then finally it will tell us about the root note right now root node needs to be specially cared about because root node doesn't have a parent right if root node does not if basically if the root node is not being monitored by something this is below it the only possibility you have is to put a camera at the root right so this is just that special case of looking at the root node so if you see that if it's this thing this temp is like the condition of the root node is the second value of it so it's not monitored so if the temp dot second is false right so it's like it's not being ordered or the root is not being monitored the only option we have is that we uh you know put a camera on the root so we increase the number of camera we have to increase the number of cameras you put the camera on the road uh that's the only consideration you have and then you return the end camera variable uh it will be more much more clear when i actually write the uh the proper function to this right so uh let's uh do that as well so we have this uh we'll have some you know we'll have some space for some real estate okay yeah so we uh we're writing this function returns a pair of a volume pair of booleans uh what is this function the function is called a cnt camera right cnt camera it takes in a three node pointer to three node off root right it takes in this now uh when it does take this thing in this thing was not needed because yeah this is what can go down right so cnt camera all right so first now first of all you need to know what is with the root node so if the root like if the root node is null right as generally all three problems what if the root node is not if the root node is null first of all you don't have a tree so in the base case when the root node is null you actually handling it with the you just put a camera on that root node and then you're done so that is handled by this the only case when you need to take care of it when do not is equal to null is when you are actually at the leaf node and somebody's actually trying to check or you're in one of those nodes which don't exist if node doesn't exist then you just simply say that uh it's like you know you there is no camera there so there is no camera here and it's already monitored or you don't need to care about it so this is like is there the first thing is like the first value is these have a camera second is it monitored right the first bull is easier to have a camera and is it so you say the null value doesn't have a camera and true because uh it's actually we just say it's monitored because you don't care about what is happening to this so if the these the algorithm will totally ignore this if you are at the null position even at the leaf nodes or you are at the one of those side positions right so this is done now let's get into the more interesting cases you are returned uh since this is an explicit uh you know the function as like pair bull returning this will automatically be converted into a pair of boolean uh if you want to actually do it you could do explicit type conversion but it's not necessary because the return type of the function is paired okay so you have pair uh of left so this is nothing but when you are doing this for the left uh part of the road knot right you're doing this for the left part of the root node and similarly you will have just remember that the first value is i'll put it here as well so that it's clear for anybody that in this function the first thing the you know the function dot one like is it camera and the second thing is that is it monitored right so left and right so once you so this is actually doing the post on the traversal so when you're doing a dfs you could do it in three ways you could do with you know a pre-order you could do with you know a pre-order you could do with you know a pre-order in order or post order this is actually a post order traversal because uh you first need to look at what left and right are and you need to do it to the end of it and then based on the left and the right values you can make a choice whether you want to uh whether you want to put a camera or not right because you need the values for both whether there is a camera on the left and right to make a decision off about the root node so like about the with the node the parent node so this is actually a post order right so now you say that if we just handle this case that if both of the children aren't monitored you need to put the camera if one of the children has cameras not have camera one of the children has camera then the node is monitored so let's say let's check that so if one of the kid has cameras how do you see that so this is the left child so you just save left dot first so this has a camera or write dot first is true or both whatever both will actually not be true like an optimal setup but like if one of them is true you it might also be so if yeah if one of them is true what you do is you just say uh okay you will have to initialize these two bulls bool uh hash cam right which is false by default and uh bull money third is also false right so what you do is you just for like if this is true then you don't need to uh if this is true that you don't need to have a cam so this lets this name involves but you now know that this is actually being monitored right uh that's cool uh if uh there's this other case which in which like if l dot uh second so basically both of them are not there so if uh both of these children aren't monitored so if you want to see both the children are unmonitored so there where you have the second variable so like l dot second is false and a lot like r dot second so both of the uh variables are not pointed then you need to make sure that the hash cam becomes true so this node should have a camera number of camera is monitored also becomes true because this because it has a camera it automatically becomes monitored and the number of camera has to also and camera increase right so that's how why we have a global variable called that camera this has to increase uh this is all handled this is all the case that's pretty much it for the left for the right and so on and finally you will need to return the we just say we return uh hascam and monitored right so for whatever the case may be this uh whether this is true uh this will be returned hash cam monitor uh what of the values and if nothing is true then both of them will be false will never happen so let's pretty much submit this solution there is a silly mistake we'll debug it run this solution first okay so there is a silly mistake let's see what that silly mistake is so actually the silly mistake was uh rather obvious it's actually right here so i just like arrows being left so let's try to do this now let's try to run this now accepted let's try to submit it and accept it right it's better than 73 percent memory uses 56 percent so a decent simple uh solution to the question to this question uh which was just a brilliant operation for like a depth first search followed by like the post-order traversal for like the post-order traversal for like the post-order traversal for a greedy approach of assigning cameras so it's actually a straightforward question but just this intuition that when you need to have children's that can affect its parents you need death per search and the fact that you know you needed post order traversal was a little bit tricky but overall it's a simple question you could easily have solved this in let's say half an hour time right and this is a pretty optimal solution so it is interesting actually to see for cases in which you have an energy and you have like more nodes how do you how does this generalize because if you have an energy you still need this by these binary variables but you need to do this for uh like for all the nodes and all the trees so this question can be asked in many variants where you could have like more than one types of cameras each of them have different properties so then the binary one and zero like just being hanging a camera and having monitors is not enough you'll have to make sure that there can be more cameras and more monitoring so let's say we have to put two cameras so like there can be many variants to this problem but at the core the fundamentals of this problem is about you know post order traversal and this grady approach so hope uh you know i you know you enjoyed this video and i really want to say that if you're watching until this end please if you have any suggestions for the videos uh please you know i put them in the comment section that you know some new videos on this topic or these questions need to be made and i'd surely try my best to make them right thank you | Binary Tree Cameras | beautiful-array | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Explanation:** One camera is enough to monitor all nodes if placed as shown.
**Example 2:**
**Input:** root = \[0,0,null,0,null,0,null,null,0\]
**Output:** 2
**Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val == 0` | null | Array,Math,Divide and Conquer | Medium | null |
1,451 | hello yours welcome back to my channel I hope you are doing great if you haven't subscribed to my channel yet please go ahead and subscribe I have created bunch of playlists to cover various categories of the problem such as linking list trees graphs breadth-first search binary search breadth-first search binary search breadth-first search binary search depth-first search dynamic programming depth-first search dynamic programming depth-first search dynamic programming and so on please check them out I have uploaded the code for this particular problem to github you can get the link from description below this video let's jump into today's problem rearrange words in a sentence given a sentence text a sentences string of space separated words in the following format the first letter is uppercase each word in the text are separated by a single space so basically we are given with the sentence and the first character is an uppercase letter and all the words in the sentences sentence are separated by a single space your task is to rearrange the words in text such that all words are rearranged in increasing order of their lengths if two words have same length arrange them in their original order written the new text following the format shown above so once we rearrange we need to make the first letter uppercase and all the words in the text should be separated by single space again once we rearrange basically so what are the conditions for rearrange there are two conditions right so one is they should be the word should be increasing order of their lengths but if two words have same length write arrange them in the original order so whatever the original order in the sentence right we will be arranging in that original order so let's go ahead and understand this with an example right so leadcore is cool let's say that's the word right so lead code how many characters it is eight characters right and this one is two and this one is cool is four so now if we saw our thread it's art or it will be two four eight right that's what it is so the corresponding thing is cool Nico right ideally this is the one right he is cool it cool but we need to arrange the sentence in the format shown ago that's what it is ready to return the new text following the format shown above right so what is that first letter he is in the upper case so let's transform I to the upper case and each word is separated by a single space I think I already have single space across so this is our answer right so this is our answer so that's how we need to do right this is a simple case where we are arranging them in the increasing order of their lands right so that's the first condition right so we fortunately there are no words with same length right so let's see if there is a another thing with same lamprey so let's see this one right in this there are some words which are the same length right so which a keep is for calm is for and it's three core is for honest too so with that what we are going to do is two three four right so this is a pretty complicated situation right we have three words of the same length right so now let's try to fill up the first things right because there is no collision with that so on right and next thing is and all right now for which for ready to take is a question right since we have to keep the order right the original order it said right so arrange them in the original order so what is the original order Keep Calm code right so keep is coming first so keep calm is that come incident and code is coming and what we are going to do the first character we need to make as caplets so this is our answer on and keep calm core right that's what it is so whenever there is a collision between the length right so if there are more words two or more words have same length we have to arrange them in the original order of the sentence so it's like Keep Calm code Keep Calm curve there in that are right so this is the idea so we are given with the sentence and each word is separated by a single space right so now what we are going to do is since we have to play with words we need to convert that given sentence into words basically we split the sentence into words now right and we need to know two things right what is that the word position and the word length two things if we know two things then only we can arrange into another sentence basically a new sentence basically right so we need to know two pieces of information right so what is that the letter V word and also the position so what we are going to do here is if you have the word we can get the length of the word pretty easily so what we are going to have is a placeholder class which will keep track of the two pieces of information that we need what is that the length of the world and the position of the earth right but if you have the word itself right it's easy to have the position of the arm I mean Linda the world anyway right so what I'm going to have is a word and its position in the place for a class right so let me show you the place code attached first for a second right so this is a placeholder class which I am calling as node ignore the naming for a second so it will be public string s and public in position so string is a word here basically this is a word and the position is the position in which I'm position of the word in the sentence basically so if you go back red so position of keep is zero right and comm is one and it's two core is three on is like that so I will be keeping the position of those words right that's what it is so once I have that I will be generating a list of objects with word and position all right and I will sort based on the rules what are the rules first rule is increasing the order of flames and second role is if they have same length arranged in rows in order so with those two rules I will start it so once I sort them right so I will have basically in this format two three four right and they are in this format so once I have them in this particular object list right what I need to do is I need to extract the words from this list and put back at the sentence format right put back in the sentence format and make the first character as uppercase right make the first character as per this so that's what we are going to do so basically the steps are simple first you have to split the sentence into words and the second thing is prepare a list of objects such as you are keeping track of the word and its position so once we have list of objects you sort them that isn't step number three once you saw in the step number four you just join the words with space in between them that's what it is right that's what the second rule and what you're going to do is convert the first letter in that sentence to uppercase and reckon it that's it so we will do those four steps and come up with the final answer right so let's go ahead and look at the code for this particular idea so I already showed you the place order class which keeps that keeps track of the word and it's a position right so let's go ahead and look at one more time word and its position right and next so just for the sake of converting this first character in to lowercase right so I am taking this text tool over and splitting it by space I have all the words in the strings STRs right so I initialize the position to zero I am declaring a list of words this month this means list of objects basically so these are the list of objects where the type is node what is it nor exactly node will have the word and its position right so now I will go through each string in this STRs and try to add an object into the words so the object will have the string and its position right this position will be incremented for each string right so now I have a list of objects so these list of objects will be sorted I am using a custom sort okay I am calling it as new arrange comfort this is a customs art right we'll go and see what is the custom start doing so essentially the custom start has to do two things right and it has to follow two rules one rule is it should arrange in the increasing order of their lens second rule is the two words have same length the they should be arranging in the original order right original order of the positions of the words so that's what this arrange compare is going to do for us so I saw it using the custom compare so once I started the words are in this particular format two three four basically I am having the width the length but I assume that these are just the words right so I have the words so now I get the words start select w dot s so this is the lambda expression to get the words and join by what is that space right so that is what we need right they are separated by a single space so we are separating by single space now I have the final string and one more thing we need to do is convert the first letter to the uppercase so I get the first letter and then before returning I am converting that to uppercase right and returning their strength now go ahead and see what we are doing for the arrange compare custom sort so this one we are passing in node type right so node type will have two things what are those string and its position all right so now I will get the length of the string a from node a I will get the length of a second string in node B so if the lengths are same what I should do if the lengths are same you the words have same length arrange them in their original order that means whatever the position so I am comparing the positions and returning the position compression do they are not same then you compare the lengths and return so this is the custom sort that we are going to use as per other word dot sort right so that's what will be used to solve the words based on the length as well as the position right so now that we are able to solve this and return the final answer right let's go ahead and look at the time complexity and space complexity time space so we are given with the sentence right the texture is sentence not the word but we are playing with the words we don't know the number of words in the text for example I am assuming n is number of words right n is the number of words it's not I would like it's not text length right it's not text length unless the whole text is a single word okay if it is a single word then you don't need to do anything of this order it's just whatever it is right but I'm assuming n is the number of the words not the text length so normally in the string algorithms right you would take n as a text length but here it is the number of words so I am just assuming n is the number of words so if n is the number of words right I am going through the first time splitting and going through the number of right so this will be order of n time complexity right so now I'm sorting these n words right so any sorting algorithm that we take so told so far its order of n plus we are sorting I would say the sorting algorithm will be order n log n right so the total complexity is order of n log N and if you would like to add this one right adding or generating the final string this would also take plus order of n right order basically order of words right so that will be totally order of 2 n plus log n right so order of 2 M plus n log n right so normally n log n is greater than n right normally 8 log n is greater than and for a valid M for high number of n basically not for like 2 or 3 if n is equal to or 3 doesn't matter much but if it is if n is large maybe n is a million right so then 2 n is much less than n log n right for those cases we will remove 2 n from the Big O notation and we will say the total time complexity for this particular algorithm is order of n log n right so let's go ahead and look at the space complexity right so how much space we are essentially using right so there is a list of objects that we are generating right the words so each word will have the position and the word itself right so we don't know again the world length right to start with so again we will go with number of words right n number of words are there so we need n such spaces right I am assuming there will be one unit of space needed for word that one unit can be anything it could be 8 bytes or in what's what say all right I am just saying one unit of space I don't know what is that unit is so each word will have different lengths so that unit be different right so I cannot quantify saying okay each word will be taking the same number of units right that's why I'm just going with a uniform way I'm taking one unit of space for each word so I have n words right so n such objects are there in here so I would say order of M to start with plus and I have this space where I am splitting and storing it in here right that would also be order n plus we are making the final string right which will be another order and right so basically we are using order three and space right so since we are going to ignore the constants we will say the total time complexity of this algorithm is order of n so the space complexity is sorry not the despise time down to 58 space complexity is order of n and time bounce it is order n log and if you have any further questions please post them in the comment section below I have posted the code to the github repository you can find the link in the description below this video if you haven't subscribed to my channel yet please go ahead and subscribe and also share among your friends please click on the bill icon so that you will be notified about all my future videos thank you for watching I will be back with another problem very soon till then stay safe good bye | Rearrange Words in a Sentence | minimum-number-of-taps-to-open-to-water-a-garden | Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format:
* First letter is in upper case.
* Each word in `text` are separated by a single space.
Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.
Return the new text following the format shown above.
**Example 1:**
**Input:** text = "Leetcode is cool "
**Output:** "Is cool leetcode "
**Explanation:** There are 3 words, "Leetcode " of length 8, "is " of length 2 and "cool " of length 4.
Output is ordered by length and the new first word starts with capital letter.
**Example 2:**
**Input:** text = "Keep calm and code on "
**Output:** "On and keep calm code "
**Explanation:** Output is ordered as follows:
"On " 2 letters.
"and " 3 letters.
"keep " 4 letters in case of tie order by position in original text.
"calm " 4 letters.
"code " 4 letters.
**Example 3:**
**Input:** text = "To be or not to be "
**Output:** "To be or to be not "
**Constraints:**
* `text` begins with a capital letter and then contains lowercase letters and single space between words.
* `1 <= text.length <= 10^5` | Create intervals of the area covered by each tap, sort intervals by the left end. We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right. What if there is a gap between intervals that is not covered ? we should stop and return -1 as there is some interval that cannot be covered. | Array,Dynamic Programming,Greedy | Hard | null |
1,071 | hello everyone welcome to algo simplified let's solve today's lead code challenge that is greatest common divisor of strings in this problem we are given two strings and we have to find a string that is a largest string which can divide both the given strings which means on concatenation of the resultant string one or more number of times we can achieve both the strings that is string 1 and string 2. let's say we have a string s and we have a string T and for your better understanding let's take a s as a b and T as a b now if you just see let's say x is the resultant string which can divide both of them now there are certain things the what can be the size of X can be one okay one if like all the numbers are AAA and a then it can be one but what if there is a pattern so the maximum size of that pattern can be the gcd of both the numbers like gcd of size of s comma size of t dot length you know the gcd will be this only so gcd let's take gcd is G so it will be the maximum size can be G because let's say it's 4 and it's six then the gcd is two it can never be greater than 2. it's never possible let's say we take four but we cannot add 2 4 to make a six it will be eight so the gcd is two so the maximum size can only be two the minimum size can be any other number like which divides both of them but if a number divides now there is one more observation let's see if this x makes this D with like a number of times on concatenating X we it makes T and B number of times x it makes s now you would say that a number of time x b number of time x makes this s n t so since these two can be made from X let's say you take a b and one more a b so now you can see that let's consider this one and this one you will see okay this is of size 4 this is of size 8. so gcd is four so if this a b can be repeated twice it will make this thing then we will consider this a b as string s we will not consider this a b even this a b can also make this string on concatenation as well as this string on concatenation if a string of size smaller than a b can make this a b and also this a b then it's possible that a b on concatenation again if it's forming like this ABAB is forming this thing then we will take the largest one and the largest one will be the gcd one with the size of gcd so it's pretty simple that we will consider the size of gcd as the possible string either it will be of the size gcd or it will not be possible for us to make a string which can divide both of them now how we will be checking if we can divide it or not you know if it's the number is B and the number is a like a number of times we can't concatenate this and B number of times then if we concatenate s and t like if we just append t to s we will get S Plus T and we if we append s to T we will get t plus s that is S Plus t and t plus s you will get OK X is repeated B number of times x is repeated a number of times so here x will be repeated a plus b number of times and also here it will be repeated a plus b number of times so you can say that if these are equal this equality holds true it means both the strings are equal it means one has a number of times and the another one has B number of times and if we add them they will if they give the same result then it's possible for an X to exist and if it exists then it will be a gcd So based on this thing let's solve it let us code it up so let's take the gcd first and J equal to this is inbuilt C plus STL so string 1 dot size comma string two dot size we have taken the gcd now if S Plus t equal to t plus s then we will return str1 Dot substring from 0 to size G otherwise we will return empty string so this should be the solution for this problem oh actually I'll just took variables of my own that I explained during the ex explanation time yeah so it should run fine | 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 |
316 | Hello friends, welcome to your Day 46 of Lead Code Challenge, so let's go straight to the screen and start today's question. So here we are on our screen. Today's question number is 316 and question number. The name is Remove Duplicate Letter. Okay, this question is a very interesting question, meaning whatever you might be thinking, everything in it will be a little bit opposite. Okay, there are a lot of twists in the question and there is not one thing else in the question. That this question is exactly the same 1081, its link has also been put, see what the T code people have done now, the two questions are exactly the same, so you have to watch this video twice because the question is quite interesting and the meaning is a little difficult to understand. Meaning, if you are watching it for the first time, then you may find it a little difficult, okay, that's why you have to watch the video twice and you have to do the dry run two or more times, that's fine. So let me tell you first, then let's go straight to the question and understand the question. So here we have the question. Now see what we have to do. Basically what we have to do is we have to remove duplicate letters from here. What has to be removed is B C A B C. There is a string from which duplicate letters have to be removed but it is not only that given string remove duplicate letters so every letter appears once letters have to be removed. Duplicate letters and one only once you must make share. Your result is the smallest in rexo graphical order among the possible meaning that whatever results I will get from these, how many results will come, which one will be the smallest among them? First let's talk about what are our duplicate letters in this? One is B, we have duplicate C. These two are duplicates. Now look let's understand this. Late sir, if I have moved these B and C, then what will be the answer we have A B. C If I removed this one and this C, what would we have C A B If I removed both of these, if I removed this C and this B, what would we have B C And if There is one more possible in this, but if I remove this C and this P, then the answer I get will be B. So we will have these four results which are possible results. Out of these, the smallest one is Laxophile, isn't it? We have to return the smallest answer in lexophile. See how the smallest answer will be formed. So in increasing order, A B C is the smallest, why A is the smallest, after that B is smaller than that, after that C. Look, is there anyone like this here? No, B is before this, C is already, so the answer will be A B C. Okay, I hope you understood this part. Now what do we do to understand it a little better. Let's just take one more example. Let's take one more example. B.C.A.C.K. Bar. I took B.C.A. Now the B.C.A.C.K. Bar. I took B.C.A. Now the B.C.A.C.K. Bar. I took B.C.A. Now the first thing in this is what is duplicate? C and C. Okay, so now we have what result can be made? Its result is only two results. One can be formed, either remove this C or remove this C. The results will be B C and a B C B. These two results can be formed. Now, among these two, which is the least graphically smallest, the most is B. Look, B. Both have common A and C, it will be seen which is smaller, A is smaller, after that C is coming, so in this case, it is okay to return BC, so now how can we do this, for this, neither is the whole one. There is a story, there is nothing in this question, it is a story, we have to understand it from the story form and that means there are a lot of dryers in it, the code is also very good, it is a good level code, we will dry it a lot, only then we will understand it properly. So this is the type of question, I hope you have understood the question as to how to solve the question, what are we saying, is it okay to solve, the question is a little confusing as to how to maintain the graphical order is okay. So what can you do, if you do n't understand, then rewind a little once again, then come again and understand again. Okay, so let's go to the screen again and understand our story formation. First, what do I do? Let me see what example we have. For this example, let's understand that I copied this from Y to N, I put this in Y. Now let's see C and B A C B C N, I put this in Y. Now let's see C and B A C B. First, let me explain to you with just a story form. How should we do this question? Okay, after that we will talk about what things are needed. Now, while I am doing the question, you can ask what things we need. Then I will explain, but let us observe you together. I have to understand that I am doing everything from the story form, then look at what I need, first of all the character came to me C, then come C, we kept him, after that came B, now B said to C, are you mine? He said yes C is bigger than B so he asked can you come after me then C said yes I am coming later so I will come later you come first so I said Y but B Wrote it, after this came AA. A asked B, can you come later? B said yes, I am also coming later, so I will come later, you come first, A also came, after that came C, now C. D saw that brother A is younger than me and he is already lying, so why should I come directly, C can come after A, absolutely right fear came after him, D also thought that I can come directly after C, so C. Also directly after that came C. Now look C has already arrived so I do n't need to check C has already arrived so to me it means it already came in the right order so I don't need to check C. So I made C skip, okay now how will I skip this, I have to go back and see that thing, we will have to maintain it, after that came B. Now B said to D that you are bigger than me, you come to me, so can you? You will come later. D said, I would have come later but I was not coming later. So what did he say to B? After that C came again. What did C see that C had already come? So we should send C to C. It is not okay, so what is the answer to this? A CD B Okay, I will do this part again once so that you guys can understand it better. I will do it one more time so that you guys can understand it better. Okay, look, K came first, there was no one there, after that BB asked C, can you come later? C said, yes, I am coming later, so you come first because I was younger, so she said. You, I made it, after that, A came and said, can you come after me? Yes, B said, I am coming later, so I will come later. You come, A also came first. After that, C said, "My." If he is a younger person than M then I would have C said, "My." If he is a younger person than M then I would have C said, "My." If he is a younger person than M then I would have come myself, I do n't need to ask him. After this D came and said C is younger than me so there is no need to ask M so I would have come first. C come again. Now C said. Said, I have already come, I am not coming, so I have to maintain this thing, I have to find out one thing first, which thing has come to my mind, it is okay if I go and check for it again and again. So in this A is so I have to think about it some more after that I need B I checked B asked what are you D asked D can you come later D said I would have come but I Not only am I not lagging behind, not only am I not available, so D said, you, I ca n't come, so C, we don't need to check, the answer to this is A, C, B, and this is my answer. Now see, what do I need? In this question, I will need two things, one is when is an element coming last time, one is the character that is coming last time, that is, its last index is the last ex, so what will I have to do for that, I will have to basically create it for that. I will create an array, last index, that will be the whole one of 26 size, okay, I will make the whole array of 26 size, below it is a little bigger, I can show you the last index, which will basically take care of each character, that last time, see how to do this. First it is understood that it is okay like this is zero, this is one, this is two, this is th, okay this is four, okay up to so no, this goes till 25, now what happens which is zero. It represents a, this b, this c, this e, okay, this d and e, I make them small, why I made them small, I will show you now and this is for z, okay, so basically something. This happens, now why have I taken small characters because in the question I have given a consist of lower case letter, lower case English letter, so I do not need to do any conversion etc. in it, I have given a lower case index if my If I know the index of any element then I will be able to do this work. Let's do it again. Okay, we will solve the problem one by one. Okay, like what is the last index of S? First I write the indexing here 0 1 2 3 then 5. 6s is fine from the end, so C came on the seventh last index, this is how to fill, it is very easy, it means there is no A, there is nothing true in this, six and C then came on F, it is fine, the end came on c3 again, what does it mean? No, it came on a2, okay, there were A CDs in it, so I mentioned it and rest of the default value remains zero, you must know that inside the array, this zero is ours and this is the character, otherwise we do not have any meaning. See, now let's do the same story again, now C came for the first time, so now BB asked C, will you come later, so we went and checked whether we are on One Index now, is C coming anytime after One Index? The last of C is from A, which means C will come later, so what did I do? I just removed C from here, I wrote B, now I am standing here, after this A came from A. We saw that B is before A, so We saw that B is coming later, B is coming after the second index, B is coming till the sixth index, so we removed B also and who put it here, I saw A, okay, after that came C, we are standing here. Now C saw that brother is a younger person than me, first of all, I do n't need to check with him, so C will come directly, okay, after this DD also came and saw that he is a younger person than me, so I myself The meaning of this small character can be said. How is this small character being said? Graphically, in the dictionary order, the one that comes first is the smallest. A comes first, after that, B, after that, C, after that, D, after that. Now we have to take care of this thing, how will I check this, I will explain it again in the next iteration, then I will explain it in the second iteration, now this duplicate is coming, so I need to check it, now BB has come. B has checked D, when is D coming last, I myself am on six and D came on fourth, so I need to check, D will not come again, I came to know that D will not come again, so I myself come again. Duplicate If we did not check the duplicate corners, then one of our problems got solved that if we save the index and keep it with us, then my work would be the same. Now how will I know that I already have a character and check it. If it is not there, then for this I will make a bullion galleon, this is also I will make basically one of 26 size, this also I will make 26 As in which basically everything will initially fall first, this will be representative for J, this will be for A, this will be for B. This will be for 'C' this will be for B. This will be for 'C' this will be for B. This will be for 'C' till 'J' for 'Ydi'. Keep all the initials false and till 'J' for 'Ydi'. Keep all the initials false and till 'J' for 'Ydi'. Keep all the initials false and I will make them true as each character comes, all these are also false. Okay, I will also give it indexing from 0 to 25. Now let's do it again. Let us do the same part again but now we will do it with the help of Lin Aare, so first of all C came, as soon as C came, I made it true, brother, C has come to me, now you make it true. So I made C true, now BB came, first of all, checked whether C is bigger than me, yes, if he is bigger then I have to ask C, can C come later, then we asked C, can C come later? Yes, I am standing on one index, C is coming for the last seven times, so C will come later, so I removed C. When I removed C, what did I do, I made C fall first and then Later, when I brought B in my answer, I made B true first. I made B true. Okay, after this came A. Now A got it checked. What is the first thing? A first. A has not been placed first. A falls already, so we will check A. Now get A checked. I am asking B. Can you come later? Now I am standing at the second index. Will B come later? Yes B. If it comes later, we removed C and B, removed B from the answer, then I made B false from here also, and then removed it, after that I removed A from the answer, so A is false. I made it true in the array also, I made it true in the lien array, so I made it true here, now A is the answer, it is ok, now as C has come, first I have checked C, first C is not coming, then C is false, now C can come. If it is smaller than C then there is no need to ask C God has come D after that D I got it checked It should be said that C had come earlier so I should make it true. Okay, D came after this. D said that he is a younger person than me, so there is no need to check me. D came himself. As soon as D came himself, he was bullion array which is present. Is it true or not? Then again came C. I checked whether C is already present or not. So I did not have to check. If C is true, I skipped it. After that, B Aa B. Falls So now B asked D can you come later then d4 is ok and K himself is standing on b6 so can B come later if he can't come then d himself come and join here and C came after that C Here I have made B also true. C is already there, so we did not add C and we have done this work. Now look, there is one more problem that how will we remove these characters, the ring which would be It is basically to remove these mutations, so for this we can use what is the stack of the stack, we will keep adding characters in the stack and will check from there, now let's see how to do that too. I told you Nana, there is a lot of it in this. All the things are being used, okay, so for this I will use the stack. Okay, so I have used the stack here. Now look in the stack, now how to do it, let's see it first. First, I will do it once. I make it all false, again I make it all false, once for all, false, falls and false, so I made it all false, first, now what did I do, the tag came first with C, then C. As soon as A came, what should I do first? I made C true. Okay, after that came B. Now B saw the peak of the stack. B is standing here waiting. Is there a bigger character than me on the peak of the stack? Brother, if he is elder then ask him, will he come later? B said, ' come later? B said, ' come later? B said, ' Yes, I will come later. You are standing at one index, I can come at seven index too, I can come from second to end, so you come first.' First I made C come first.' First I made C come first.' First I made C false, I made B true, false, I made C false, I made B true, and in place of C, who put B? Okay, now I turned to B, now it's A's turn. Asked again, did you understand? A asked again. You have to ask B only if you have a big character. If it is big then you have to ask. B, can you come later? He said yes, I can come later because you are currently on the second index. Stand up and I B is coming till the six index. If the last index is six, then if I come till six, P can come somewhere in between. When I come till six, he said, you get removed, work to remove B from here also, remove Y from here too. Do it and A came to his place. When A came here, A marked himself that I had come so that he would not come again. So I made Now C is waiting towards C is saying that you are younger than me so I do n't need to ask you. I came just like that and got myself true marked. I came after C. D also came straight away because he was younger than him. He also declared himself true saying that he was okay and came after this again. Now see, when C came again, C saw that I had already come. If there is truth in chaka, then there is no work for tr, if there is no work for tr, then si ho has come, now b has asked, no, earlier had come to bring ko, now b aa b has asked d, can you move away, why because b is so. It is false, now I saw D is saying brother, I am standing on the fourth and you are standing six, I will not come later, so if you want to come, then you come to me, then B, I would have come, after that, C came again, now C. Check it, I checked C, now B is true, check C, so C is C, it is already true, it means it is true, if not again, then what happened to us, this answer is completely ready, now look at the answer, how to prepare. First I need to know how to remove all the elements from st, after that I have to reverse it. Okay, and this work is very easy. If we do it first, then if I reverse it in the answer, then what will it become? A.D. Okay, this will become my answer. A.D. Okay, this will become my answer. A.D. Okay, this will become my answer. Answer, this part is very simple, how to do it, see first of all let's go to our code and start coding one by one, so I came here, first I will do everything first, I will have to make it last. Index Okay first of all let's create it so I created a last index array int last index equal to new int 26 so I created a last index array now how will I put that let's see for int a e 0 a lesson add length a p Ps Now first of all I have to convert the character into index, so first of all I take out the character. When I added it, I inserted the character here, after that I take out the index. How will the index come out? I wrote the index, now I will explain. How does it happen? Look in the convert index. First of all, I changed the character to 'A'. Okay, now let me changed the character to 'A'. Okay, now let me changed the character to 'A'. Okay, now let me explain a little how it happened. However, it is worth explaining in this question. Look, what happens is that we have a value of 'A' like lets say. That value of 'A' like lets say. That value of 'A' like lets say. That I don't remember A, from Let's, the value of A is 56, then the value of B is 57, the value of A is 58, so if I go on till A, then I have done here like let's come in the vector, then what is A mine A, what will be 566 B mine A? 57 56 What will happen to mine A, in this way I will get the Ix which we had made last Ix, he had taken G, I was repainting G, A, so it was getting repainted with this, so in that way, this part of mine will be done okay. Now, I am not going to go too deep into this here because by going too deep here, we will miss the main question, what will I do now, see my last index, which is the last index array, index of the last index, sorry. What will I put on the index of the last index, I put it which is our frequency which is where our character is coming and last there, after this I will have to create a bullion present whether it is present or not, otherwise I have created a bullion for it. Present array created Bullion Present is equals to new Bullion In this I also made it of size 26 Look whenever an array of Bullion type Bullion Cy is created then what happens in it too Initially falls are always the same Initial falls are fine all the time Like when we make integer type, what is there in it is initially zero, similarly what is there in bullion type is always false everywhere, so this thing has been done directly, now I have done this thing, what to do now? Now I have to create a stack, what type of tag have I created, character type, I have created a stack, I have named it New Stack, okay, so I have created something like this, now what I have to do is to travel through the entire string and create a Have to extract a character, do things according to that character, okay, so first of all, I saw, first of all, I put a loop for aa e 0 aa le addle r l ok i plus ps, first of all, I extract the character of the string, yes, I get the character. And if I want to extract both the indexes, I copy it from here, I copied it and pasted it here, okay, so I extracted the character, now see when I have to work, when our boolean which is our that which is inside the answer stack if If that character is not present then what has to be done means I put that index inside the present and if it comes false then only I have to work, that means how since late we already have A in the string, A has come again then I have added boolean of present. Go and check that it is not there because it is false and whenever any element is present in it then it has to be made true, otherwise only if it is false then we have to work because it is not already present, it means that If you run then you will understand better. Okay, so first of all I checked that it is false. If it is false, then we will work. If it is false, then what do we have to check? If the size of the stick is greater than that, then the size of the stick means there is something in the stick. Only then will you go and pop it from it, right? Which is the peak element of the stick. If it is big, it is bigger than our character, only then we need to pop it. If it is small, then it was going to be popped directly. You have seen it. Is it there and what else have to be checked, is it coming later or not? That means we have to check the frequency, the last index, we have to check that, so for that I have to call it the peak of the stack. I would make this square dot a little square, widen it a little bit, and subtract the vector that is at the top of the stack. If it's fine with a, then I will get its index and I will check if it is big. We had seen that only if it is bigger than me, I can pop it. First, look, the size of the stack should be greater than zero. The character lying at the peak of the stack. It should be bigger than our character. Now I have to check whether it is coming later or not. Otherwise, I checked in the last index. The character which is from the peak of the stack is somewhere on the element at the last index. It should be bigger only then. So we will pop, now what do I have to do before popping? Before popping, I have to go to our present element and mark it false because if we are popping then that element will be removed from there, so what do I have to do for this? I have to go to the present array, where in the present should I copy this part, so that I can get the peak of the present also, I have to go to that array of the present and mark it as false, what do I have to do after doing false, I have to do Pop from there is fine, I have to pop from there, so dot, I made it pop from y. After popping, till the time oh ok, if will not come in it, why will come in it because there may be two or three letters together which we have to pop, okay. Going ahead, we will discuss it in the example, this is also fine, so I have done it, now the character that was there will itself be pushed, it itself was always being pushed, so we have to push it, so I said Cuttack Dot is the push character which is ours. The character was pushed, after pushing it, what do we have to do in our present array. If we have to mark it also, then what will I mark in the index of present? After marking, when the whole of the When it will be run then what will I have in the stack and all the eight elements will come. Now what do I have to do? Basically now I have to create my string. If we have to make repeated connections in the string in Java then we should use String Builder. So I have used String Builder here. Do this and initialize the MT string, now what will I do, see while the dot size is greater than zero, what to do till then, keep appending in string builder, pop whom with tag and append in string builder, now see the answer that would have come, stack. If it has come reverse because of , then stack. If it has come reverse because of , then stack. If it has come reverse because of , then what do I have to do with it? Basically, I have to convert A. B. Dot. First of all, I have to reverse it. After reversing it, I also have to convert it into string. So, I completed this step all at once, okay. So that the code is not too big, it is not good, although the code is quite big, once you run it, see if it is working properly or not, then you will see if there is any mistake, then it is working fine, just submit it and let's see in this case, if there is any error. So we will see and solve it, okay, maybe it has been submitted, otherwise it would have become red again, okay, once it has been submitted, let's take it to where on our white board and do this. Okay, so I have this one. We keep the parts, mainly we want this part, okay, I mainly want this part, so I got it done, the new page question is quite good, a lot of things are being used in it, okay, you will have to see it twice. Watch the video so that you can understand it better. If you can understand it in one go, then it is very good. Once I see the example, have they given it is okay, I do it, okay, so I have taken this example, I would have written it down. I am t B A S D T B and I also write down its indexes 0 1 2 3 4 5 A First of all we will have to create a last index Now see how many B CDs are there in this, so by the way, let's make this four, make A B CD and You can also create it, however, I don't need the account, how will it be the last one? First of all, what will come if I do C minus sign A? If I come, what will happen after coming, but basically after going to T, it will be indexed in C. After going to zero, it will become zero, then it will come to B, then it will become N, then it will become A, then it will become T again after coming to C, so I did it on Y, then it will come to D, it will become F, then it will come to C, then it will become F. Came again in F, after that came in B, C came in B, came in Si and C came again in Se Bat Bar, Last Index or Last Ix D. Now what do we have to do, let's make B, we will make B small, its region because We have four conductors and placed them everywhere, this is for A, this is for B, this is for C, this is for Y, we have also kept this complete false because this is initially false only, okay, after this I made a stack now. As soon as we come to the stack, first of all we are getting two or three things, we are getting the character and we are getting an index. What will come in the index? Okay, now we have seen that present of index is false, present is false. Now see, why is C false? Exactly, because if it is false, it means that it is not present. Not quite present. The size of the stock is zero, which is greater. Yes, no, the size of the stock is If the condition is zero then if the first phase happens then they get stuck and told the conductor to push it, we pushed it and went to present of index present of two and made it true, made true of present of two then went to present of two and I did it. Marked True, now it's B's turn. Now look, now B has come in the character and B has come in the index. What has come in the index? One has come in the present of index. Present of one is false. Yes, it is absolutely correct, why because even now there is no present. The size of the stack is not zero. Now what is the element at the peak of the stack? What is the peak of the minus score of the peak? So this is also greater, what does it mean, what did they do, it means that you have to pop, so when we did the pop, what did I do before the pop, I said go to the peak of the stack, meaning go to the present array, you mark C as false. If you do this then it will mark the C as false. After marking it as false, what do you have to do after marking it as false? Pop it from the stick, I have popped it, then remove it from here, what happened as soon as it was removed, it got removed from false. Remove, what are you saying now? If you go to check again, if the size of the stack is zero, then it will not be able to be checked. Now what happened to the stack, push the character. It was character 1 and the present index of index was one. Go to it and make true. Make it into two present of index. Look what we understood from true. From true we understood one more thing. See what element is there in the stack till now. It is becoming true for that. Look, there is B in the stack too, so for B. If it is true, then I hope. So it must be clear to you. Now it is the turn of A. Now look. Okay, now A is stuck, so A is in the character. What is the index of A? Is it zero? Okay, that means I hope. So it must be understood that if the index is present then it is false, yes is false, if the size is zero, otherwise this condition is true, it is true that the peak of the peak has reached, BB is greater, yes, this is what happens. is also true then last index chk last index of whose b's six is sis index of whose b's six is sis index of whose b's six is sis greater than aa's value kya hai to is 6 greater than is yes to is ok this is also true if If both of these things are correct, then it means that now it can pop from here, all three conditions have become true. Now in the present of int, go from the peak of tuck and subtract one. It is okay, meaning it goes here and says that the one who is lying here is Make it fall, after making the fall, pop it, now again, is the stack empty now, Chu Poo's Poo is empty, after it is empty, said, push it and said. Go to present of zero, go to index and do 'Y' on 'Y', 'I marked 'Y', I index and do 'Y' on 'Y', 'I marked 'Y', I index and do 'Y' on 'Y', 'I marked 'Y', I understood 'C', then 'C' came to me, 'Y' understood 'C', then 'C' came to me, 'Y' understood 'C', then 'C' came to me, 'Y' comes to me, what is the 'ix' of 'Y', what is the 'ix' of 'Y', what is the 'ix' of 'Y', now again present of index is false, the size of the half stack is zero. No, what character is there at the peak of the stick? Go and make it true, I made it true as well, okay, so I hope you understood this part also well, after this again after rotating the loop, it came towards D. When it came towards D, it wrote here D. And what is index of What is greater than If you make it true, then it has been made true. What do you have to do after making it true? The loop will run again. C has come. Now let's see how our work with C will be done. Present of index is false, meaning here also I change it, first came in the first character. What is the meaning of 'C' in C index? So this is false. What is the meaning of 'C' in C index? So this is false. What is the meaning of 'C' in C index? So this is false. False means we don't have to do anything but skip it. See how well you understood it. How did you skip it? We came to know because it has come before so we don't even have to check it. C Now B has come, brother, everyone. B has come. B said, I am still in the line. B has come, what is the index of B? One is okay, it is a little r. It has come, its index is false, okay, the size of the stack is zero. If not, then the size of the stack is greater than zero. Exactly what is the peak of the stack? Si hai toh last index of sorry check last index of stock what is the puck of last index of stock what is fo greater than aa ki valya kya ki sagter hai nahi hai He said brother I will not come later If you have to come first, then push character B in the stack. After pushing character B, tell him to mark it as true. If you do not mark it as true on your own, then there will be a problem, so after coming here, I also marked it as true. After C, we moved ahead towards C. Now C has come again. The index of C is two. When C came again, we saw again that it is true. In the case of true, we do not have to do anything, so we finished the thing with this. Now see, my stack is ready. Now what I did in the next step is quite similar. What I did was, first of all, I created a spring builder and appended it upside down, BDCA, after that, I made it reverse. What about doing reverse? Made A CD B and converted it into string and returned it. Okay, that part is quite simple. You guys, I hope you must have understood it very well. I tried a lot so that I can explain it to you very well, so it is okay. If you have any doubt then you can come and ask on our Tegra channel, you can give your suggestion in the comment section, whatever is your work, it is ok and see you guys tomorrow where we will be solving the next question. Then thank you. If you liked the video then like the video and subscribe the channel. See you guys tomorrow. | 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 |
766 | foreign with lonely Dash and today we're going over toplet's Matrix number 766 of elite code which says given an M by n Matrix return true if the Matrix is dopelets otherwise return false a matrix is toplets if every diagonal from top left to bottom right has the same elements I'm only hoping I'm saying this word right hopelets uh if anybody knows if I'm doing it wrong please let me know uh anyway so here is the example Matrix that was given in the question and I've written it out as an actual Matrix over here to kind of give you the idea of what it would look like in your actual coding and we know that this is a toplets matrix right because up here in the top left hand corner we can see a one and if we go down one and oh right one we can see it's also a one we go down one and right one and I can even show you this here this diagonal all of the numbers are exactly the same if we do another diagonal all of the numbers are exactly the same and another diagonal all of the numbers are exactly the same so that is a hopeless Matrix now in order to figure out whether something needs to be returned as true we have to start off by identifying two things first we need to identify the number of rows here that we're dealing with and we need to identify the number of columns that we're dealing with so obviously here we have three rows and four columns and so I'm just going to identify them and I'm sorry I'm kind of writing with my mouse today it doesn't look great but here's our number of columns and our number of rows using zero based indexing okay so really we know that if we're thinking of it in terms of M and N up here as we are given in the question our m is equal to the number of rows which of course is 3 and our n is equal to the number of columns which is four and we're going to need to know that information in order to write our code so when we're thinking about it we could brute force it and we're starting we'll say okay in order to solve this we're going to look at our very first number in our uh row and our very first number in our first column and we're just going to say okay is 0 the same as 1 and we'd say yeah of course we're just adding one to each one of these um each one of these indices and we'd say okay that's the same We'll add it again we'll add one to this and we'll say okay is 2 the same well yeah it is and we could go through all the iterations and that would be perfectly fine it'd be a little bit more complicated but for purposes of today we are going to start at this lovely number we're starting at one and instead of comparing down and right we're going to compare up and left okay and the reason is that we're going to get down here eventually and I'll make a little bit more clear we're going to end up down here and because we know the number of rows as soon as our I guess you could call it a pointer as soon as we leave our area it's just going to stop and we're going to move on so I'll give you an example we'll work through it so we'll say okay is our number at 1 the same as our number up and left at 0. yes of course it is fantastic we're going to move on but we're not going to move on to the next number here we're going to move this direction right because we have to finish all of the rows so then we're going to ask ourselves okay is the number here at 2 or I should say 1 2 is it going to be the same as 0 1 which is this number yes it is great we're moving on to the next column and we're going to ask ourselves okay is this number the same and this number is 1 3 is it the same as 0 2 and of course it is yeah yes and we can't move right anymore so instead we're going to move down and go back to our one column and we're going to do the same thing comparing these two numbers and then we're going to compare these two numbers one and two and by the time we're finished doing that we'll have compared these and the only things that we have left to compare are this 4 and this 9 which interestingly we don't have to compare it because they have no diagonals so if we can get through this entire Loop of comparisons then we can return true if we complete the loop however if at any time the number to the top left does not match the number or the element that we're dealing with we're just going to return false okay so I know that sounds maybe a little bit complicated but when we write some code it'll become more clear so again if we're looking over here on the right side of our matrices we're going to compare one number to the number above and left two of it then we're going to continue on in the column and our next step will be to compare that number to the number above and left of it and then we're going to move on again and we're going to compare the number on the right side to the number above and left and as soon as we run out of and room in our column we're going to move back to index one and compare the next row until we get to the end of that column and when we reach the end of the column at the end of the rows we are done and we can return our answer okay let's see if there are any edge cases to consider for our edge cases let's just take a look and see what our constraints say okay so we know that m is going to equal The Matrix dot length or the length of our Matrix which means that's going to be our number of rows we know that our n is going to be the number of columns because of Matrix I dot length in this case I guess they're using Java is basically saying this is Matrix one here or I'll even highlight it here this is Matrix I the length of it is 4 so that tells us the number of columns so that is going to exist because M so our rows we're going to have at least one row and our n is going to have at least oh it's going to be less than 20. so it's going to be fairly small equal to or less than 20. uh okay so I guess theoretically we could have no columns we can't really have negative columns it doesn't say it can't be zero so we could theoretically have I guess one column because we would do a single index at any rate and that our Matrix i j is going to exist entirely so there's not really any edge cases to consider let's move on to some pseudocode for our pseudo code you can see I'm just going to be typing it into the python section of the elite code website again it doesn't matter where you type it so the very first thing that we need to do that we talked about was identify okay so I'm just going to do identify the number of rows in Matrix okay so that's the very first thing we need to deal with and of course we need to identify the number of columns in our number of rows right so we have our rows which go left to right in our columns which go up and down if we don't know the numbers of each we won't be able to move forward so that's the first two things then we're going to have to create a loop so Loop through each row and then within that we're going to have to do a nested Loop that also that Loops through each column right because when we talked about it we knew that we're starting on second row but we're going to go through the column first and then move on to the next row so that's why we're looping through each row that also Loops through each column okay so then if the element that is above and left of the current element um is not the same so it's not if it's not the same then return false okay otherwise uh we are going to continue the loop right because it's just going to Loop through each one of the columns going left to right and then it's going to Loop down through each one of our rows uh if the loop finishes then return sorry then return true because if it completely finishes the loop that means that we are in a topics Matrix and you just return true now it does not look like a whole lot of code to write and hopefully this will become more clear when we get to actually writing the code so let's go do that now foreign okay as you can see I just copied our pseudocode into the Java work area of elite code website and we're going to follow line by line so first we need to identify the number of rows in Matrix so we know it's going to be an integer so integer rows we'll call it rows for the number of rows is just Matrix dot length right simple straightforward next integer columns right we need to find out the number of columns in each one of our rows and that is going to be the length of the very first row in our Matrix so integer rows equals Matrix length and integer columns equals Matrix of our first row length l e n g t h am I just misspelling that entirely links and again length there we go now that we have identified our number of rows and identified a number of columns we can get rid of that we need to Loop through each row that also Loops through each column okay and so we're going to use a for Loop so 4 and we'll use integer I equals zero so this is going to be you know what let's change it to row right so integer row so it's going to be one row and it's not even going to equal zero it's going to equal one right so we typically start at zero because we think we're going to start at the beginning of any of our rows or matrices but remember we're not starting looking at the first element in our Matrix we're looking at the one on the second row in the second column and when we're using zero indexing we're going to have to start on row index one instead of zero so for integer Row one as long as the row is less than rows right because as soon as we run out of the number of rows we've got to stop our Loop and we are going to iterate row plus it goes by one okay so that's what's going to iterate us through each row but we also need to iterate through each column so we're going to do the same thing so for integer column oh column that's going to equal 1 and as long as column is less than columns less than the number of columns we're going to iterate also by one all right so that's what's going to take us through column M ends s there we go make sure I spell it all right so this line is going to take us from left to right and then as soon as we finish the first or as soon as we finish that row this line is going to take us to the next row below it and all we're doing is comparing the number that we're iterating from or iterating through with a number that is above and left of it so how do we do that so if Matrix and in this case row right because this is going to start at one row column and this is also going to start at 1 does not equal Matrix rho minus 1. and column minus 1 right so our row and column we're starting at 1 and we want to know if it's the same as up left which means it'd be one minus 1 is 0 and 1 minus one is zero so if it is not the same as the diagonal up left then we need to return false otherwise it's just going to continue through our for Loops until we reach the very end and when we reach the end of our loop we're going to return true so if we get to the end of our for Loops without returning false that means it is a topolitz uh Matrix and we're done so that should be all of the code that is necessary for solving this problem let's hit run code and see how we did and accepted let's hit submit to see if it fits all of our test cases we'll have a look over here and yes it's done now this shows that it's two milliseconds but faster only than 38.07 uh I don't but faster only than 38.07 uh I don't but faster only than 38.07 uh I don't know why it says that it's usually a pretty darn good way to solve this type of question but that's it that is all the code you need in order to solve The topolitz Matrix question using Java foreign | Toeplitz Matrix | flatten-a-multilevel-doubly-linked-list | Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._
A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements.
**Example 1:**
**Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\]
**Output:** true
**Explanation:**
In the above grid, the diagonals are:
"\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ".
In each diagonal all elements are the same, so the answer is True.
**Example 2:**
**Input:** matrix = \[\[1,2\],\[2,2\]\]
**Output:** false
**Explanation:**
The diagonal "\[1, 2\] " has different elements.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 20`
* `0 <= matrix[i][j] <= 99`
**Follow up:**
* What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
* What if the `matrix` is so large that you can only load up a partial row into the memory at once? | null | Linked List,Depth-First Search,Doubly-Linked List | Medium | 114,1796 |
419 | Hello Welcome Back Friends Today We Are Going to Solid Code Problem 498 A Lips in Awards Show's One Environment Report and Beach Sail Kiss Battleship Another Anti-Return Number of Kiss Battleship Another Anti-Return Number of Kiss Battleship Another Anti-Return Number of Battleships Folded Inside Battleships Can Only Play List Horizontally and Vertically On Board in Words They Can Only Be Made for the Shape One Member in and the chapter we battleships time just us example clear for the explanation to edit can see his own this is one battleship and sister mother battleship so others can give vertical or horizontal only possible to battleships has come net how many battleships and there And Mother Board is Ashu for this Problem Hui Can Easily Solve Organizing Like a Difficult Hui Travels Matrix from the Beginning Cell to the End Cell and Wherever Hui Find Character One Day Will Be Counted as One Battleship Goddess Fountain Do You Will Apply Edifice on the Cell The show will try to go for directions for example after and hydrating like this metric from beginning software and because it means the Twitter account Battleship S 1251 Battleship and will try to interest in evil Try to deficit in all four directions like this is one direction and Right side inside don't side and in the left side of this will take you were going out of the world din will just returned at you inside the board and what do you will open the app quit Rahul Kumar all details with tejaswita star you know what to Do something different character so I do n't and on accounting battleship you know of Agni and lag more times for example hui seedhi 600 bill account battleship is vansh and will change the verses star character is clear aaj to vrat ki vriddhi hui a clear name Renu video ko Here In The Matrix And Will Andar Plus Form For Stroke Player Song Again Hui Servi It Means The Two Front 's Second Battle Of Years Will Prevent 's Second Battle Of Years Will Prevent 's Second Battle Of Years Will Prevent Account Battleship And Will Apply To Divorce In All Four Directions Care That Sui Will Make This Character A Star So I Will Not Count Login And Solve Veer Is Silver Gain C 10 Gram Doodh Defes So Will Do Like Ka Up And Down World And Left Side And Don't Like Share And Will Change This Character A Celestial Against Will Not Count Begins Again You Witch Year Song Again selections will try Tubelight ka Dandruff World types of download and in the left side and will changes character apps and pain wherever setting on this second universe the control of matrix like you will go near and dear su will see you will not see a senior ministers Will Not Counted As Another Battleship Already Process Of Development This Battle Scene Already Discounted Dushwar Them Z1 Battleship 100 Deaths Your Solution Will Work For Battleships In Board So Let's Go Through The Solution Superstar Creative Everyone Contest Battleships And Here That They Are Going To It Read through the two back to board will have been given substances recently at you bittu matrix from 028 board link earlier and interested to find the character experience that is where the battleship is going to start starting with SVC at character on the board will increase in the Number Battleship Servi And Will You Life Strengthen This Community Sill Subtle Edifice Civil Works No Merger Notifications So 0 And Greater Than Body Language Se Zor A Greater Than Gold For Gift Character Data And Details That One Day Were Rich Nothing Doob A Farce In that case otherwise we will mark the celebs who want to change the character to another character and share with the people with a difference in all directions for directions meaning of this leaflet from this day a sale 500 verses to come to me is a so if you See the past cell this is sahay minus one tasty come minus one row end column SIM columns a few of the world with me to go and right side ki daroga this time end column will visit plus one because they are going into the column that end e Was going download here oo will increase by one convenience plus one oo a clear and calling specific objectives naseem column and issue gond left side clear daaru will just as in a problem will decrease by one development versus previous column on 220 initial chairman md face where playing Clear S U Can C IF IM Minus One J A IG Plus One Five Plus One G And Oil J Minus One So Let's Chest Like Toubro The Test Cases Give Arrangement Sure Weekly Castor Stitch K Send Mixture Tree Working Correctly So In Forest Swayam Example Receiver Discussing Som Hui Powder To Battle Tips And Other Ise Intimate Rickshaw 150 Battleships Solid Submit This Code A Song For Disseminating Accepted One Hundred Percent Of The Runtime Error Zero MS Evidence Year And Fifty Seven Percent Better In Memory Usage Of All Sorts Of That Can Solve The Problem Of Number Of Battleships On Mode On The Question Certificate For The Interview Young Developers So Insisted Of Waiting Number Of Battleships Another Question Zoom Encounter Is Like You Know After Accounting The Maximum Size Subscribe To Track Of Union President's Setting On The Battle for Example Subscribe of the Volume and of the Sheep and Wool 220 Front of Questions Respect Like Uniform Finding Number of Things on Board Basically and Finding Minimum Battles Minimum and Size Battleship and Maximum Five Battleships So Life is Solution Helps in Understanding This is the Problem So Accurate Awesome Solution Subscribe My Channel And Like Button And The Bell Icon So You Will Also Get Notification Open Poster In Solution For Lips Problem Solve Thank You For Watching My Video | 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 |
5 | Hello everyone welcome to my channel Quote Sorry with Mike So today we are going to do video number 72 of our dynamic programming playlist. Lead code number is five. It is a medium question but actually it is quite easy. If you look at it then the constraints have also been kept small. Okay and This is a very popular question. The name of this question is Longest Palindrome Substring. It is ok and many companies have asked for making it. I have mentioned only these three. You will get the list of the entire company in the description. Ok, so you will get one by one for Longest Palindrome Substring. String S is given. Okay, you have to return the longest palindrome substring. Now you know what is a palindrome and what is a substring. Okay, let's understand by looking at the example. Like look at this example, which is the longest palindrome in it? You should have a palindrome substring, but I am seeing that one is A, ABA and one is B, OK, so any of the two can write the answer, the length of both of you is three. The biggest one is only of length three, okay, so you have to return the substring. Look here, the biggest palindrome I can see is B, right, this one would be ok, let's assume, let's take another example, A C, which is the biggest palindrome in this? Yes, this is a palindrome, otherwise the maximum length will be either A because a single character string is a palindrome. Right, it will be either C or E. Your answer can be any of these. Ok, you are looking at the length. The maximum length is one. There is a maximum in this. Length 2 was asked, maximum length was given in it, okay, it is a simple question, we will approach it in a very basic way, we will make it with the latest approach, okay, let's see, look into part A, let's understand it. Okay, look, tell me the thing today. How do you check whether a string is a palindrome or not? Well, there is a very simple way, people reverse it, like let's assume it is ABA, reverse it and ABA will come out if both are equal. So palindrome is ok, what are the other ways, one way to do this is very simple, look at this one, look here, first, what will we do, take a pointer here, are both equal, yes if equal, then the rest. You will not have to check whether i is sent here or i is sent here, are these two equal? Yes, then i is sent here, h is equal? Yes, then i is sent here, h is equal? Yes, then i is sent here, h is sent here, both of these are obviously equal, that is, how simple is the method, you can create this by using two pointers. Can you? I mean, I think this is the simplest way to check palindrome. Well, if you look at it, its code is also very simple. Now I am just telling you how to check palindrome, so if I make it through iterative approach, then write this. For palindrome check, I will start from i = 0, I will start from j = n - 1, start from i = 0, I will start from j = n - 1, start from i = 0, I will start from j = n - 1, right, and how long will I simply run till i is less than or equal to j, only then i was here, j was here. i came here j came here and so on run till i le = j only came here and so on run till i le = j only came here and so on run till i le = j only then it will run ok if my given string is s of i to it a of j ok then it is good na mean If these two characters are the same then what will I do, I will move ahead L plus sorry I plus j minus and if it is not so then break it or return false is fine meaning if two characters are not found equal then the same. Time should return false because this is not a plum, let's assume that it is ABC, okay this A is here, J is here, if these two are equal then there is no need to check the rest, isn't it? Let's say there is something A This is B If this and this are not equal then why would you check the rest For now if this whole string is palm a bit okay then we will return false at the same time Okay and if these two If the characters are equal then we will move Aa forward and J backward. Okay, this is an iterative method. There is also a recursive method. Just convert it into recursive. What will we do in a simple way? We will write a solve function. There are two pointers and AaJ is okay. If aa which is this is my greater than equal to h then it is right meaning I have compared all the characters and aa which is h has reached or aa has crossed h means all the characters have been found equal right then I return true. I will make sure that all the vectors were found equal, that's why I reached here further, okay and if it is not so, then what will we check that if S of I is equal to Il to A of J, then what I said is that further. Check it means check i psv and j mive and if it is not so then return false else then return false. This is a very simple ratio code. Pay attention to it. Okay, what did I say that if both the characters are equal i and j then Okay, you check p and j. Okay, check from there and if it is not so, both are unequal then return false. Okay, and how will we call this, i, mine will be starting from zero, j will be from n. Look similarly, it was the same here too, so look similarly, I converted the iteration into recursion, so there are two ways to check whether any string is a palindrome or not, okay, this is the normal thing, I have told you. I have taught you, now let's come to this question, okay, you pay attention to this question, I will take the first example is mine, what is B A D, okay now let's come to this, pay D B A D, okay now let's come to this, pay attention to one thing, he said that Find the biggest substring and show it which is palindrome. If the substring is said to be palindrome then it is okay. First find the substring and then keep checking whether that substring is palindrome or not. Okay, so there are many substrings. One is itself, one is B and which one is Which substring is visible? What else is AD itself? B was also here. Here also A is itself. Okay, here this one itself is the only substring of A. Then AD, this one is okay. Then last one is D. So look, there are many substrings, all of them. We will check the substring whether it is a palindrome or not, okay, and now look at what I actually did, pay attention to this, let's assume this index is zero here T 3 4 So first I started from here, okay first. So from Aa to Aa, I took only the string which means B. Then from I till A, here I mean B. From Aa till I took it like B. A B is taken like this. Okay, so see, R has been fixed now, I and J here. Another pointer starting from I so that I can create a substring, I'm okay, look from I to J, then there is B, then J, go ahead, then look from I to J, then B, then look from I to J, B, A, and so on, okay, then J, when If it comes till here, then the entire string will be checked. Okay, after that, what will we do? I will come here, assuming that the plum is not found, then it has come, then J will start from here, A to A, meaning this one, then J will come here from A. B is this one or this one subbing and so on, so I will generate it in all the substrings like this and what I will check for each substring is whether it is a palindrome or not. Okay, so let's say here I reached and here J reached. It means which one is this B A B is this one, so as soon as I send it to check, I will call solve, what will I send in solve Aa and J, what will it tell me whether this string is a palindrome or not, whether this part is a palindrome or not. It is a palindrome, so I need a string. So, how do I get the substring of this string? S Y B S T R I N G Where is the substring starting from Aa, what is its length? Look, j - Aa what is its length? Look, j - Aa what is its length? Look, j - Aa + 1, this is the length. Na, in substring c+p, we find + 1, this is the length. Na, in substring c+p, we find + 1, this is the length. Na, in substring c+p, we find out the starting index and what is its length. Okay, so as I came to know that this is a palindrome, so I stored its substring, I also know its length, so I will keep updating the maximum length. Length, now I have got three, okay and which string is that, B A B, okay, either you want to store no string, just store the starting point means where did it start, this substring started from zero. It was okay, now look pay attention, let's do full dry run with this understanding. Okay, look, now let's start the complete dry run. Its okay, so I have not yet got the maximum length, what is the maximum length of the palindrome, so I am keeping it zero. Right now, I will either keep it as int min or zero, okay, and the maximum length of the substring, if its length is zero, then what is its starting point, I will also keep that so that I can extract the substring. Remember how we used to extract the substring. What is its starting point and what is its length, so I will just store these two, the starting point, I don't know yet, is -1, starting point, I don't know yet, is -1, starting point, I don't know yet, is -1, let's start, what I said, i will start from here, we will start from the first row and j then from here. It will be okay, so I have extracted the substring from i to j. What is it brother, there is b in i to j? So what will I simply say or will I call recursion? I will say that brother, check this string from a to j to see if it is a palindrome. No, and I taught you here a little while ago that you will call the solved ones, or you can do it iteratively, I will call the recurs, okay, notice, till now I have not said even once that this is a DP question. It happens that you hear the topic, don't be afraid, that's why I do n't even talk about the topic. Okay, first you look at Intu. Right now we are building Intu only. DP has not been mentioned yet, so do n't be afraid after seeing the topic. Solve it. From this we got the truth that yes brother B, this is obvious, substring, this is a palindrome, okay, if it is a palindrome, then it is okay, what did I do, what is its starting point, zero, what is its length? Is its one is ok now let's move j from a to j I checked again solved call from i to j is this palindrome no it is not a palindrome so nothing will be updated ok j went here When b A came, I sent it in solve that from row to i.e. i to j i is my sent it in solve that from row to i.e. i to j i is my sent it in solve that from row to i.e. i to j i is my row j is my to check if it is a palindrome and it will say yes it is a palindrome then as soon as it came to know that it is a palindrome So what I did is look at the max length so what is j - i + 1 three is look at the max length so what is j - i + 1 three is look at the max length so what is j - i + 1 three is its length and what is its starting point is zero okay now let's move on b is it a palindrome no it is not a palindrome b a b AD This is not a palindrome, okay J, now it is over, I will start from another place, just after this, okay J, now it will start from here, I from J, look, A, is this a palindrome, yes, but look at its length, it is more than my maximum length. If not then I will not update then go ahead this is a palindrome no this is a palindrome yes look ABA is a palindrome but the length of this is also more than the max length otherwise there is no need to update its ok After J moved ahead A B AD Is Y a palindrome No Now J is over Okay after this I moved ahead J Started from here B is a palindrome but its length is not more than the max length B is not a palindrome B AD is not a palindrome Okay then here I go ahead J Will start from here What A P Yes but its length which is not more than the maximum length AD is a palindrome No okay After that I is here J is here D is a palindrome yes but its length which is not more than three is not more than the max length so will not update Gone is the story of A and J, what will we do? Find the substring, what is the starting point, what is zero and the maximum length? Look, its three is three. Take out the string of length from zero to three. B. A is from zero to three in length, so this is my best. Big Palindrome is substring. Got it. Okay, now focus on one very important thing, then we will be ready for the code. Now look, focus on one very important thing here. Focus on this example. It's all right, so look at this example. If the same It must have been made in the same way as I mentioned above, then we will do the same, it was simple, I started here, J started here, then grew, checked the name, updated it, then J here, checked the palindrome, then J here and so on. Okay, so let's go by the value, let's take one such state, let's go by the value J was here, so you called solve of 05. Okay, so of 05, when I checked whether it is a palindrome or not, remember how to check. We used to ask whether zero and five are equal, is zero character five character equal, 0 f, which character is A, yes, it is equal, both are equal, okay, so I used to say, okay, check further, meaning index number one. And check the index number four, okay, check this, after that he said, are these two equal, yes, equal, then I said okay, and check the next one, check th, these two are also equal, okay this. After that, two will be crossed, if it becomes like this, then it will return true, we are not ours, there is a condition of base case i >= j, then it means condition of base case i >= j, then it means condition of base case i >= j, then it means everything is fine, so even if If I look, 05 14 23, then I know that yes, this is my palindrome, so it is okay, all this must have been checked, now let's go by the value, go ahead, your loop will be bigger, come forward, it must have come here, j here. It must have come, okay, then again you must have called solve, for this you must have called for 0, okay, for this, how would I have checked the pum, zero character, sorry, no, one character, f is equal, yes, equal after that. What I did is go ahead th is equal yes is equal ok now one thing you notice here is that this n f I checked here also for g f and y f I checked for this also solved. For F also, you are seeing that all the problems are repeating, so from here I got the idea that why not when I am calling recurse or in solve, then I should memoize the result there, that means I should write it in advance. If I say somewhere that the substring from 1 to 4 is a palindrome, then I have written true and stored it here. The substring from 0 to 3 is a substring and that too is a palindrome. Here, store it for all. It was already taken so that when I would come here, there would be no need to check further, I would say, ok, this is true for 4, this is true, then I would directly return it from here to 2, saying that brother, this is already a palindrome. Okay, it is clear till now, that is why I said that when I solve the problem of recurs here, I will apply memoization here, okay, then I understood that okay, this is actually it can be made with recurs plus memoization, otherwise I am normal. Rick was writing, okay, so that's why I will not use this method. To solve this, you can also do it in an iterative way. Unfortunately, there is no mention of this in the official solution of lead code. This one is fine. I don't know. It should have been that way because it seemed to me to be the most basic and new approach. Okay, so if we quickly look at the story that we have understood, then how will it be? I had said that I will start from zero and will go to I plus, okay? And J will also start with I. J lesson will be A. No, if it was a palindrome, that is, if true came from there, then what I used to do was to check that whatever is the length of the maximum length that I have already stored and the current length that I have got, that is. j - aa pv If it is greater than the j - aa pv If it is greater than the j - aa pv If it is greater than the maximum length which is already mine then I will have to update then I will update the maximum length j - aa pv and yes the j - aa pv and yes the j - aa pv and yes the starting point will also be stored I remember the starting point what is aa And what because right now we are seeing everything from Aa itself, starting point is my Aa, so like this for loop, the entire for loop will end, what I have to do in the last is to remove all from the starting point and whatever is the maximum length of mine, a simple edge. That's fine, so let's code quickly and the function of solving the checking palindrome, I have already told you about it above and what will we do in it, we will put memoization in it, so let's code quickly, just like Explained, I first of all said, brother Rick, is a string a palindrome, what kind of string is it or not, how did they check, first of all they wrote the same function, they used to pass a string to it, an i pointer and a j pointer went into it. It is ok and if i which is >= j is reached then it It is ok and if i which is >= j is reached then it It is ok and if i which is >= j is reached then it means all characters were equal return true then ok and what will you check after this if s off i == s off j then if s off i == s off j then if s off i == s off j then check further also return solve s i + 1 and j -1 is ok and return solve s i + 1 and j -1 is ok and return solve s i + 1 and j -1 is ok and if it is not so then nothing will be returned false ok that means that character was not equal so there should be no return from here but it is being returned here so I have returned false ok now Let's come to the function with our longest length. I told you, first of all, let's find out the length. After that, I said that we will keep a variable named max length. Let's keep it as int. Okay, and starting point A is okay. Equal to what to keep now, let's keep only zero for now, either -1, you keep only zero for now, either -1, you keep only zero for now, either -1, you can keep anything, okay so it was a very simple for look i = 0 aa < n i+ look i = 0 aa < n i+ look i = 0 aa < n i+ p for int j i remember from i It used to start with j < n j+ प ok and after this it is j < n j+ प ok and after this it is j < n j+ प ok and after this it is very simple that if the solve of i s aa j is this string s which is the sub string from aa to j is it a palindrome, if aa is true then it is a palindrome. Okay, so what will I do, if the new length I have got is greater than the max length then I will update the max length as it is okay and what is the starting point, this time it is SII, I am looking at the starting point. Point is, we are checking from here only. Okay and lastly what will we do return adot substring what is the starting point a and what is the length th this will get my long palindrome substring okay now let's do one thing without memoization submit it and see Here sub string is C+ see Here sub string is C+ see Here sub string is C+ P, I had written sub string by mistake. Let's run it and see. Let's see ruble to pass example test cases. It is passed. After submitting, let's see whether it is submitted without memo. Ok, indeed yes. See why it got submitted because its constraint is very small right see so const is very small so without mem is also accepted but I also make it with memoization in 100 is ok and here memset my size is off ok so I am the first I will check that if it of i is not equal to my then return t of i is ok and since ama j is an integer then what I do here is send one more or send true, same thing. Okay, here send zero instead of false or send false, it is the same thing. Okay, so here I store t off aj is solved and here t off aj = off aj is solved and here t off aj = off aj is solved and here t off aj = 0. Okay, so let's see an example of how to test. First let's see if it has passed. After submitting it, we will see that indeed yes, this has also passed and you pay attention to what I have just done. See how many minutes are taking without memorization. Milli seconds is 1034 milliseconds and now with memorization it is 184 milliseconds. Okay so I hope it was helpful any doubt raise it in the comment section I will try to help you out and pay attention to its time so off n score so here it is done two for loops and here look at all the strings We are visiting all the characters once, so here it seems to be off, here too it is fine, so off n is cube, actually this is the solution, so see you guy in the next video, thank you. | Longest Palindromic Substring | longest-palindromic-substring | Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters. | How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation. | String,Dynamic Programming | Medium | 214,266,336,516,647 |
143 | hello friends uh welcome to my channel let's have a look at problem 143 reorder list so here the list is actually a singly linked list so in this video we're going to share a solution based on linear traversal and reversal so first i'll read through the problem statement to digest the requirement and then we go over the analysis and finally we share the code first let's look at the statement so we are given the head of a singly linked list so the list can be represented as error notes connect to l1 then connect to arrow n minus 1 then to lm so reorder the list to be on the following form so we connect the head with two then head with 2 and so on so we get l not connect with l m then l n connects with l 1 then connect with l n minus 1. so that's the requirement so we may not modify the values in the lists nodes so only nodes themselves may be changed so here are two examples so in the first examples in the first example the linked list has lens 4 so the return is then connect with 4 then connect with 2 and then connect with 3. so this is the result and in the second example the linkedin list has length five which is an odd number so we first connect one with five then five connect with two is four and four is three is now so this is the return so with that said let's also look at the constraints or additional assumptions for this problem first the number of nodes in the list is in the range between 1 and 5 times per four so this constraint actually defines the problem size and the second constraint is on the node value range which is in between van and maslodend so with that said so we are ready to look at the analysis so this problem actually is very interesting so the solution is based on linear traversal with reversal and the merge so here in this solution we're going to practice several things first so we're going to practice slow fast pointers technique and then we practice how to reverse a linked list so also we practice how to merge linked lists so here we merge two linked lists actually there is a problem in this code which requires to merge a number of linked lists so it might be useful to check the corresponding list in our channel if you have time so for this problem the procedure is the following so first we'll find the middle node using slow fast pointers method so if we are using zero indexing then the index of the node the so-called middle is the so-called middle is the so-called middle is n over two so here over means integer division and the n is the length of the linked list so for example if the links list has length um which is uh even or even number so for example 0 1 2 3 so the mid is in this node true and if the linked list has length um which is an odd number so for example five so zero connect with one with two with three is four then the middle is again this node with value 2. so this is the first step the second step is that after we locate the middle then we're going to reverse the linked list represented by the middle node so if we use example one so we can fix the idea as below so this is the original linked list so the middle is three so then we break the link between two and three and then we reverse the second half so we will get two links list one is represented by the original height so that is when connected with two then now the reverse one is nothing but four connect with three then now so this is the second step the first step actually is routine so we're going to merge the two linked lists obtained with alternate nodes from the two linked lists so we from we connect event with four and then we update the height correspondingly so then we connect four is two and two is three so we are done so this is the third step so here actually there's a remark so it's possible that the second half of the linked list is longer than the first half so when the original linked list is of odd length for example if we use example 2 so the first half will be 1 2 and the second half after reverse will be five four and three so which has length three so we just need to connect the last node after we exhaust the first linked list and all other nodes except the last one in the second linked list so this is actually a thing that is very easy to do so with the above procedure specified so now we are ready to write the code so as required by the problem we are good we're going to do the things in place so we're going to write with some detail and explain the code 11.99 so in the and explain the code 11.99 so in the and explain the code 11.99 so in the process we're going to write some annotations so first so we're going to send the middle the so-called middle node the middle the so-called middle node the middle the so-called middle node using a slow first pointers so this is actually a very routine technique so if you practice quite a lot so you can write it with uh with ease so here in order to do this i'm going to initialize a variable called previous so because i need to break the link let me do the reverse in the second step so previous originally is none then we're going to initialize a slow and fast pointer initially both pointing to the head so notice that the head is not null at the very beginning due to the problem requirement assumption the number of nodes is at least what so the links list is not on now list and then we can do the standard slow faster technique well fast and fast next so you notice or understand this condition after the next two lines so we're going to update the pre to be slow and slow move to less step further so slow next and then we opted first to be first next so that's why we have this condition first and the first next because of this condition first next is not now so we can consider fast next and its next rate because this part here is not now otherwise we cannot do this so after this while loop so actually the slope corresponds to the middle node and if we use this one as example this will be the slope and this will be the previous so before we do anything let's first treat a special case if pre is null so in this case it means that the linked list is too short so just to have one node so we just need to return the head in this case so this is actually very easy so now up to now so we have this uh what um what we want to do next is to break the link first so we this is the pre you can imagine and this is the middle so we want to break this link so previous next we'll set it to now so then we can actually get the corresponding information for the first half of the node let's print out that just for a examination so if we print height so this head will represent by one two so let's do a check yeah this is one and point to two that's everything the right so with that said let's do another thing to the second step so now the second step is to reverse the linked list are headed by and by the middle that is the slope right so we're going to do reverse so for this actually uh let's first introduce a dummy variable let's call it uh now then we're going to do the reverse so this is actually very routine well slow so slow is the linked list height right so well slow so what we are going to do is that first let's save slow next for later use and then they connect slow with dummy so this line actually did two things first it breaks the link of slow with slow next and then we pawn slow next to be done dummy so after that we can up this dummy to be slow and slow to be temp so the temp is the original slow next right so this is the standard way of reverse a linked list so after that because if we exit this loop slow will be now however the dummy is not now right so the dummy will be the head of the reversed linked list so let's print this out just for a check dummy for example when the dummy will represent four pointing to three let's do this check so you can see this there's a four point two three everything is right so now with this done so we can do the next step so the next step is merge the two a linked list by hiding by the original head as a dummy so for this merge actually it's very simple we just need to use alternating nodes from the two nodes and for this purpose i'm going to use a auxiliary node so and also make it a start so to be this node so i'm going to use the default initial initialization data then we're going to check the head so height is the first half and stop me either have a lens that is equal to the length by the height or the longer so anyway so we just need to use a head as the check condition so well ahead so what we're going to do first i'm going to save the temp with the head next and the dummy next so it's a head next and dummy next so this is the still four liter used and then what we are going to do is we connect next to be head and then we connect the head next to the dummy so after we do this what we are going to do is that so um we set the ox to be the dummy and then we are going to update the head and dummy to be temp one and ten two step temp two so from this line we can interpret the purpose of the first line after the well um vowel condition so that's about it so we have um so here what we are doing is that save template temp 2 for use later and set aux next we had and connect next with dummy and then we upped its aux to be the current dummy and then we update head and dummy by temp 1 time 2 saved earlier so that's the case so after we access this while loop so the first linked list is exhausted but the second might be not so if the second is exhausted so we're going to have dummy is empty so if not so if dummy so the dummy will be the last node in the second list so we're going to connect aux to dummy so this way actually we merged the two linked list so we're going to use this the aux as a moving variable so when we do the return we're going to return start next right so the return is simple so we're going to return start next so this up to now we finished the overall logic for this problem so now before we make some comments let's first do a special case check yeah it passes the first example now let's look at the generic case yeah it passes all the cases it should be reasonably fast because it's a linear method so anyway so before we end this video let's overview the structure of this solution so we split the logic into three parts so the first part actually is a standard practice of the slow fast pointers technique to locate the middle node and after the first step we're going to reverse the second part of the linked list to prepare the merge the third step is to do the merge of the two links list by alternating nodes from the two linked lists now afterwards we return the desired result so in the process actually we used dominoed twice at least forgive for example when we do the reverse and then we do the merge so this technique or trick is very useful sometimes when we do linked list problem so with that said i guess that's about it for this video thank you very much | Reorder List | reorder-list | You are given the head of a singly linked-list. The list can be represented as:
L0 -> L1 -> ... -> Ln - 1 -> Ln
_Reorder the list to be on the following form:_
L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ...
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[1,4,2,3\]
**Example 2:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,5,2,4,3\]
**Constraints:**
* The number of nodes in the list is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 1000` | null | Linked List,Two Pointers,Stack,Recursion | Medium | 2216 |
42 | hello guys welcome to algorithms made easy so today we are going to see the question trapping rainwater let's quickly go through the problem statement given n non-negative integers statement given n non-negative integers statement given n non-negative integers representing an elevation map where the width of each bar is 1 compute how much water it can trap after raining so let's just understand this question if we draw the bars according to the given array this is what we get and if we are said to fill the water in this shape the water will accumulate in the valleys so this is where the water gets accumulated so how do we find how much water is there on each bar at each index suppose we take this index five so the water accumulated at index five would be the valley formed by the maximum and left and the maximum and right so what is the actual level because here we can see that max's are different so it would be the minimum of these two max and since here the height of this bar is 0 it would not affect our answer if we do not consider it but if we see the case of index nine the maximum water just the water that can be accumulated would need us to subtract the height of this bar so this is the actual gist of the question that we need to find the maximum and left and the maximum and right and then take the minimum of both and then according to the height of the building at the index we can find the amount of water that can accumulate on that building or the bar so that's all that is written in this algorithm so calculate the max on left calculate the max one right and then the water on the building would be minimum of max from left and right minus the height of building so the question is how do we calculate this maximum simply we can say that there are two approaches for now that is a brute force and using an arrays the brute force approach for each bar you would need to find the maximum on the left by looping till the start maximum on the right by looping till the end and then apply the formula that we had got this approach would end up having a complexity the time complexity of o of n square while the space complexity here would be o of 1 as we are not taking any additional space how do we reduce the time complexity that could be done by using an extra space so we know that we are doing an additional step of going to the left and right all the time so we can save the maximum in the left and maximum in the right in separate arrays and then calculate the water on this building so we will have these loops to calculate the max left max right max and then once we have these two we'll have to loop to find the water but we do not need these many loops we can just combine these into one loop but just for the understanding purpose i have shown you two different loops okay so let's just start coding this one so first we'll take an integer n that will store the length of the height then we'll take two arrays which would be of size n now we need to return water so we take water and at the end we'll return this water in between we'll have loops so for we'll do a combined looping thing instead of doing the two separate loops so here at the same time we'll keep on adding right max and left max both so if i 0 then left max of 0 or you can say i is equal to height of 0 or height of i and right max of n minus 1 or the last index we are first filling up the last index in the first index height of n minus 1 now comes the else part so left max of i would become something at the same time we'll find right max of n minus i minus 1 n minus 1 minus i okay so which would be equal to something what would the left max be it would be simply max of height of i and the previous lift max while the right max would be the max of height of n minus i minus 1 and right max of n minus i now that we have the values we can again loop and this would be minimum of right max and left max minus height of i so this is all about the array method okay let's initialize this sinustate and if you submit this code that's accepted so this was one of the method now let's go on and see the next method which is using stacks here we'll take the same example and we'll take a stack and add the index of these bars into the stack till when we'll keep pushing the index till we get an index for which the height is higher than the height of the top element so here we can see that the height for index 2 which is 0 is lesser than the height at index three so we are getting a increasing height and we stop over there okay so after this what we do is we need to start our calculations on what do we calculate we'll calculate on 2 so we'll calculate the water between its left and right so water between its left and right here what becomes the left becomes the one that is there in the top of the stack and the right becomes the one that we were going to push in the stack so what's the formula here is different it is distance multiplied with the level that should be there we'll understand the importance of distance in a while for now let's just see how this is getting calculated here we are taking the minimum of top of the stack which is the left element and the minimum of height of i which is the right element so this would be the water level and the height of the pop element which is this element itself so this is the same formula that we used earlier also right now that you have understood the formula let's see how we calculate the distance is the one between the left and the right which would be 3 minus 1 and we'll subtract one more to get just the one in the between so if we use this formula we get the water here as one unit that we can see now let's take another example if you are at index six what you'll do is you'll calculate for index five because you'll get that the height of index six is greater than height of index five so here according to the formula again we get the water between these two points as one unit now is the fascinating part as we move on to this index seven here we find out that the distance plays an important role here the distance becomes 7 minus 3 minus 1 which gives us 3 and the water level that should be there is minimum of height of left and right which gives us 2 and from that we subtract the height of pop element which is 1. so this tells us that this part is filled and we need to fill above it which gives us 3 into 1 which is 3. now that we have understood the concept let's start coding for this so since we are using a stack we first need to initialize the stack next will have two variables first is the current variable and the second is the water both will be initialized to zero and then we will start looping so while current is less than height length which is we'll go from 0 to n and in that we'll be checking the condition for stack so while stack is not empty and the current height is greater than the height of the top element of stack so we'll perform some operations or otherwise we'll just push we'll push current and do a plus so what operations do we perform here first pop which we are going to take in a variable and then we'll check if stack is becoming empty or not if it becomes empty then there is no need of performing the further operations we can just break from this while loop otherwise what we do is find the distance which would be current minus stack dot peak minus 1 and we will find the water that is going to be filled so taking a variable fill which would be distance multiplied by minimum of two heights we were taking that is current and stack dot peak from which we subtract height of top now that we have got fill we need to update water that's it return water so now that we have got a expected output we can just submit this code and see whether it gets submitted or not and it gets submitted this was the stack method let's try to improve it further let's move to the more optimized version of the solution which is using the two pointers approach so what we do is we'll use two pointers i and j which are positioned at 0 and n minus 1 and we'll have some variables which would store the max left and right for our bars and lastly the result variable water in this approach what we would be doing new is that we will only consider the positions we are currently on and we have seen not the ones we have not encountered so here we'll consider 0 and 11 and we can see that there is a slope on the left side which means that the water will accumulate on the left so we would be processing the ith pointer now to calculate the ith pointer the water at it index we would be taking the maximum left minus the height of i and we will add it in the water that was already accumulated previously so for that now we see that we would need max left so we will need to update max left which is going to be the maximum of the previous max left and the current height in this case it would be zero and the height of i is also zero water is also zero so everything becomes zero now since we have crosses the ith position we will move the ayath pointer one step ahead and this becomes our new ing since both are equal we will again calculate for i and here we can see that the maximum left would now get updated because we have not seen a height so tall so this becomes one and the water becomes still zero as max left is one and the water is still zero now we will again move the ith pointer ahead again there is a slope and so we calculate ith pointer here we can see that there is a building or there is a bar which would prevent the water from flowing so it would get accumulated here and as we can see that the water here becomes one the max left could still be one because there is no height that we have encountered which is greater than one so we will just update the water so we move towards right so i moves one step ahead and here we can see that the slope is towards right so we process this right the max right over here gets updated to one and the water still remains 1 because there will not be any water on this building or this bar since we have updated this we will decrement the jth pointer and move inside so here we can see that both the bars are equal and so we process left and now increase the height of the left and so update max left which becomes two the water still remains one as there is no water that is going to be filled on top of this bar we move i and again keep doing the same here the slope is towards left so we fill the water and we will keep on doing the same thing till i and j are not crossing over at the end we will get the result in a variable water so now that we have understood this approach let's go and write some code for that okay so firstly we'll take four variables i j max left max right and water then we loop while i is less than j and now we check if height of i is less than or equal to height of j so this loop is dedicated for updating max left and this is for max wright and processing the right so max left becomes mat dot max of height of i water becomes water plus max left minus height of i and i becomes i plus similarly max right becomes max of max right and height of j water becomes max right minus height of j and j becomes j minus at the end return water so let's submit this code and there it got submitted here's the time complexity for all the methods that we have seen for the brute force the time complexity is of n square and the space complexity is of one while when we were using arrays the time complexity was o of 2n because we were having two for loops which gives us o of n and the space complexity was also of 2n which is equivalent to often while using the stacks the time complexity is o of n and the space complexity is also o of n while in the two pointers approach time complexity is o of n and the space complexity is o of one so that's it for today guys hope you enjoyed the video hope you learned something new thanks for watching see you in the next one you | Trapping Rain Water | trapping-rain-water | Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining.
**Example 1:**
**Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\]
**Output:** 6
**Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped.
**Example 2:**
**Input:** height = \[4,2,0,3,2,5\]
**Output:** 9
**Constraints:**
* `n == height.length`
* `1 <= n <= 2 * 104`
* `0 <= height[i] <= 105` | null | Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack | Hard | 11,238,407,756 |
309 | uh so we have an array for which the ith element is the price of a given stock on day i so we have to design an algorithm to find a maximum profit you may complete as many transactions as you like and that is buy one and sell one share of the stock multiple times with the following restrictions you may not engage in multiple transactions at the same time that is you must sell stock before you buy again after you sell your stock you cannot buy stock on the next day that is cooldown of one thing yes so this is uh so we it is a variation of the uh sales talk problem so the symbol will one will be you can only buy ones and sell ones and you have to find the uh the maximum profit that you can make and the second variation is like uh you can buy and sell multiple time but without the last uh like uh this restriction that you have to uh cool down by one and uh and now we have this third variation that you cannot do multiple transaction and after you buy sell your stock you cannot buy the stock the next day so we have this thing and how would you solve this sort of what would be your approach so is the cooldown one day fixed yes so uh to make the maximum profit uh we first need to buy one item at its minimum cost and we need to sell it at its maximum cost right yeah so i can wait as long as i want before selling a stop yeah the cooldown has to be like one or more than one like you can also wait like three four days to buy a new stock but you have to wait at least one day one like i would solve it nicely using um like a backtracking like uh what i mean is like i suppose this is the thing and so like i can try with buying in day one okay or not buying in day one and if i buy then i have to sell the next like so next time so like then i have to sell or not sell but i have to sell in some day and then i can do it again and get see the maximum profit that i can make like i just try all the possible combination like i can like buy in day one and then i pass this function again like two three four two three zero two but i have to sell it the first like the next time or i choose not to buy in day one and i just do two three zero two and i have to buy the next time so now for this case i have to sell right so i can like choose to sell in day two so if i sell it then i will get three zero two but i because i sold it i cannot use the three again so i have to buy and i have to buy the new next time and because i have bought the i didn't buy the next uh in the day one i can buy the next day like i can buy uh at i can buy two and i can get three zero two as sell and i can choose not to sell it in the second day or i can choose to sell it so if i sell it then i will get zero to as buy but because i can i cannot buy in the next day i have to pass two to buy or i can choose like not to sell in that case i can do 0 2 and sell again you know so this is my this will be my back tracking and i will consider all possible uh situation and get the maximum okay but here you see there is one like we are solving the same sub problem again and again like 0 to b can be also present in other case you know so we can think of dp yes dp like we can have a dp like array of like uh i to j and we can have like we have to buy do it by yourself you know and if we can store this and use it again and again does it make sense yes like uh if we use two uh arrays like uh one for selling and one for buying yeah that can also work yes that and i think that will be easier to implement yes so let's go with that uh do you want to go implement it you can try okay let's yeah so yeah you can implement it using that and let me stop the screen share and you can start this is our array one two three zero and two and uh for the i suppose i had the index of i uh so we have to give one uh one day of cool down after the selling right yeah so uh will it be like i cannot think after relation actually okay i can tell you the relation uh so let me write it in the google doc so we have like dp ah so we have two dp of cell and dpf by ah so dpf by will be like uh i'm just thinking so dp so suppose we have arrow right so we can do like uh suppose we have the first day we buy in the first day so we cannot uh sell uh in the uh yeah we can sell in the second day we cannot buy it right so if like if we buy in the i then our answer will be like uh dp of cell i plus 1 and uh if you buy in day one the answer will be dp of cell i plus one uh and if you sell in a i then we have to do dp of by i plus 2 because i have to give one day of this so dp of sale and if you buy will be the max the best uh like the best possible uh case we can get if we sell at day i and if you buy a day i like uh like dp of by is the best profit we can make if we buy at day i and dp of cell is the best profit that we can make if we sell at day i okay so if we buy a day i the answer will be uh dp of cell like we can sell actually in any day right so we can say we like it will be maximum of dp of cell i like i plus 1 and dp of cell uh i plus 2 like continue something like that okay and if you sell it day one the it will be also maximum of dp of i by i plus 2 dp of by i plus 3 and so on something like that uh what do you think this makes sense uh yes so we have this uh there's like one more way that we can try to solve it using backtracking and then we can use some kind of memory numeration uh like we can store it in custom cache after we solve it using backtracking i think that will be easier to implement yes okay so how would you implement using backtracking yeah we can solve it using backtracking then we'll understand and then we can use the dp to solve it in a better way so how to solve it using backtracking okay let me write the functions how to solve using backtracking definition that track so are you writing the solution yeah i'm just trying to like figure out so should i stop my screen share it's okay uh you don't so if i have definition of backtracking but so the backtracking how to solve it using backtracking so we can start from so we have an array and we have like okay let's pass index and if index equal to length of prices we like stopped return okay this is the base case and let's try to find the other cases so and we also have to pass like we need to buy or sell so let's pass two boolean values yes like just buy something like that so if you have this buy if is buy so we have to buy it sorry so if this buy we have to buy it so if we have to buy it so either i can buy by now or i can buy the next time next day so if i have to buy now then i will buy it so i will buy it at so i will buy it today so the price will be prices index okay or i can do a backtracking of next day which will be index plus one and is buy will be still be true and if i buy today then i have to sell the next day sell the next time so we have to pass we have to do backtracking and index plus one is by will be like this by will be false we have to sell it right and it will be this by true if you have to buy it and we also have to keep track of the profit that we are making so we have to also pass like yeah profit and when you this so we will have a self dot maximum profit which will be zero and when you reach the end we have to uh do like self max profit will be maximum of sales max profit and profit that makes sense make sense so and now when you sell then we have to get the uh price like profit so here we have to pass one more variable like the last price like if i have to sell like uh i'm like else so we have to sell right we took a return we don't have to go more so because we should avoid the else conditions as much as possible so here we have to sell so now what will be the profit will be so i can sell now or i can also sell the next day two options to options sell today or sell next day although like we can like sell next time so for the cell next time uh it's like backtracking index plus 1 and pi is false and profit will be profit is not changing so i'll just pass profit everywhere profit and profit but if i sell today i make some profit so profit will be plus equal to or the price of today like sale price will be prices and index today's like price because we are selling today so the profit will be self sell price minus like we have to pass one more variable like when i bought it what price i bought it by price so i have a buy price so sell price will be sell price minus by price and i have to backtrack and because i have selled it today i cannot sell it plus two yes and i have to pass it as true because next time i have to uh buy it and i have to pass profit and uh by price will be zero like because i'll buy the next time right so i don't have to consider my price so i prices will be zero but set but in the cell next time shouldn't it be the buy price uh which line in the line 35 in line 35 the sale next time will be uh yeah it will be yourself will buy price right yes because we are we have not been bought it yet so i have to do it the next time so we have to buy price and profit so also let's put by price in here also by price in here like okay if we buy now then the price by price will be priced right because you're buying two dates so yeah we have bought it so it will be price and sell price will be this and also you have to make one more case if index is greater than uh length okay put it in this actually oh no yeah like return so that we don't have an array out of bound induction because here we can you know whenever we're being plus two then we can reach the end like when you reach the end when you sell it uh like the last day we can again might try to buy you know like some area out of bounds so we can prevent it using index this okay uh do you think this looks okay backtracking index plus one false so let's check the flags one more time all the plugs so we have this and let's also write the driver function here to backtrack and index will be zero and i have to buy first time so it will be true yes by price will be and so by price will be price of zero one second return self dot max pocket right yeah once again line number 34 like the third argument shouldn't it be price of zero yeah by price no actually when we buy then it doesn't matter right like because suppose we are buying here is buy oh yes because it doesn't matter because we are buying that time so the previous price of buying doesn't matter but when you sell it matters the buy price so because you have to buy the first time so we can just pass zero right okay so let's try so let's go through the code one second and try to like see so if index is greater than length prices then return we don't have to do anything and if you reach the last one so just update actually we can also do it like combine this two as like this you know right now okay so like don't we have to check the is by variable like uh if we just bought one item and haven't sell it yeah right in this case the profit will be but profit will be profit right so that doesn't matter like i understand your point is like yes what if we sell or buy like does but if we do not sell one item like yeah that's okay like thus uh is by flag matter here that's a question right i think it doesn't matter because like suppose uh we have two cases right one is we have to buy it at the end or sell it but whatever the thing is the profit is already made okay and at the end we are not doing anything so we don't need to consider this flag that's what i think okay so now if is buy we have to buy it now so we have can do two thing we can buy today or we can buy the next day like the next time so if we buy today then the price will be the price of index and we have we are buying so we have to update the price by this price and profit will be profit and backtrack the next one because next day we have cancelled and we are making this flag as false because we can sell and or we can do the next time we can buy the next time so just do index plus one and true by price and profit that's it or we can sell it or if this flag is false then we need to sell it so the sale price will be prices of index so at this price we have to sell it okay we have like two options like sell today or sell next time so next time is like very simple so we just do index plus one and false and by price and profit we don't do any update here but if we sell today the profit we make will be on today's price minus buy price at which price we bought that share and we upgrade this profit and we uh reset the by price to zero and we backtrack so all so that is my solution do you think it should work okay let's run in the code okay we got this three so i think this will work but we might get time out because it's not be optimized but let's see okay so we got something wrong here so we have one two and four uh output is three okay so we are cutting output as four but we should get three what is going on here so we haven't checked a buy price yeah so by price is like not set maybe somewhere so price is the prices that index and backtracks index plus one by today or by the next time okay let's uh print something here and see what happens so we are selling here right so print so this will be else right effects yeah i think i'm doing return here so print sell price index so in case of okay let's do a dry run and see where the coat might get wrong so we have one two four can you do a dry run one two four so what will happen so i first improve true three zero so yeah we will buy it so we have zero true zero so we have uh is buy is true so we can buy today and what will we send back by taking one okay and uh okay so let's uh keep going so now we or we have this one it will be backtracking off one two one and zero by price yeah by pressing one which was zero right by price should be zero and profit is zero because you'll not have buildings yes okay now we have this so let's consider this case we have one false one and zero so now we have it goes here again and we have index no we now we have sell right we have false we have sell here so we can try to sell it today okay so sell price will be uh so index is okay sorry index equal to now 2 and we have this condition backtrack one false one zero so now index will be uh one index only one yeah it will be yeah this will be one so now we have to sell price will be two and profit will be sell price one two minus y minus one so one what will be one so now if we backtrack uh to true and profit zero properties indexes one right then we do uh back in x plus two right so one index plus two so it will be change three yeah three true zero one so when we have three then it will stop right uh and we update the max profit to uh max profit will be two one yeah so that's probably one right because we have one yes now we have the case of buy so we have bought it at so yeah so now we again have this case that we don't sell today we sell the next day so it will be backtracking of we have two right index will be two and this will be false by price will be one profit will be zero so now we come here again and now we try to solve it for two like we are selling at day two so sale price will be prices of index which will be four yes right and profit will be that's right three and backtrack will be five true zero and three so why are we getting four the question is why we are getting four okay let's open one thing we can print index uh you can just print the four variable we are setting it why profit is becoming sorry let's do one to four so in this case profit is favoring four three false one four and three true why profit is becoming 4 is the profit okay can you think of when it is written for in this code profit profits always sell price minus by price oh we are doing plus one so one time we have maybe we are getting one somewhere and one plus four three so we have three true zero and one so three is the index and zero is the buy price this one and one is the profit yes so yeah that is the first case and now we have four is the index zero is the buy price profit is four so how we are getting profit as four answers so let's just print profit and index oh i think we are setting the what profit here right yes so that's what i'm making mistake i got it so you know here we're setting this property here yes so like let's make it original profit okay like okay uh let's make a new profit the profit will be profit plus uh this right that trains silly mistake and we passed a new profit here and you pass the profit here ah yeah cool one silly mistake okay uh let's give this one to four yes so yeah so our solution is correct we just need to optimize it okay we got time limit excited so now we need to optimize it our back tracking is working fine so let's just take out the code okay so do you think we can do uh a caching here imagination memoration here is possible i think we can do it we can just like cache the answer so backtracking because this one we are doing it repeatedly so this profit we can save it in some we can have in dictionary of this element and like uh like if i have to do it like self dot cash will be this and when we get the return then we can sell cash so for this index is by price and profit you can put in cash right who can cash the result how would we cash it so because you're doing a backtracking so i don't think we can do caching because we're doing backtracking so because we don't have any track we are not getting the value from uh like there uh but maybe what we can and we have this profit which will keep changing so i think caching is not a good solution is there any way any like sub problem that we are doing solving repeatedly i think we are solving this one repeatedly right this back tracking index true false plus one yes and this so i think what we can do is if we pass the profit you know as a result then we can solve it i'm not sure like we are doing it from you know like recursively can we make it iteratively and then solve it how to cash it like what you can do is maybe not pass the price but when we buy it past the index you know when we bought it like and then that can help us to solve this thing can we make a dp from here okay so uh the answer is like we have to do something so we change it a little bit and uh instead of this buy price and profit we have to pass the sell index or like buy indifferential index find extension index okay then we can solve it so how can we do by index and cell index and solve it so what we can do is we'll discuss one method that we have solved seen in the which is similar to our solution we will discuss it and java yes so let's try to understand it first return get maximum price you can also build it okay so we got a working solution java that is almost same as what we solved but uh they used the almost the same way but they have managed to make the cache like a memo to solve this problem so let's go through the solution and because this is similar to what we make so forget this dputil we i think we don't have this one yes we only need so as you can see this code is running and this if you submit it will yeah it success so let's just discuss the solution here so we have so instead of uh the keeping track of the profit we keep track of two indexes like buy index and sell index and we have the prices which is the average that we passed and we keep it keep track of the profit between this buy index and sell index in a memo 2d array so let's see what they have done it so now we have the base case that if by index is greater than prices dot length or cell index is greater than price of dot length then we cannot do it anymore we reach the end so we return zero okay and if we already have the solution of buy and sell index then we return the buy and sell index it's memorized yeah or we compute the memo so if the price of cell index is less than the price at by index they cannot do anything we just return the uh the we that we just go to the next index because buying is not possible so we just try to buy from the next index and sell from the next net index this is the like or we can buy it we can sell it so if we can sell it we have two option either sell now or sell the next time they like that we did before so let's make a this and this so that we can understand so we have to option that we can end price like profit and profit yeah profit now will be the price of so we just sell it right today and we also now uh and from because we sell we sold at uh sold index so we can again start we have to give one day of cool down so we can do it from plus two like yes after uh one day and the cell index will be plus three because we have to buy after this index okay so profit by selling now and it will be maximum of math this or we can sell it the next day which will be plus one so this is the uh way to solve it is the same of what we did but little bit better because uh because of keeping track uh like track of the profit we just keep track of buy and sell index so that we can ah build this uh matrix in a right way but in the interview even if you can solve using this uh this backtracking you will get some points and maybe you will get the offer because no one expect you to come up with this solution by yourself and the interview will guide you to how to reach this solution but it's great that we had a good thinking process and you can solve it in this way | Best Time to Buy and Sell Stock with Cooldown | best-time-to-buy-and-sell-stock-with-cooldown | You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
* After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,2,3,0,2\]
**Output:** 3
**Explanation:** transactions = \[buy, sell, cooldown, buy, sell\]
**Example 2:**
**Input:** prices = \[1\]
**Output:** 0
**Constraints:**
* `1 <= prices.length <= 5000`
* `0 <= prices[i] <= 1000` | null | Array,Dynamic Programming | Medium | 121,122 |
234 | [MUSIC] QUESTION KEY YOU SO LET'S START IT IS PERENBUM LINK LIST OK SO WHAT DES EN MARRIAGE MINS FIRST OF WHO IF WE SEE THIS NOT IF WE CONSIDER NUMBER DATE IS ONE YOU TU ONE SO IF WE START IT FROM D STARTING In and they bill come de number it note so what they need you do they have you start reading from meaning they have you be read it from starting and you can see every it is coming out you be from it Mins aur number ok so what is it simple step method you can think of ki hum log itse kya kar sakte ki isko na hum log matla le jaayenge aur hum log kya kari compare kar denge starting yahan par aaye equal tu zero lagayenge Because if this condition of ours is not fulfilled, that is, if this condition is not fulfilled then we will be taken out of the loop and what will we do, we will get 4 sitters done, okay so this is a simple method, you can think but it is Note applicable every d region behind dead it is you can see dr what jump it you tu it in zero and time and zero of one space so this method will not reduce ours okay then it will not reduce so us zero on one space I have to think, okay, because this has become stupid and space, okay, now what can we think that suppose if I divide my number in two equal parts, this is equal parts and then suppose you check it from starting what I bill. Do per de second number means divided portion de second record both de tu number [ record both de tu number [ record both de tu number condition you can think of this is on and seeds but today you can think of number which is of meaning size so what you can think of one tu three You One Okay Suppose They Have D Number This One Too Three You One So What You Can Think About It's Simply Date You Have Too Be Divided Into Equal Parts I Bill Tell You With One More Example of No Date Number Date It's Not Feeling Well Suppose one two four three one it is n number ok so what will we do first of all just divide it from middle you can divide from each and every it total depends on you ok we can do any fashion ok we What did people do from here and check this is how much it is, one, two and four, and what did the numbers behind them do, reverse the date, this is how much will come, then we will check a question, this is from 11, okay, you and three are from. What if it is not there, it means that this number is not the first one, after that we will divide it, okay, how much will come from here, 123, what will we do with the last number, we have to reverse it, how much will come, one and you and this is three, neither three nor we. People were like, let's count from the front, let's count from the back, he will come from the same place, he is coming from the same position, that's why we consider only the people, if both of them are okay, then how much has he come from, this one is from this, he is from this one too, you are the same. If it is three then count from the front for both, when count from the back, the function can be done at both places, so it means A is for both, so what is our number, so this is the simple condition that what we have to do. What we have to do simply What is the first D Second portion Okay, we have to compare it, how to find out the middle Okay, so here you saw that our first condition is to find out, so we We will find out the middle here, so first of all, now we have this, let us make two points, I will tell you what is the need to make two points because we have to find out the number, okay, so we are making 2m, okay, so first of all. What do I do? Okay Hum log kya loco bhi hai so find out and do fast Okay, fast and next should not be null and close next's next means fast's next What is this one First one is you and fast key next connect, this one is top with mixer, these two are not taps, it means what will be slow, one less will flood next, now where will this one come, this one will come on you and where will five come next. On next pay, it means here on here, we will check again, there is a connection, no, it means that the value of our slow key has come, we have to return it, what does it mean that this is the number, no, this is the number. Let us check it and it is okay for this, our order is okay, we have made the head, after that whether the next of five is next or not, then first of all five's next means this one, you and his next's next. This one three, these two taps are there or not, what does it mean, the one who is a slow painter, will flood the slow bill, the other one will be of fast one, okay here, what will happen now is that he will check again for fast and the next tap is this? Look, five's next and its next's next, what doesn't it mean that the one who is slow will go one less further, he will go to 3 and the one who is fast will go to where three, so you can see our How much is the output? Three and we will see that it is digital and how much comes in it. What is our mid number? What did we do? Divide it by MED. After that, what did we do? The term which is the number below, we have to reverse it. Okay, so we go to our reverse one. What to do in reverse? We have given three points to me, I have started first, how much was created a point named Previous, created a painter named Current, okay, so what is the previous first and who has done the current on the current? By help on help, I mean this one which You are there right now, not only this is our reverse string, that is, these are the notes, we will look only at this one, so what is the current, we are on the head, that is, you are on and next, you can see that the next current is now. On what is the current and next, our current is on the next one, okay but what does it mean, vile current is not equal to null, what does it mean, we have to do the whole link till it is not null, it is caste, okay, then more. Most Important Think Don't Confuse Between This Next and Next These both are different and you can write different names if you want. Okay, where is the dot, see here, you can see how much is the dot. Operator A is the dot operator when it has to be there, what is the meaning of next after that, it is to tell that after this note, we have to jump to this note, okay and JB is also written simply next, what is the meaning of this name. Okay, I have understood now, what have you done after that, how much has this one become? These three conditions of ours will come under our first. Okay, what is written after that, , equal, you, previous, tell who that one is? Note, what will it indicate? Okay, the net of the current has to be indicated. Here, what is the previous to the previous? We have a null, so what does it mean, now how much will our current become, then how much is the current? After that, what is the previous equal to current? What will be the previous bill's hole position of the current, how much was the current, what will be the hole in the previous, what will be your position, date is here, this will be our current, our tap is done, what is the meaning of this which is closed of ours, it will break here. You are fine, the current is pointing out the tap, as you can see the current is pointing out the tap and the previous one is no holding position of this, you are fine, it is simply empty, poor guy, now this Who is this previous bill hall disposing of? If the previous bill hall disposition is ok, then what is the current in it? What is the current here? Who is the current halling now? Next is the next one, what was our one, what will happen in it now? Our current bill host D Next date this one current is halling whom one is ok so inside the current inside the previous you went to A and inside the connect one A went when as soon as this happened then it became till a back point. Because of these means this one, in the first starting, this blink dr was closed, what will happen after that is that our as soon as this is current equal you next, this one is this point, whatever happened, it started indicating this and this is our node. It has become simply one is indicating you are simply what will we get done written previous second previous means they have you be indicating also means this whole note of ours will become a, it is representing, okay, what did we do, we got our note reversed. This one and you are gone, okay now in the last what we have to do is 1 and 2 of the starting and one behind and you, what was our number, this is our number, so what is ours and this one behind, if we reverse it, then how much is it? 12 These two are equal, what does this mean So I have already simplified all this, look at the name, what should we do in this, we will check, okay, first of all the condition is fine, which will be our tap painter, meaning our If you do n't have any note then will you get return 2 done? If there is zero number then you will get return done. If there is no number then you will get return done. Middle is equal to first middle head. Now what we have to do is find out which one is in the middle or not. What we are doing is to do the evening point, which was the first half, so that if we divide the last number, which is the starting point, then what will we do, which is the starting point of the next number, like If this is the number, then we will know that you are the next one, what will happen to us, which is the second portion, which will be its starting point, how far will we write, the second half will be the starting point of the second half, that is the middle of it, which I told you right now. Found his just next one, this is what I told you that his just next one will be, what is there after that, the list note that starts the first half is the head, any note starts with what, headset is ok, what do we do now? What we have to do is to check which is the first part of the second half. Unless it is being taped, what does it mean that we have not played the entire string, we have played our entire note, it is from here, this one is not the same, but we People, this portion is to be completed from start to lake entry. Okay, what to do after that to check that if your value is before our start, if the value of the first start of second half is not there, then we will get our returns burnt. Meaning. First of all, this one has its value and its value, if it is not from both the keys, the value of the start of the first half, second half its value, if it has not come from both, then what will we get done, if we return it, then the next step is now you will see the next position. Let us tell you in the big jam, see what is said here, we will move forward here on the first starting basis If this flower condition is achieved, then what will we get done in the end, it will be written true and our program will be successful, okay you People must be understanding it, okay, so see, we are running 'Accept' and after running 'Accept' and after running 'Accept' and after submitting it, let's see the complete convenience. Okay, so see, you can see here, I told you separately, first of all the reverse. tell it in big | 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 |
216 | Jhal Hello Hi Guys Welcome to Cold Weather Today is Question is Combination No. 3 in this question be up to find all the possible combination of number dep guddu and number and given to 19 number from one to 9 can be used and its unique number boys And Give The Number 2 And Subscribe Combination Video give Number Distance From 12951 Combination 1253 For To-Do List From This 12951 Combination 1253 For To-Do List From This 12951 Combination 1253 For To-Do List From This That Now Hindi Souls Will Have To Take Only Three Number Combination To Generate Is Impossible Nahi Soe The Combination Veerya The Commission Will Find r12 65 2340 Combination of Three Does It Is Equal to the Guide subscribe and subscribe the Channel Number One Two Three Two Elements Combination To-Do List Combination To-Do List Combination To-Do List A Vision for All This Subset Offers Numbers But on One Two Three End In which subjects will find that subject which achieve this and 10 20 condition vacancy in this app has only been subjected to three liquid liner is condition in this is only and such Samadhi element of these types 500 to three is the answer subscribe Video subscribe How to take atul wali committee offer answer birthday idea is to generate submit listen let's look at the driver of this code no left-front taken left-front taken left-front taken 9th article 356 simplicity purpose and goals to point two elements high music 125 29 this question is backtracking type so let's C What is the Main Function of World 2151 Study Into Consideration Elections 2019 Absolutely Against Two Elements To 9 4 2nd T20 World Cup 2012 Elements Of Elements December 19 2012 That I Absolutely To So In This Case Will Not Make A Call For Forward College Will Make A Call Forward Is Finance Minus One Day It Will Consider These Three Elements Good 2012 Elements That Will Not Make A Call Forward Will Just Simply Is Vitamin A Call From Near 90 Coolness Want To Know It Will Call To Dysfunction 9 0 4 And Elements 30 And Came One And K In 2009 That Similarly In This Condition Also Most Mega Call Forward In Last Week Ka Call Forward Earth And One Element Will Also Increase Not Only Earthquake Will Be Equal To Minus One Which They Have Taken Into Consideration The Elements But Were Wrong As Well I Will Return The Call From Her Only Been Cases And The Answer Is Not Found No One Will Go Back To This Will Make A Call To A Friend Spider-Man NDA 350 Elements A Friend Spider-Man NDA 350 Elements A Friend Spider-Man NDA 350 Elements And Give Vikas Vyas Taken Into Consideration Noble Call Forward 99 Hair And 10 And K Vacancy Means Switch Powder Combination In Which Year And Also Like World Tourism Day Required And A Number Of Elements Of All Should You Record Only Like Five System * Uniform Elements Which Are Like Five System * Uniform Elements Which Are Like Five System * Uniform Elements Which Are Foot By 20 Combination Will Take This Comes Into Account And After 10 Years Soft Science To Make A Call Forward Because RN Vikram Negative And K Vikram And Sune Tips Will Return From Hair Election Bansi Lal Written Test Will Return This Adhikat 232 That Nau And Spine And They Can Do And Quiet's Vikram One Election Absolutely Head But Did Nothing So It Will Return And Nowhere Recorded Decided And Witnesses And DR All The Answer To Return To The Email Serval Combination Vighn 1947 To Three Will Be I Ho To Please Like You Will Not First Thursday K Dushman Solar Panel Answer Will Return This Answer And Nor Will Make Butter Debit Or Current Combination Williams Current That Bismil Saurabh Current Commission And Will See Weather This Current Commission For Being Given Condition For Not Knowing What Will Do What Will Caller Equations Recursive Function In Which Will Pass Answer All Current Track That Art Architecture And Enters Size Duration Target Required Its End Share And Starting Audition Date Of Birth Jeevan The Number 212 Not Starting Number One After This Application Has Been Called Will Return Divya Answer Function The Answer Is Gold Channel Subscribe Combination subscribe Video like and subscribe the Channel and 10 and 1000 combination looking for some will and discrimination in no final answer is back a are current events which contain the current combination no will return from her big boss big guide will be developed within Go for them and will be amazed and the will also be the native and as well as know you certificate condition second day box one hour of 10 limit of elements in two front 98100 something about it and will agree with you ka note Mahila K Vikram this condition Want To Know And Between m0vie Can Not Take Any Element Here Element In Consideration For Rate And Wars Still Have Any Value In And So In This Case Better Returns From Here Only Be Kanpur Down Words Om Nandishwar Best Condition No Valid Lighter Loop Point High Court to know the subscribe 9 plus the first will happen it into your current vector will consider this element also on a back I know at all Nakul per reaction function only Krishna can only happen in the sporting answer or current that and - sporting answer or current that and - sporting answer or current that and - I because now at suppose Strategic 121 Subah At Least One Into Account Swar To Sudhar New Answer Which Will You End When Required In Further Iterations Will Be For Note 500 Notes Printed And Elements Class Voucher Decree By One And All Meditation Will Be Called From I Plus One By Itself But I Don't Initially 151 125 Not To Find Information For One Beat 12345 Dowry Into Consideration And Take Vansh Again Into Consideration Thee And Suno Vinati Shri Krishna Functions Over BF Got All The Combination Richa Starting From 20th Starting From Chief We Are Not Refrain From Next Number 12192 Subscribe 159 Are One Hai Ke Raaste Seervi A Pooch Yovan In From Shri Krishna Call Back Find All The Congress Meter Cutting From Nowhere Pop Back 118 Mode On 419 Oil Boil Smoke Plus 9 Portions Of Welcome To Back Starting From Evil Bake Its Evil Returns Off The Day the President Accepted Only Custom Taste's Stall at Summit the Presiding Accepted I Hope You Liked Video Thank You Too | 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 |
68 | hello everyone welcome back here is my name and today we are tackling the infamous text justification problem number 68 uh on uh little daily challenge so it's a fantastic challenge especially for interview so first thing first understanding the problem we are essentially building a mini justify feature for a word processor and given a list of words and a Max white we need to format this words so that they are Justified on both left and right so there are some nuances but that's the gift so let's have a look at example two clarify so with the word this is an example and Max white of 16 our output should be like this so maybe a visual representation is easier so it's Justified text so notice the varying spaces and between the words so that's the magic we are about to implement so let's start coding and we will employ a greedy strategy trying to fit as many words on a line as possible then we will distribute spaces using modular arithmet so it's simpler than in sounds so I promise the core idea is to pack as many words in a line as we can and without exceeding the max white and once we have got our line we will distribute spaces between the words and if spaces I don't divide evenly among the words we use modulo to add more spaces to the leftmost gaps and for the final line we simply left align text so I have let's implement it and then I will dive deep into the code so resolved blind white will be all right and zero and four W in words if white plus Len W landline greater than Max White for I in range Max y minus White line I modulo Len of line minus one or just one and plus space and result line white will be result Plus join the line also all right and zero and line will be plus W and Y will be plus length of w and finally return result Plus join line join the line L dust the max white so okay let's run it to verify uh it's working so yeah o is working so as we can see and what we did so now diving deeper the logic so we start by initializing three main variables so rest so this will store the final result containing justification line and line is a temporary list to hold the words for the current line and white this gives track of the total character length of the words added to line and then the main logic of our solution begin as we look through each word through its word in our worth list so for each word uh w we check if adding it to the current line along with spaces I would exit the max wide so the expression white plus Len plus land line so this one gives the total white of the line if we were to add the current word and here land line provides the minimum number of spaces required since there is at least one space between each word and if adding the words would exceed this white it's time to justify the current line so the inner loop distribute spaces among the words in line so the modulo arithmetic ensure Extra Spaces are added to the leftmost gaps between Wars so it's a clever trick to guarantee even a distribution and the expression I modulo landline minus 1 over 1 so this one helps decide where to place the extra space and after justifying the line we append it to our results so simple and rest line and white to the next set of words so then we add words to the line so if there is still a room on the current line for the word we add it to line and update the white and once we have processed all words there is likely a partial line left so this represents the final line of the text which gets left justifies so we use a python L just method to ensure it takes up the full Maxwell right padding it with spaces on the right if necessary so and there we have it this solution is quite efficient for packing the works into a line and justifies the text using the bondulo operation so the modular helps us decide where to place the extra space ensuring a balanced look so now let's submit it for unsynthesis cases to verify it's working so yes it's working and as you see it's bit 83 with respect to random so I have run it previously so it was even 94 percent but yeah maybe it's a different test cases or something so basically it's quite efficient and also uh code is short and elegant and the beauty of this approach lies in its simplicity so we are using python list and string module operation uh and that's a heavy lifting of the space distribution uh so all right that's a wrap up of our live coding session I hope you found it enlightening and if you like uh seeing implementation in other programming languages check the description below and as always hit the like button share and subscribe for more coding Adventure tutorials and much more always practicing happy coding and see you next time | Text Justification | text-justification | Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth` | null | Array,String,Simulation | Hard | 1714,2260 |
342 | so for today's question that is power of 4 we have been given an integer n that should return true if it is a power of 4 otherwise it should return false so basically uh n is the power of 4 that means uh for integer x such that n is equals to 4 part x like it should be a power of 4 so 4 16 into 4 something like that it should go like that so if we are getting uh putting n equals to 16 then it should return true because that's a power of 4 if it's a 5 it should written false if it's a 1 it should return true because uh 0 if our value of x equals to 0 it should it would return 1 so that's why it should be true okay so this is uh my solution so what i have done is taken integer r that is equal to zero that is remainder and while n is greater than one and r is equals to zero so uh that time this while loop will uh keep on executing so what we are doing is r is remainder so n modulo four so that will return the remainder that should return 4 uh sorry 0 if that is divisible by 4 n is divisible by 4 then what we are doing we are dividing the value of n so let's say for 16 4 divided by 16 divided by 4 it should return 4 okay so this step is just output so uh yeah so after this n goes to four will get four uh so the value of n is greater than uh one and r is equal to zero then we will continue again so here uh four modulo 4 that should return 0 and uh 4 divided by 4 that should return 1 so now the value is not greater than 1 so that's why we will continue so we'll check what is the value of r after this so our value is 0 and n is greater than 0 so we will return true for that condition else we will return false so that is the solution that i used so this was based on just basic mathematics so the other solution we have is using recursion so here what we are doing uh we have taken and we have taken three conditions okay so these three conditions are terminating conditions for uh the recursive recursion so uh if n equals to 0 will return false if n equals to 1 will return true if n modulo 4 that is any like when we divide a remainder for if we end up if n is divided by 4 the remainder should uh if the remainder is not equal to 0 then we'll return false okay else we will uh if i if either of these conditions are not there then we will uh written the power of n by four that means we are just dividing the value of n so let's say example of here we started with 16 then uh since n is not equal to zero one and modulo uh four is uh equal to zero so not this condition as well so then we will go here and we will again uh like 16 uh divided by 4 that means 4 this is power of 4 is then again called with value of 4 so then it will again come here uh again it is not uh then four divided by four now the value will be one so n equals to one that means it should right until so any other cases it should return false okay so that is one solution as well so that is uh all for today's problem on the lead code that was uh the power of four okay thank you for having have a nice day | 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,641 | Hello hello guys welcome back today we are going to solve dynamic programming account south wales prince problem statement that you have been in India, the length of the screen and kept you tied is in English subscribe which is made by us should be the previous one. Subscribe one two three 500 appointed subscribe now school so you have two positions here so if the table here at this position on the number is from me or can come, can he can like that means can become five Here's how much do you want from me because you will take then here quickly so this position then subscribe for that then good if you want if here this then here we can do a way because you can see Here you can see that if we subscribe then for this let's go to subscribe husband. First of all we will create a function solve in which we will add water and any character just which is not a pill. I have run a software. Friends, define garlic. The back is that our name is last. Okay, our name is last. If then our name is last. If you have got your answer, then we will turn on was written and we will check whether our which is the value of last. Is this or the value of the last, come to our praiseworthy last, if I am subscribing, then I subscribe, what do I do here - 121 Jai Hanuman, good feelings, good wishes, inch plus, I copy this to watch it five times. If I copy and paste it, I'm looking for A+ Okay, it's done, here's A+ Okay, it's done, here's A+ Okay, it's done, here's what's going to happen here, so here I what's going to happen here's what's going to happen here, so here I can keep you 15 subscribed, if my subscribed, I can say that subscribe to that you I will also have 304 34, I can take one and here's this and here's the value of my last key. If I don't have it then how will I use the camera that came to me, if it's done then we'll put it here. Hain Na Tere Ko A Transitional Period You To That Or Let's Check If I Have CR From Here If I Have Last Ki Value What Is My I Know That I Have You To Me Come This So 34 systems that I can keep one more I can keep my darling away that baby If it's my last wedding Drink be the phone If this is what I need I only have one more that I can keep just like that So it is new and then what will I do, I will open my number of passengers, here I will keep the answer, you, let's look at it, let's look at the front and see that it is telling where it is, here we forgot to put plus, let's go. If we try to solve the tree then the correct answer is ok, it will go at the time of submission but we will return it to us Simar, the time complexity will be reduced once, to forgive you, let's go and get an astrologer, the affair happened till the minute, okay. And here there are ints which will tow their values that are ints which will tow their values that are ints which will tow their values that how much has been calculated, we earn DP and simply we are here 1431, this is mine, I have already calculated on this name and what it is saying, if calculate If I do then I will simply get it done till now, this is not my only work, I have the last one here, I will get it done, if it is not so then what will I do, I will store it in my index which was last, I will submit it and let's see. Joint Secretary of IS submits this Cost of this organization Thank you for watching my video | Count Sorted Vowel Strings | countries-you-can-safely-invest-in | Given an integer `n`, return _the number of strings of length_ `n` _that consist only of vowels (_`a`_,_ `e`_,_ `i`_,_ `o`_,_ `u`_) and are **lexicographically sorted**._
A string `s` is **lexicographically sorted** if for all valid `i`, `s[i]` is the same as or comes before `s[i+1]` in the alphabet.
**Example 1:**
**Input:** n = 1
**Output:** 5
**Explanation:** The 5 sorted strings that consist of vowels only are `[ "a ", "e ", "i ", "o ", "u "].`
**Example 2:**
**Input:** n = 2
**Output:** 15
**Explanation:** The 15 sorted strings that consist of vowels only are
\[ "aa ", "ae ", "ai ", "ao ", "au ", "ee ", "ei ", "eo ", "eu ", "ii ", "io ", "iu ", "oo ", "ou ", "uu "\].
Note that "ea " is not a valid string since 'e' comes after 'a' in the alphabet.
**Example 3:**
**Input:** n = 33
**Output:** 66045
**Constraints:**
* `1 <= n <= 50` | null | Database | Medium | 615 |
835 | uh hey everybody this is larry this is me doing uh day six of the september lego daily challenge on september uh hit the like button the subscribe button i'm gonna do this live so join me on discord in image overlap i think i did this on a contest or something like that i think the big thing to notice is that n is equal to dirty so that means that is any rotation just up down that right okay so you can do uh proof first i think and just slide uh yeah can i move both left right how do we choose okay but yeah but i think it's just doing that and then uh returning it uh just put force calculate going left end times going right end times going up and times going down end times and depending on the definition of whether we can go up or left or sorry uh like combine two directions going diagonal um then we might have to do some checks but um and so key thing to note is that moving a uh you know down is equal to moving b up so you only have to check moving one of these uh yeah so let's get started uh with our ordered links the same so n is gonna let's just do this then and then now we just have to do four um uh zero negative one zero one so that we get all the com uh possibilities of all the directions up down left right uh we have to do more than what to do more but yeah and then for n oops for shift say in range sub n because if you move more than n then your not you know two things will be completely overlapped so or not overlap at all so then you don't need to do that and then now we just set count 0 for x in range and for y and range n if okay so overlap is the both ones so if a sub x sub y is equal to one and b sub x i guess we have to do some down checking first if x plus d x times shift is equal to less than n and the same for the dy then oh i guess we should do it put in a variable okay fine and then now we just have to check whether that's also a one p of n x and y is equal to one then we just increment count and then now we take the best of you know pass and then the max of count i think that should be it if we have to go only in one direction uh but let's kind of give it a look okay i wonder yep oh no oh i guess we should have just read the explanation for the first one that's okay so now we have to add in another direction then so let's just call this shift x and then for shift y and range sub n this is shift x and this is shift y but of course now we need think about this for a second um this is a little bit awkward the way that i did it but um because now yeah maybe that's okay oh yeah actually then this is just um shivered shift y we don't need the dxty anymore okay i think i changed some stuff and then i forgot um the only thing that we have to actually maybe we do we yeah because we want to make sure that um we go for all the directions so yeah let's try again i was going to put into a test case to just test the diagonals for clear i don't need this uh okay so we're running into some technical difficulties but okay we messed that up no that looks okay so basically first we go uh left right yeah should be roughly right unless i'm off by one somewhere which is possible oh uh this should be here okay i guess i shifted the things but then in dentist okay cool uh yeah let's submit it because i'm relatively okay with this one it may time out i think that's the only case but okay so if it doesn't time out then that's fine um so how fast is this right well n to the fourth times some of one so and yeah end to the fourth uh time uh over one space so that was pretty good but given that n is equal to dirty i wouldn't think that much about it um yeah uh that's all i have for this farm uh seems like a straightforward problem i'm gonna take a quick look at the solution maybe there's a better solution but given that n is dirty i don't think i just expected to but let me see if i missed something obvious and then we're gonna we could go over it together uh in that case um now okay shifting count linear transformation i mean okay yeah that's just still into the fourth okay yes we can do convolution but that's ridiculous okay so a lot of these are still into the fourth i don't know if there's a easier solution so yeah um or not easier just quicker solution cool uh yeah let me know what you think about this farm hit the like hit one hit the subscriber and join me on discord and i will see you tomorrow for the next one bye-bye | Image Overlap | linked-list-components | You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values.
We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the **overlap** by counting the number of positions that have a `1` in **both** images.
Note also that a translation does **not** include any kind of rotation. Any `1` bits that are translated outside of the matrix borders are erased.
Return _the largest possible overlap_.
**Example 1:**
**Input:** img1 = \[\[1,1,0\],\[0,1,0\],\[0,1,0\]\], img2 = \[\[0,0,0\],\[0,1,1\],\[0,0,1\]\]
**Output:** 3
**Explanation:** We translate img1 to right by 1 unit and down by 1 unit.
The number of positions that have a 1 in both images is 3 (shown in red).
**Example 2:**
**Input:** img1 = \[\[1\]\], img2 = \[\[1\]\]
**Output:** 1
**Example 3:**
**Input:** img1 = \[\[0\]\], img2 = \[\[0\]\]
**Output:** 0
**Constraints:**
* `n == img1.length == img1[i].length`
* `n == img2.length == img2[i].length`
* `1 <= n <= 30`
* `img1[i][j]` is either `0` or `1`.
* `img2[i][j]` is either `0` or `1`. | null | Hash Table,Linked List | Medium | 2299 |
1,844 | Hello hello one to baat hai gopal number 84 ki replace all widgets end with characters to pun interesting like this loud english letter this end subscribe and subscribe - 40000 example2 subscribe - 40000 example2 subscribe - 40000 example2 and this so like this is my second this that this is my It is an English letter and I got the rotation here from Digit as if I talk to the media otherwise now as if I will have to subscribe to the first and second aspect, I will shift it to one space, if I do my ghagra then subscribe to this and after that I will subscribe to this. If I shift in two utensils, then here I will give this, in the same way, after which scene, what is mine, after C, it is mine, okay, then as soon as possible, I will shift someone in three times, okay, if I do three children, then this goes Okay, then I will tell you this place of support, similarly, when should I talk about a date at home, then it is a matter of discussion, look at my photo, I will start Asif, then if it is okay, I will do four shifts, then if my mother wants this, then this ghee, then I will now get this wet fragrance. According to the digits in Ghr, I am like a young man running away, start the setting, first of all, I run the types, last lo, then come Lansdowne s.no, types, last lo, then come Lansdowne s.no, types, last lo, then come Lansdowne s.no, I am the length of I Plus serial, the extra given in it, this is our string, its hearty. What do I do? If people go into this then I will pick each character. Okay, so after picking each actor, what will I do? So to pick each character, I select care sequence to 880 mine. It will suit every actor, care sequence to 880 mine. It will suit every actor, care sequence to 880 mine. It will suit every actor, okay then what do I do? Then I check whether that character is our letter i.e. it is our letter i.e. it is our letter i.e. it is our English alphabet or it is our digit and there is one more thing in it that it will be found in whatever character. All that is not in our list that and she is the direct request to the person Udayveer that anything can happen in the same way if we subscribe that StringBuilder Facebook object New Stress Builder Right now what I do is that this is what I have taken Whoever subscribes to this channel, ghee in English-Vinglish is like if I ghee in English-Vinglish is like if I set the ghee in Maa Ghee with character and digit pin. If it does not work, how did I take quantum herbal and then I will make it in 1 minute. You will have to feel the convert salt now. What will this converter do? Basically, whatever our digit is, we will take that digit, now we have subscribed and subscribed, so now here I subscribed that war subscribe button more this which this alarm set this raised and after that this one which is one month What will Ego do to these two? If he sacrifices one of the subscribe, then he wants, so now that convert string, so what we do is like subscribe to the youth, like, subscribe, then set that twice, Quantico 297 plus two. So mine comes 98 99 Raghava Digital Then we do this our this so we print this song again Which ko Tyag I have printed CO And finally what will I do So finally here which is mine That ends here At night, I will get the pattern done here by converting it into a peer vestige and said, son, that's why there are two strings, now what do I do, this is our function, now I will have to create a function, I created this convert function on the public, convert then I Appointed here and should convert into the house this is our I this I am pregnant he subscribe here which does the hair character and then there is an interior flavor his body this is mine its flame take it is okay now what am I What I do is, when I got a character and I liked it, then what should I do, like I got this, okay, I also added the character which is my character, Monday Digit, this is the question, the email has been described here and then this one which is in this Youth i.e. this one which is the first one which is the i.e. this one which is the first one which is the i.e. this one which is the first one which is the character and once we do the interior of it, how many liters of 1978 Edison will be filling the return that our one can edit and our one gas key will come first, then what will we do that the gardener will change. So this is our exciting herbal edifice, now we are this young man 181, so first of all we convert our character - first of all we convert our character - what will happen from 202, which is our forest, this is the character in the character, convert it into interior. If it happens, what will you do, then 1968, which was converted into war, then you can subscribe here for that number 9828, like, comment, if it happens, subscribe a movie returns. Home text is given here in this place then we also appointed final what do we do which will become ours then we convert it into strong building is getting damaged access submit that Taimur submit Done Runtime Roots Second Step Dahej Central Go Online Submission for This Question on | Replace All Digits with Characters | maximum-number-of-balls-in-a-box | You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices.
There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`.
* For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`.
For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`.
Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`.
**Example 1:**
**Input:** s = "a1c1e1 "
**Output:** "abcdef "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('c',1) = 'd'
- s\[5\] -> shift('e',1) = 'f'
**Example 2:**
**Input:** s = "a1b2c3d4e "
**Output:** "abbdcfdhe "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('b',2) = 'd'
- s\[5\] -> shift('c',3) = 'f'
- s\[7\] -> shift('d',4) = 'h'
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists only of lowercase English letters and digits.
* `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`. | Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number | Hash Table,Math,Counting | Easy | null |
600 | hey what's up guys this is chung here so this time uh today's daily challenge problem right number 600 non-negative integers without 600 non-negative integers without 600 non-negative integers without consecutive ones uh so this one is pretty tricky one and okay so the description is very short so you're given like positive integers right and return the number of integers in the range from zero to n whose binary representations do not contain consecutive ones right so for example we have n is equal to five which means we need we are we're searching from n to five right and then we have six numbers in total right the binary representation is as far a as follows as this and the three is not a valid one because we have two consecutive we have some consecutive ones right that's why the answer is 5. and then example 2 this one is pretty basic right 0 and 1 right so we have 2. so here we have 0 1 and one zero right that's from zero to two that's why we have three here okay so the constraint is ten to the power of nine right so it's pretty big you know the first brutal force way is simply we simply just loop through everything from zero to n right and for each of the number we uh we check the bits one by one right and we see if there's any consecutive ones if there is then we just simply skip that all right obviously the time complexity is going to be at n times what times 32 right because i think 10 to the power of 9 is a range of 2 to the power of 32 right that's why this would definitely our e and a better one a little bit better one which but we'll still tl is that you know we have a bunch of like bits value right so we check the current value if it's zero or one if it is zero it means that you know the next one can be either zero or one right or the current one is one then the next one has to be zero right so that's the second solution but this one as you guys can see even though we have we could have either zero uh one branch or two branch but the time complexity is still going to be the 2 to the power of length of the beat string which is 32 right so this will still tle basically this one so this one what it improved was that you know we're not basically we're not searching for all the numbers we're only searching for the numbers that's doesn't have a consecutive ones right but still this one will also tle um so which means we need a better solution right even better even faster one um so to do that you know we have to make some observations here you know let's say we have one zero one right you know remember we're searching the uh okay so we have a one zero one right then right so remember we're searching for anything that's smaller than n right so let's say we have the so the first one is one right so which means that any number that's within the range uh from zero if we fix the first number to be zero right anything after this right so anything starts with zero but ending could be anything right basically this is uh something that would definitely fall in falls into the range of this end right if we have if we know like in this range in the six bit range how many uh how many like numbers doesn't have a consecutive ones that can greatly improve our performance right so let's try to solve the sub problem first and then we'll come back here okay so now the sub problem is that you know given like a bit right given a length okay length of beat right how many numbers does not have one once right i'll just use the one once for short right so in order to solve this sub problems you know we need to look at this one here okay again right so let's say now with sub problems that are given like 6 bit value right we want to know how many right how many numbers right with the size with the length of six digits six bits right who doesn't have the consecutive ones right so now we can i think we can go back to the second approach you know because this one okay obviously you know the first one can be either zero or one right so let's say if the first one is zero okay so the first scenario is that you know the first one oh sorry the first one we put is zero the second scenario is that we put the second one we put the first one to one right so this is the two scenarios we can use to solve this one recursively okay so if we oh we have a dp right so let's define dpi here right i is the basically this is the dpi right of beta the length is i here right so that's the definition of the dp here um so we have two branches right basically we can either put this one current one to zero or one so if we put the left most significant the most significant okay so the most significant bit to zero then it means that you know the next one can either be zero or one right because you know zero it doesn't have any consecutive one is fine so what does this mean this so what's this is like it means that you know the next this one can be anything right so this is what this is dp i minus 1 right because you know if we fix zero then the next one can be either zero or one basically anything after this one can be which means it's basically it's a sub problem of dpi minus one but if this one is one it means that the next one has to be zero right and after zero right then the sub problem is what so this one can be anything again right here's like this so now we have two fixed bits the remaining is what i minus two right so that's how we uh can calculate the uh the dpi here right basically this one is going to be what dp of i minus 1 plus dp of i minor i minus 2 right so that's going to be the state transition function and this one is what actually is a fibonacci number right but the difference is that you know the value of dp0 is instead of zero it's gonna be one and dp of one is gonna be instead of one is gonna be two right so the base case is what so the base case is like this uh we already talked about we already saw the example dp1 is what dp1 is equals to two right because dp1 is with one digit we have what we have either zero or one that's why the answer is two right and we need for the fibonacci since we have i minus two we need another like we need another uh base case which is dp0 0 is going to be 1. and what and why is that because for dp3 right dp3 goes to dp uh two plus sorry not for dp3 so dp2 here db2 equals to dp uh 1 minus dp0 plus dp0 okay so dp2 we already saw the example dp2 the answer should be three right because for dp2 we have zero one and one zero right that's why we have dp3 and for dp one is two and then the leaf dp is zero to one so we have to set cp0 to one actually dp zero to one this doesn't make any sense right we simply use this one to make sure we can get a 3 for dp2 right or you can just simply set dp to e equals to 3. you don't have to worry about this dp0 right uh cool i think that's the first sub problem i think this dp0 might also be useful uh let me think yeah i think this one also make also going to be useful but i will we'll take a look at it later but anyway so that's how we calculate the dp basically given like a length of a bit string we can use this one to calculate the uh the total number within who has the same who has this bit value who has this bit length that who doesn't have a consecutive ones right okay cool so with that you know let's go back to the original problems one zero one right so now uh so first we see this number one here right and then we have this what we fix zero so which means that anything that's after zero can be calculated right so which means that you know so now if we fix zero so what range we're currently recovering this ring zero two zero one right so what's this value this is a dp of six right because we have this six that's the range we're covering right um okay so that's that and but if it's zero right oh sorry so we covered that right so we covered the uh we covered the dp6 uh with this one but how about one case right so for one zero two one right so this is something we cannot cover basically we cannot use dp dp7 to cover to do to cover this one case right because you know this will also include some values numbers who is greater than this than the original n right that's why we can only uh use this dp when the current one is when the current bit value is one then how about okay so how about the uh did how about this range the range of what the range of this one which is going to be the one to this uh zero one right so we already covered this scenario at this uh range then how about this range right how can we calculate this range so what we can do is we simply just keep moving the bit value to the right side until we see another one okay so let's see this is one right so now let's keep going uh go let's go to the next bit is zero means we cannot do anything okay and then the next one is also zero we simply skip that we don't accumulate right because we shouldn't uh because this dp will include both zero and one right because that's for everything now the next one is one right then we can just use dp again why is that because now with one we can use the similar logic here right now we have this one so the range we have is one zero right to what to one zero one so this is the zero we fixed right and this is zero bit value we fixed okay so this is the second range this is what dp of what half seven i'm sorry dpl dp of three right second one because now we see another one here that's why we can uh use a similar strategy as for the first one right basically we're going to fix this one two to zero and then once we fix this one to zero then the rest can be anything right that's why we have dp3 here okay and then the last one is and then we just keep going to zero and then until we reach here it's going to be a zero so now gonna be a one zero right to this one zero one so this is gonna be the last range gonna be dp of what right uh yeah i think that's it right so now as you guys can see if we just uh follow this strategy we can cover uh all the out of the ranges right because here you know we're covering the range from the zero to this one and also curving from this one to here right now we're splitting the this big problem into a few sub problems which is dbf6 plus dp3 plus dp1 right so that's the first scenario and how about second one we have a second scenario which is the you know currently this one doesn't the original number itself doesn't include any of the uh the consecutive one that's why we can just keep going until we reach the end right what if this one has an has let's say for example if this one has a one then what will what would be a different this one right so now i think the only difference is that you know so here stays the same this one stays the same and now for the first for the third one now instead of this one we're gonna so the one we are covering the range we're covering is going to be this right 0 to the 0 1 right so this is going to be the thing we're covering here because this is going to be the ones where we're fixing right that's why we have two here right so that's that and now you know can we continue no and why is that because you know so this is the last number we're covering here right and as you guys can see any number that is a greater than this current number will result in will result to a consecutive one because you know this one is have one you know any number if we add one doesn't really matter how many numbers we added here if we add one we'll have like what we'll have like one zero right which we have consecutive two uh consecutive ones if we add two we have like this one it's also basically this is the last number that will not have a consecutive ones any number that greater than this then the last number here will result to a consecutive one that's why you know if the current number if the limit this range here has a consecutive one and this is where we should stop we should not continue right cool uh i think that's the basic idea here let's go back to the original problem here i think we can try to implement this problem right so actually the implementation is pretty short but the idea behind it is pretty mind-boggling right so like i pretty mind-boggling right so like i pretty mind-boggling right so like i said we need like this kind of fibonacci like dp structure first to help us to pre-calculate the number of the values to count often the valid numbers within the who has the same certain like length of the bits right now let's do a dp of um times 20 32 because that's the biggest number we're dealing with right so like i said the dp 0 equals to 1 right and dp 1 equals to 2. i think db0 equals to 1 this also has a meaning of it but it's not that obvious right so for i in range of 2.32 in range of 2.32 in range of 2.32 here we have dp of what i plus equals to dp of i minus 1 plus dp of i minus 2. right we have already talked about this how why this one is one or two right and then the next one is that we have to check right we have to check the most significant bit first right uh let's do a defined k equals 30 31 right and then we need a pre equals zero because the answer is equal to zero and the answer is equal to zero okay so this pre so the pres use to check if we have if we need to stop right in case we in case the original n has a like two consecutive numbers right something like this right so basically we need to maintain like a pre but pre-like digits right like a pre but pre-like digits right like a pre but pre-like digits right in case we have two consecutive one that's when we need to stop right so basically we have y of k is greater equal to than zero okay i'll explain why we need that equal to zero here if so basically we check if the current digits is like it's one right of this k and then it does not equal to zero right it means it is one then we do answer dot uh plot dp of k right so why we have k and dpk here right again right so let's say we have 1 0 1 right so we're checking this bit right so what is the bit here so we have k is what is five right so if we do a one left most five we have what we have one zero right that's how we set d set this one and the five is what the five is actually exactly the count of the remaining digits right the remaining bits except for the current one which is exactly five that's why we use dpk to represent this one okay and then right like i said right okay and then else right else uh we simply just do nothing right and then we do a k minus one and then we return the answer something we return the x right but here like i said we also need to take care of this consecutive one case which means that you know if the pre is oh it's equal also equal to one that's when we'll simply return the answer okay and then we set the pre equals to one here and then the pre will be zero right because that's the simple that's the s to update the previous value okay and then so the first thing is that why we do a k equals to zero here how about if we do a k greater than zero if we don't consider that so what's going to happen right so what will happen is that you know for the very basic case let's see if the n is equal to 5 which is one zero one right uh if it's one zero one so it will be what it will be first it's going to be a zero uh zero to zero one right which is a dp of three right dp of three and then if we stop at k is equal to one instead of zero that means that we would there's no way we can check the last bit right basically the k equals to zero is to check the last bit if the last bit is one we also need to cover that we also need to consider that because you know if the last bit is one it means that we have one zero needs to cover right that's why we need to do a equal to zero okay and then the last one is that when we return we need to return the answer plus one so this one is to include and itself right because everything we have been doing this while loop here is we're only considering the what we only can we're only uh including we're only considering the anything that's smaller than n right we're not uh checking the number and itself right because you know for again for one zero one right so the first range we're covering is what we're covering is this from zero one zero two zero one right and what under the second the last uh range where curving is what is from one zero to one zero it's not to one zero one so i know this part is a little bit tricky i think it's tricky here it's not one uh one zero one because we're fixing this one to be zero and then there's nothing else here right because you know if we have a uh you have one zero right and this is then when we covered when we try to fix this one to be zero and then that's when we have we will have one zero to one zero one right this is the one we will cover the one zero one case but for this one actually since we're fixing this zero in this case so similarly since this is one we're fixing zero here which means that you know the range we're covering is one zero to one zero for the last one not one zero one right so this is a the difference okay so which means that you know this while loop will never cover the n itself and that's why you know we need to do a answer class one because you know when we when there's a concept when there's a consecutive uh ones uh in this and itself obviously we should not include this n number into the final answer that's why you know whenever this if check is true we simply return the answer but if nothing if there's never a consecutive once in this end we will we need to include it into the final answer um yeah i think that's everything you know i'm not sure for the for this last part if you guys uh clear about that because you know i the way we are doing this thing is that you know uh oh and that's why when i it says that you know dp0 do does have other meaning it's this case which is for the one for this case for the zero case one zero to one zero this is also another uh valid number right that's why you know dp0 is 1 because we are covering 1 number in this case which is the 1 0 itself right because it means that you know the dv 0 means that basically by fixing the current uh after fixing the current one to be zero there's not nothing there's nothing on the right side for example this one right so basically if you fix the current one to be zero there will be five digits on the right side that's why we have this dp5 so db0 means that you know after fixing the current one to be zero there's zero digits on the right side which means that you know this dp0 will we will be representing this uh one zero itself right that's the meaning of db zero i think and yeah so that's it i know it's a pretty long explanation but i hope you guys uh can understand what i'm trying to explain here and as you guys can see so now the time complexity is what simply o of 32 to the max right because the k is like this and this is also like a constant right oh we haven't even run it no so let's run it so what's the point if it didn't work right all right cool so it works right um yeah i think that's it right i mean just to recap so basically this to solve this problem you know we have we need to make we need to solve two sub problems the first one is that given like a length of the digits how many values numbers how many numbers within uh who has that size who has this eighth length of digits are valid numbers and we use this one this fibonacci like uh kind of dp transition function to calculate it right and so that's it and the second one is that you know this given this dp here right how can we utilize this gpu to help us to find all the valid numbers within the using the given numbers right so the way we're doing is that you know we only use that this fibonacci dp array whenever we see a one because otherwise you know we don't know because with a one that's when we can fix this one to zero and we can just safely check all the remaining digits on the right side right and then under further for divided range which is greater than this counter range right we simply just keep go moving forward until we see a next one right and then we just keep doing it accumulating that and the last thing is that how can we deal with the this consecutive ones in the original and right we simply stop there cool i think that's it for this problem and thank you for watching this video guys and stay tuned see you guys soon bye | Non-negative Integers without Consecutive Ones | non-negative-integers-without-consecutive-ones | Given a positive integer `n`, return the number of the integers in the range `[0, n]` whose binary representations **do not** contain consecutive ones.
**Example 1:**
**Input:** n = 5
**Output:** 5
**Explanation:**
Here are the non-negative integers <= 5 with their corresponding binary representations:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
**Example 2:**
**Input:** n = 1
**Output:** 2
**Example 3:**
**Input:** n = 2
**Output:** 3
**Constraints:**
* `1 <= n <= 109` | null | Dynamic Programming | Hard | 198,213,474 |
886 | hello everyone in this video we're going to be looking at the solution to delete code problem possible by partition so in this problem were given a set of n people so we have n people and we want to split everyone into two groups of any size so there's any size now each person may dislike some other person so they should not go in the same group so it is like if I were given a 2d array or very two people if they're in the same array meaning that they dislike each other so if a or B are in the same array then a or b cannot be in the same group they dislike each other and so we only have to partition everyone into two groups we can look at this example here so we have 1 2 1 3 2 4 so 1 doesn't like to so 1 & 2 are separate one doesn't to so 1 & 2 are separate one doesn't to so 1 & 2 are separate one doesn't like 3 so 1 & 3 are separate two doesn't like 3 so 1 & 3 are separate two doesn't like 3 so 1 & 3 are separate two doesn't like both 2 & 4 are separate so cook 1 like both 2 & 4 are separate so cook 1 like both 2 & 4 are separate so cook 1 can't be this group 2 can be this so very simple problem as they only have to separate them into two groups so we'll just look at this example and see some approaches so this is the dislike array meaning that the people who dislike each other this it should be Java yeah so these are the people who dislike each other no my what I thought earlier was what we can do is 1 & 2 dislike each what we can do is 1 & 2 dislike each what we can do is 1 & 2 dislike each other so first of all we can have two groups so we can have took 1 and we can have group two so when I do dislike each other so obviously they have to be in the they don't get to be in the same group they have to be in different cook so one can be here two can be helped now I come to one and three and so one is already in a group and she doesn't want to be in the same group as one so three terms here no 4 and 2 is already in the group and who doesn't want to be the same with h2so4 culture so what I thought for it is you can just manually run a loop and if two person are not in any group and then we can just put them in two different groups and if one of them means it is in a group then we can put the other into a different group but this approach won't work and I'll tell you why so suppose I have 1 comma 2 and I have 3 comma 4 and I have 1 comma 3 so what I do have to be in a different group so 1 is here 2 is here no three and four have to interdiction group so I put three here because no condition and four I can put here for I can put here but two and four cannot be in the same group so our answer will be false but it's the answer false no the answer is true how is that so what we can do is one into don't want to be in the same to fine I can do one I to one and three don't want to be in the same group so I came to two and three and two infer don't want to be in the same group so I can do one at four so this is you can see a possible answer for this given test case point to one thing to put one forward together and to 3i together and nobody who doesn't want to be in the other group in with someone else is not so this is a sandy condition satisfied this is a condition satisfied example so what I mean is that we have to look at all of the cases at once for example one may have one comma two and then we have three called two comma three and then we have five comma six and then later on one can also have one comma 5 later on one can also have one over seven so my point is when we are searching for one then all the person point doesn't like have we have to take care of them at work two five and seven and then one all of the person who do doesn't like we have to take care of the met one so one three and like that so this is nothing but an adjacency list representation of a graph we will be solving this by considering people or people as nodes on the graph so idea is we'll come across a node or a person so we'll have two groups again good one and two that will be the same in our approach so we have Group one and group two now if you're going to do is we come across a node we're going to use BFS so we take that node and we put it in a queue and after putting it in I putting it in the queue so I have one two three four five so I take one and I put it in my queue now all the person one doesn't like I now I take one out of the queue and put in and take in all the person whom one doesn't like and afterwards I just whatever those persons are their group will be potato cut so I'll just make all of their groups the opposite of one then afterwards if one or the person he doesn't like are in the same book then the answer is false otherwise answer will be true so to make motions as I code it so like I said we'll be doing this with cloth using PFS and the idea for that was that we had to find all of the person that one person doesn't like and that can be used as adjacency list representation so for the list representation we'll just use a list of list popping teacher and I will just call it drop because they're having a graph so it would be a new ArrayList you are a list of for size and plus one because people are from 1 to n naught 0 to n minus 1 so the size will be n plus 1 and then we'll have in or we'll have a group so any so group of I will tell the group that the person is in so coop will be new in and it'll also have the place what and initially all the people will be in group 0 which is meaning that we haven't put them in any code so cook 1 and go now we just need to add the bus we just have to make that a since a list so first we'll just create so it doesn't go it doesn't give null point exception so I less than equal to and I plus and then grow it add new ArrayList Oh in teacher so this is just filling up with empty array list so it doesn't give the important exception when we actually add something in our list no simple thing less than equal to N or dislikes dot length less than equal to just like so I pressed us so the disk what we are doing is so dislikes of zero doesn't like dislikes of I of zero doesn't like dislikes of by your phone so in the edges in the adjacency list of dislikes of I of zero will put in this lecture for your one and with one will put in zero simple so meaning that in curve dot get his lights of I of zero thought dislikes of your phone so zero doesn't dislike zero doesn't like one doesn't like zero so both of them be will be in there adjacent silat will be in each other 30 sensible so just copy it and in one we have zero so when doesn't like zero doesn't like one and we have a will have a queue like we usually have for or do you p2p we usually have for to India fest and we'll just name it queue so it'll be a new linked list oh he just between we need to write that so now we can just to work on the people so Oh let's then n I so we're going to look at each people then we're going to look at all the people they taste like and we'll put everyone in some group so first of all if the person is not in any group only then we need to worry otherwise we don't need to bother so a group of I meaning is equal to zero meaning that person is not in any way so I'll just write it down group of group is equal to zero groups are I'll just write down good are one and to cook if group is zero then meaning turn out in any group so if group of I is zero then what we need to do is we need to add that person to our Q so Q third over I so now we've oh like edit this guy to our Q and then we'll look at all the people he dislikes so first we need to make his group as one so we need to group him so I'll just give him one randomly then I read it and to avoid it to make you know while not you thought empty so we'll keep on doing it while queue is not empty meaning all the purses are not so white thought queue is empty what I'm going to do is I'm going to say in U is equal to Q dot foo so whatever person is on the front of the queue I'll take him out and I'll deal with his dislikes so his dislikes are in the list da thought I taught you the graph of that gate of U is the list of all the people it is light so what I'm going to do with the people he dislikes is that I'm going to put them into opposite group as he is if he's in one I'll put them into it is into I'll put them in one and then I'll do if they're already not in any group so group of T is equal to zero they're not in any group then if group of U is equal to one then we'll put the person he ate he hates in two and you're facing two then we'll put the person he hates input then we add this person to earth queue and then we'll deal with his dislikes so cute Auto for K so why am i considering this group of PI to PI so am i considering the opposite of group of you when I already put is one here so for the first person group his group will be one for the other people cook may not be one that's why we have to check and put the person he dislikes in the opposite group of U is 1 then we'll put the person he hates and do if there isn't cook dude and we'll put the person he hates finally we'll add the person to work you know here comes the main thing so if group of G is zero and there's one no condition suppose that J the person you hate is already network so if he's already in a group and he isn't that thing repels you then our condition will not be satisfied because they're already in the same row so cooper-cooper U is in the same row so cooper-cooper U is in the same row so cooper-cooper U is equal to of U is equal to poop of J so according to every if they're in the same group then we can no longer like have the people in to cooks so it is fine a condition soup then we return for so we take out you we deal with all the person he hates and if the person he hates is already in his book then we turn first because it is not possible to divide the person in that case otherwise all well and good we can divide the person because there is no problem which like counters our condition so otherwise you can simply return true and that's all that should try to the neck compiler I will return statement very dear I returned it inside okay and so the idea of BFS that we got was from the thing that each person will have it dislikes list so that somewhere reminds us that this person that this can be solved using adjacency list or this have has a plane of adjacency lists in it and using BFS in one node we go to all or that all the neighbors of one node so here using it using BFS from one person we go to all the person need it's light and little bit them so that's why we use BFS so that's all thank you and one more thing guys do subscribe to my channel I plan to do a lot more lead code problems and hopefully I'll be doing all the mainly foot problems interview problems so stay tuned thank you | Possible Bipartition | score-of-parentheses | We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group.
Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates that the person labeled `ai` does not like the person labeled `bi`, return `true` _if it is possible to split everyone into two groups in this way_.
**Example 1:**
**Input:** n = 4, dislikes = \[\[1,2\],\[1,3\],\[2,4\]\]
**Output:** true
**Explanation:** The first group has \[1,4\], and the second group has \[2,3\].
**Example 2:**
**Input:** n = 3, dislikes = \[\[1,2\],\[1,3\],\[2,3\]\]
**Output:** false
**Explanation:** We need at least 3 groups to divide them. We cannot put them in two groups.
**Constraints:**
* `1 <= n <= 2000`
* `0 <= dislikes.length <= 104`
* `dislikes[i].length == 2`
* `1 <= ai < bi <= n`
* All the pairs of `dislikes` are **unique**. | null | String,Stack | Medium | null |
1,998 | hey everybody this is larry this is me going with q4 of the weekly contest 257. yikes uh gcd sort of an array so yeah so basically this is a tricky problem hit the like button hit the subscribe button join me on discord let me know what you think about this problem especially if you'd like to talk about this and other problems come hang out come make me feel good in like conversation i don't know that sounds like i'm trying to brag or something but yeah so this one i actually got it relatively quickly i got in about 13 minutes and if you watch me solve it live during the video the live uh coverage i actually talk way too much i probably could have if i just focus on coding i probably could have done it much quicker but i don't know maybe today i'm just in a talk of talkative mood and i didn't care about it that much but yeah um yeah i didn't get a wrong answer so that's good i wasn't even confident anymore because i've been very sloppy but the idea here is this right so basically you can sort two numbers if there's a common divisor so i'm going to break it into two components one is um yeah we'll do about the primes part but basically let's say pretend that you know i know that n is 10 is uh it's 3 times 10 to the fourth but uh let's yeah because n is 10 3 times 10 to the fourth we cannot do this in n squared time because it takes too long but let's pretend that we can do this in n squared time um that i'm going to explain an n squared algorithm real quick right um and this is maybe intuitive if you think about it i don't know what the sorted thing is okay i could copy and paste um but yeah and yeah i'll go over a couple of cases but the idea is that if you have an n square solution um then you can look at every number every pairs of number and kind of see if they have a common divider right if they have a common divisor then you can sort between them and in this case for example um 5 you could start with 10 and in a way because um because of this um what's it called they call flipping uh swapping um in this case swapping is transitive right and what do i mean by that what i mean by that if a is if you can swap a with b that means that and you can swap a uh okay let me say it again let me write it down if you can swap a with b and swap b with c then you can swap a with c right i don't know my computer is a little bit slow um and the reason why this is the case um even though you cannot do it directly to be correctly to be true right so for example let's say you have a b c and you want to sort it backwards um and you cannot you know you cannot swap directly a with c you can just kind of use you know uh you could kind of use b as an intermediate variable for example this is one possibility sort a with b and then you sort c with a right or sorry b with a so you can definitely do it so you know it takes a couple of operations but because we have infinite number of operations this transitive probability holds right so that means that now if we have an n squared algorithm is that well um now we just kind of go through the way to kind of do a depth first search on every possible pair right um and what i mean by that first search is that you may imagine that we have um you know now instead of a and swapping b then now a is connected to b there's an edge from a to b and there's an edge from b to c and that means that those three numbers are interchangeable of each other right and then now you can do a connected component and what does that mean for you well in this case at the very end um there are a couple of scenarios right which means that if everything if the final sorted numbers um if you look at them one by one if they're in the same connected component then you can get them together right in this case um yeah in this case actually i think every number is sorted but um okay they don't provide a good example for you but for example you can imagine uh something like 2 4 or let's just say 4 2 and then we add some odd numbers 3 9 uh 27 right um okay maybe a little bit not sorted so let's just say i don't know nine again right doesn't matter right um so the idea here is that we're building out these components because okay we know that we can swap this number with this number right so this is one component so one component is 4 2 and then another component is 9 327 right because you can swap them with each other and then now if we given the sorted um uh answer the question is okay so can this 4 get to this 2 well the 4 can get to this 2 if they're in the same component right um and you can do this in n square um of course it's time small but the definite search or breadth first search will be n squared right um yeah the nine can you get to the three the answer is yes okay that's good the 2 can you get to the 4 yes because they're in the same group same for 3 and 27 right so then the answer is true for this one but keep in mind that in this case the 4 and the 2 do not interact in any way oh sorry the 4 and the 2 interact with each other but they're totally independent from the 3 9 and 27 right so that's one thing and then the second thing um so that's the n square algorithm and that's too slow right so then the question is you know how do you make it faster well the thing that i talked about is um connected components and that should ring a doorbell and the doorbell is use union find and basically the idea behind union fine is that okay for every number this is not a good example um but for every number we try to figure out um yeah uh so for every number you can still do it n square but the linear time way is to break it down to these components right um because okay for example and this is kind of awkward because these are all powers or whatever so let's actually take this number real quick um right so what does this mean this means that 10 is equal to 2 times 5. what does this mean that means that this number is in the same group with every um every multiple multiples of two and five and every multiple of five right so now right but what does this also means right this means that 10 now is a group between two and five because of what we said earlier with a swap b equals b swap c and so forth um so the translated property holds and that means that you know now given the 10 even if you have a two and a five oops uh let's just say we have two and then uh a multiple of 25 and four say um right or even five times say nine so 45 right um so 45 and 10 they have at least five as a multiple together or so i divide it together so that means that you can swap 45 of the 10 and then because 10 uh is also as a divisor with four that means that four now can swap at 45 due to the transit properly right but so what does this you know now i'm going to say it another way this means that now any number with a divisor of 2 is now swappable with any oops number with a divisor of five i think i missed typo because i can't see what i'm typing because my computer is slow for some reason my chrome is slow okay actually i mostly typed it okay so swappable is one p i think it's a two piece i don't know actually whatever um so yeah so that's basically the union fine way of doing it is that now you know now you in this way you so now you define these what they call your equivalent set um so now you have um multiples of two and as in one set and multiples of five in another set and now you put them together right um so that's basically the union find solution um and now yeah the thing that i thought about though is that this may still not so this is fast um you could do this in linear time the problem is that you have to factor every number in the number list and that may be too slow if you're not slick enough right um so the way that i did it um because you can do some math um so the biggest number is 10 to the fifth so the square root of that times 3 30 000 is equal to some number i forget what it is but it feels too big is this fast enough in python um right so i wasn't sure so i did one more optimization um and the optimization is using the sieve um i always forget how to say the sieve of errors uh aristotle's did i spell that right nope ah close mr t uh maybe i misspelled this right uh i misspelled this incorrectly huh how do i spell it toast yeah okay ever told denise okay well but yeah so i would google this but basically that's the way that i did it um i'll go over my code right now um pretending that union fine is a constant i know that there's um there's some inverse anchorman stuff i know but i'm just going to call it constant for now because it's easier to say so i have these uh this union fine code and then now i have so i set up the primes this is the sif basically i just go up the up to the max and matches the biggest number into the array but basically i calculate all the primes uh factors for this number so for the and this is just to say if i'm not going over the sip that much but this is actually max let's say m is equal to max this actually wants him m log m time the proof is a little bit tricky please do some research uh but yeah but basically here now that we have all the primes together reunion them uh with the first one because that's just how you group them they're is transitive right so now we're um reunion all the primes together given a number and then at the very end this is just to see if they're in the same component which is that okay if the u find of the number so s nums is the sorted number so we have to sort it so it has to be on log n i suppose actually but uh but yeah but basically we look at if the number in unnumbs if the group is the same as the or if it's not the same then that means that it's forced otherwise if it's true for every one of them then it's true um so yeah so this algorithm like i said because you have to sort first it's going to be n log n plus m log m where m is the max number um yeah in terms of space this is all of uh i think m log m as well because of this thing because we uh yeah and also uh of n plus this for space um because this can contain a lot of devices i think so i think it's m log m i could be wrong um on that particular one um yeah and there's also a lot more space for you know union fine and stuff like that but yeah but that's all i have for this one uh let me know what you think i think if you get this part um you can actually implement most of this part the civ is also a little bit tricky as well but that's fine i did so i actually did everything from scratch i didn't do any copy pasting i know that people like to cop to have this template and even this is template so maybe you can save a couple of minutes but um but yeah i did this in about 13 minutes without it so you should be able to not need it is my point uh even if it takes longer obviously but yeah uh that's all i have for this one let me add let me know what you think and you can watch me solve it live during the contest next and i talked a lot during the contest so hopefully maybe that's helpful i don't know why i talk so much anyway let's actually see how this one's looking uh 47 people have gotten it so if i do this now maybe i'll get in a good time but yikes though that was a rough problem for me okay but i just need to write it down actually if that wrote it down was pretty easy but i just kind of convinced myself i didn't need to okay let's actually do this one any number of times swap i and j if they're if they are um much mccoy uh if they're mutually something uh i'm pointing out numbers right now um return true it's possible to start numbers in non-decreasing numbers in non-decreasing numbers in non-decreasing order okay so basically this is going to be some sort of union fine perhaps and this kind of thing okay so yeah um how do we figure though is i think it's gonna be some sort of union fine but how do we figure it out if they have a common denominator uh or a common divisor then that's good so that well that means that we can do them this is 10 to the fifth so common dividers are not that big but um that means that for every we can group okay so we just factorize every number and then we group all of them and if we are able to group all of them i mean but that's not always true because in that you can have if the input is already like sorted like this it doesn't matter that they're not grouped um so then the question is okay i see so then now it's just union fine and basically for every um we just look at the group of the result and the thing okay fine um so sorted away or sorted answer maybe so that answer is equal to a copy of this um or yeah we just sorted actually it's called s numbers for sorted numbers um and then now we factor every number and okay so then union fine okay union fine of x is equal to return parent of x and then here if parent of uh is just not equal to x our current of x is equally fine for that pound of x okay and then here we just have pound as you go to this thing it's not even a maybe called group i forget what i use for union fine let's call it g and that's called parent whatever i know what that means and that's good enough for me yeah yes you got a u fine of a u b is equal to minus b uh u count of u a is equal to u b and then that's pretty much it so then now we group them together all the numbers for x and nums we factorize how many numbers are the 30 000 is it three times ten i always forget i read this as sometimes three thousand and i get in trouble so okay thirty thousand square root of ten to the f uh what is square root of ten to the fifth um square root of that i'm just using a calculator don't worry that's 316 so 316 times 30 000 is 9 million yikes is that fast enough uh i'm trying to think how i would write this in a good way do i need to use the sif i'm worried about uh just doing this straight up but then this goes only up to 10 to the fifth so we can use the surf um yeah let's do that yeah okay uh let's see what uh nums uh let's try to surf um okay um the good thing is that we can able to test this pretty quickly so that's good um okay what does that mean i have to remember how to do the presif but uh but i should be able to do this just 45 minutes and i think my idea is right my implementation has just been terrible because i don't practice enough but okay if length of times is equal to zero that means that this is prime so prime sub x well this is a prime so then okay just do this and then otherwise and then we do for y in range of uh let's just do it this way well y is less than or equal to max we add this by x and then we just use prime of y dot append x okay yeah okay so then now let's return something let's see if this should be fast enough i'm gonna run it for this but what i really want is something like um 10 to the fifth do i have enough zeros but it's hard to tell oh two and that okay fine okay this looks fast enough so i'm happy about that um let's print it out real quick to see that we do real work because otherwise okay so we don't do real work so that makes it easier for it to be fast huh oh okay that's why which is a quick loop uh okay y is equal to x plus x okay so this is fast enough maybe we could if it gets nasty we could mess it up two three four five six seven eight nine ten 10 11 12. everything looks okay so far and looks and it runs pretty quickly so okay so then now we have to look up table for the sieve then now we just have to go for the x um okay for x and nums uh so what does this mean when we see a number let's also get the index when we see a number it means that we want to group all the things together so okay for y in primes sub x we want to union uh y with primes of x of zero um so this should be a union we'll start actually from the first number so then we skip the first number um yeah maybe this should be good so then let's look at parents oh um i forgot to set this to how do i want to write this okay if x is not in parent then parents of x is equal to x and then we return uh okay maybe that's good enough actually um okay it doesn't so then now it's what is what am i printing that means that 2 and five are in the same group which is what we want two five and three are the same group so that's also what we want is that a true answer for the second to last one five cannot be i thought we put five in the same uh thing okay so maybe that's not quite true let's see let's put out what i'm doing here print out union so x of zero and then y okay so it's union two and five and then three and five why am i looking at the white case oh i'm looking at the one case that's why okay sorry so okay so i'm doing it right um and then here it doesn't because two and three unions but then the five doesn't okay so then now we are mostly done all we have to do is just um yeah okay actually we don't even need the index on here because this is just to include the unions and then now we look at for for a b and sip of s nums and s nums uh if union find of a uh that's not true what am i doing if the union fine of the prime sub a of zero basically get the group that it is in and we union and everything so everything should be together if this is not equal to that of b doing that um then we return oops we return force otherwise they're in the same group so we're okay i think i talked too much to be honest but okay so this looks okay i mean i'm a little bit early but let's give it a submit and then we get a wrong answer we'll debug it um cool i mean i was actually pretty happy about this one hey uh yeah thanks for watching everybody hit the like button hit the subscribe button join me on discord and come hang out with me um yeah stay good stay healthy to help you have a great rest of the week hope you had a great contest uh anyway see you later and yeah good mental health bye | GCD Sort of an Array | suspicious-bank-accounts | You are given an integer array `nums`, and you can perform the following operation **any** number of times on `nums`:
* Swap the positions of two elements `nums[i]` and `nums[j]` if `gcd(nums[i], nums[j]) > 1` where `gcd(nums[i], nums[j])` is the **greatest common divisor** of `nums[i]` and `nums[j]`.
Return `true` _if it is possible to sort_ `nums` _in **non-decreasing** order using the above swap method, or_ `false` _otherwise._
**Example 1:**
**Input:** nums = \[7,21,3\]
**Output:** true
**Explanation:** We can sort \[7,21,3\] by performing the following operations:
- Swap 7 and 21 because gcd(7,21) = 7. nums = \[**21**,**7**,3\]
- Swap 21 and 3 because gcd(21,3) = 3. nums = \[**3**,7,**21**\]
**Example 2:**
**Input:** nums = \[5,2,6,2\]
**Output:** false
**Explanation:** It is impossible to sort the array because 5 cannot be swapped with any other element.
**Example 3:**
**Input:** nums = \[10,5,9,3,15\]
**Output:** true
We can sort \[10,5,9,3,15\] by performing the following operations:
- Swap 10 and 15 because gcd(10,15) = 5. nums = \[**15**,5,9,3,**10**\]
- Swap 15 and 3 because gcd(15,3) = 3. nums = \[**3**,5,9,**15**,10\]
- Swap 10 and 15 because gcd(10,15) = 5. nums = \[3,5,9,**10**,**15**\]
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `2 <= nums[i] <= 105` | null | Database | Medium | null |
1,679 | hey guys in this video I'm going to talk about a lead code problem the problem's name is Max number of K some pairs so in this question we given an integer ARR nums and also integer variable K in one operation we have to pick two numbers from the array whose sum is equal to K and remove them from the array and we have to return the maximum number of operations you can perform on the array so we have to remove all the pairs which are having some equal to five so let's take this example here you can see the sum is five you have to pick two elements I'm picking one and I'm picking four 1 + 4 is equal to 5 it is equal to four 1 + 4 is equal to 5 it is equal to four 1 + 4 is equal to 5 it is equal to sum so I remove these two elements from the array so the array will become 2A 3 now again I pick this element and pick this element 2 + 3 is equal to five pick this element 2 + 3 is equal to five pick this element 2 + 3 is equal to five so I remove these two elements from the array and the array will become empty since I perform two removal operations I return two as the output so talking about the first approach let's take the input array so I've taken the same example as example one so in this approach I'm going to use a map to count the elements and their number of occurrences so this approach is similar to the first problem lead code called two sum I leave a link to that video in the description box below where I'm going to use a map find out if the complement of the current number is present inside the map or not so let's declare the map so first let's start with i is equal to 0 we check if that element is present inside the map no it's not so add it and set its frequency to 1 now the complement of this element 1 so 1 + something is equal to 5 right 1 so 1 + something is equal to 5 right 1 so 1 + something is equal to 5 right that is our Target 1 + x = 5 so this that is our Target 1 + x = 5 so this that is our Target 1 + x = 5 so this will become x = 5 - 1 5 is equal to K will become x = 5 - 1 5 is equal to K will become x = 5 - 1 5 is equal to K right so this is equal to Kus 1 if we subtract the current element from K we will get our expected value which is four so we have to search if this x is present inside the map so X is four in this case so we have to check if four is present inside the map no four is not present as of now go for the next element now I is pointing at two check if complement of 2 5 - 2 equal to 3 if complement of 2 5 - 2 equal to 3 if complement of 2 5 - 2 equal to 3 check if three is present inside the map no it's not present so add that element and set it frequency to one now go to the next element complement of 3 is 5 - the next element complement of 3 is 5 - the next element complement of 3 is 5 - 3 is = 2 check if 2 is present inside 3 is = 2 check if 2 is present inside 3 is = 2 check if 2 is present inside the map yes it is present so there is no need to add this element into the map but we have to remove this element which is its complement from the map so I remove this element from the map and increment the count to one because we found a pair remove it now in the next iteration I is equal to 3 complement of 4 is 1 because 5 - 4 is 1 because 5 - 4 is 1 because 5 - 4 is equal to one check if one is present inside the map yes one is present so we increment count and we remove the complement from the map and in the next iteration I is pointing at four which is out of bounds so we come out of the for Loop and return whatever is present inside count is equal to two denoting the two operations so two is the output now let's take a look at the code for this approach so let's start by creating a map let's take the second example now numis 31 3 43 and K is equal to 6 I created the map where key is going to be the ARR and the value is going to be the frequency of that R element I create a variable count which is initially zero so I is pointing at zero now we start with i pointing at Z now we find the complement of that 6 - 3 now we find the complement of that 6 - 3 now we find the complement of that 6 - 3 is equal to 3 check if 3 is present inside the map No 3 is not present so this statement will be executed I add three and get its current count is zero default value 0 will be executed I'm adding + one so it will executed I'm adding + one so it will executed I'm adding + one so it will become one next iteration I is pointing at index 1 we find the complement of that element 6 - 1 is equal to five that element 6 - 1 is equal to five that element 6 - 1 is equal to five check if five is present inside the map no it's not present so again this statement will be executed add that element one and set it frequency to 1 in the next iteration I is pointing at index 2 find the complement 6 - 3 is index 2 find the complement 6 - 3 is index 2 find the complement 6 - 3 is equal to 3 check if 3 is present inside the map as key yes three is present so remove that from the map and increment count to one and then removing that elements next move I further calculate the compliment 6 - 4 = 2 check if 2 is the compliment 6 - 4 = 2 check if 2 is the compliment 6 - 4 = 2 check if 2 is present no it's not present so add it into the map so 4A 1 will be added into the map move I further complement of three is three check if three is present inside the map it was present but it has been removed for this pair so there is no three present so add the current element three into the map and set it frequency to one and in the next iteration I will go out of bounds and will reach the end of the for Loop and we come out of the for Loop so whatever is present inside count is having the value one so one is returned as the output so the time complexity of this approach is O of N and the space complexity is also o of n because we're using a map where n stands for the length of the Namar now let's take a look at the approach which we use where the time complexity is going to be of n log because we're going to sort the array in ascending order and the space complexity is going to be constant space so this is a better approach where we improve the space and we sacrifice the time complexity but for this specific question o of n login will run faster than o of n because of the small input size let us go to the method two so I've taken the example two to explain the method two so this is the nums array so in this question as I said we are going to sort the array in ascending order so after sorting the array will look like this so the value of K is equal to 6 and now in this approach I'm going to use two pointers so left will be pointing at the starting of the array and right will be pointing at the end of the array we add the elements at left and right left 1 + 4 is elements at left and right left 1 + 4 is elements at left and right left 1 + 4 is equal to 5 since 5 is less than 6 we need to increase the target value we have to increase the sum we have to move the left pointer because if you decrease the right pointer the overall sum will decrease so because the array is sorted in ascending order the larger values are placed at the end where right will have access to so if you remove the larger it will either not change the total sum or for sure decrease the sum that is why we try to move further and increase the sum now left will be moved further and we find the sum again sum is 3 + 4 is equal to 7 the sum again sum is 3 + 4 is equal to 7 the sum again sum is 3 + 4 is equal to 7 compare it with K 7 is greater than 6 so we increase the value now we have to decrease the sum compared to the Target six so as I said to decrease the sum decrease the right pointer Now find the sum again 3 + the sum again 3 + the sum again 3 + 3 is equal 6 so 6 is equal to K so we increment the count and since both so since both left and right have been used to form the output we move both the pointers so left will move further and right will be decremented so this action will perform until left is less than right so this y Loop will run until left is less than right as both are not same we end our iteration and finally count which is having the value one will be returned as the output outside the while loop so one is the output now let's implement the steps in a Java program so let's take the same example as example one now we having the input array so let's sort the array in ascending order after sorting the array also the array will remain the same because it's already sorted in ascending order that's fine now let's declare the two arrays now let's declare the two pointers left and right left will be pointing at zero index and right will be pointing at array length minus one that is last index and declared a variable count now we use the while loop where left is less than right left is zero and right is three yes it will go inside now let's find the sum nums of left plus nums of right so 1 + 4 is equal to 5 it nums of right so 1 + 4 is equal to 5 it nums of right so 1 + 4 is equal to 5 it is equal to K so increment count this part will be executed and since we used both left and right in our forming the sum move both the pointers so left will move further and right will be decremented by one now let's repeat the same steps find the sum 2 + 3 is equal same steps find the sum 2 + 3 is equal same steps find the sum 2 + 3 is equal to 5 again both are matching so increment count move both the pointers now this condition will fail because right is equal to one and left is equal to two since this condition is failing 2 is less than one this condition fails so we come out of the Y Loop and return whatever is present inside count has two so two will be returned as the output which is matching here so the time complexity of this approach is and login because we sorting the are in ascending order and then using a while loop to iterate from left to right the space complexity is of one because we're not using any extra space to solve this question that's it guys thank you for watching and I'll see you in the next video | Max Number of K-Sum Pairs | shortest-subarray-to-be-removed-to-make-array-sorted | You are given an integer array `nums` and an integer `k`.
In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array.
Return _the maximum number of operations you can perform on the array_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], k = 5
**Output:** 2
**Explanation:** Starting with nums = \[1,2,3,4\]:
- Remove numbers 1 and 4, then nums = \[2,3\]
- Remove numbers 2 and 3, then nums = \[\]
There are no more pairs that sum up to 5, hence a total of 2 operations.
**Example 2:**
**Input:** nums = \[3,1,3,4,3\], k = 6
**Output:** 1
**Explanation:** Starting with nums = \[3,1,3,4,3\]:
- Remove the first two 3's, then nums = \[1,4,3\]
There are no more pairs that sum up to 6, hence a total of 1 operation.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109`
* `1 <= k <= 109` | The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix. | Array,Two Pointers,Binary Search,Stack,Monotonic Stack | Medium | null |
914 | hey everybody this is larry and this is now me doing the bonus question uh hit the like button hit the subscribe button join me on discord let me know what you think about you know today's bonus question i'm gonna do a hard today uh um okay fine let's actually just let the rng choose because i don't know if you're doing it at home with me then you know i want it to be fair so let's see okay subscribe to do about to find it one that does not require subscription because i'm cheap and i haven't paid for it maybe one day i'll pay for it anyway okay so we're getting a yeezy day so 914 x of a kind in a deck of cards okay in a deck of cards each card is a number or individual on it we aren't true if you can choose x over two or x is greater than two such that as possible to split the deck into one or more group of cards where each group has exactly x cards and you two cards have the same number okay so basically the idea is actually it's kind of very similar to the problem that we did today because it's kind of like okay so we have you know let's say we put them or in a counter right then now what well then now the values um if we set it's um length of this is equal to one i think that's pretty much it right unless i misunderstood this part because they have all the partition this is actually wrong because x has to be greater than or equal to two so but this is like mostly right but it's not right because of that like i could try it um and if this was a contest i would be very sad if i submit this i think that's why i've been kind of i don't know but yeah as you can see i returned true because there's no uh um the number of counts is always whatever but yeah i mean you can this becomes a little bit awkward now but um okay let's just write it this way do set is equal to all this stuff and then one and max of s is equal is greater than one right so i think that should be good but you know it's not as cool as a one-liner but it's not as cool as a one-liner but it's not as cool as a one-liner but we'll see if that works maybe i missed some case as well oh now oh huh i really did miss understand this one i guess in this okay fine i don't know if i misunderstood it but i did miss an edge case that's kind of uh um because the idea here is that do i wow for easy i'm not gonna lie i underestimated this because it was easy i was like usually maybe i'll try to you know do something cute and clever uh even then there's a thing but the idea here is that basically you can split into groups of two by squaring this into two um and then the next idea would be to just you know take the min and then you know put it into multiples but then that's when you get into issues of you know gcd and stuff like that right so and that's pretty much the idea i think is that we now do the gcd of all these things um and then just making sure that uh i've always forget where the gcd and python is i guess we can do that um i always forget whether gcd and python allows me to um gcd and python allows me to do a list but i guess not i feel like to some language where you can take it as a list but uh how do i do it um i think there's a reduced function or something like that or map function now it's a reduce function right uh gcd reduce python something like that so you could do it in one line or something but uh okay so you could do something like reduce gcd list of s right something like that because the idea is that if you just naively tick uh where is my other yeah we naively do one two that's fine but then we have like um let's say four and six right four numbers one three four one two three four five six the answer should be true because then now you have two as a number which is the gcd portion but you know ooh what did i get i will force but this should be true huh did i miss this hmm because the gcd should be between four and six and that should be unless i misunderstood it um and that should be two i mean maybe my representation is wrong oh no whoops this one is query not white um i don't know why i had still have this i think i just left it in for some reason because i don't know left it in from before and forgot to take it out because i was trying to fix the second part but uh okay so let's try it again let's give it a submit i mean it's not a hard problem but it's definitely a little bit harder than yeezy and i definitely just underestimated if i really thought about it maybe it would be okay um i wonder if yeah i don't know that you can do it in a better way um in the sense that i wonder if there's like some brute force way i can do it like you can't really test for one two three dot uh maybe you could take the smallest number and then before like you know put force on the factors or something but that's a little bit awkward uh let's take a look we could really is this fast enough why is this fast enough and it's real plugin i guess if you already okay i guess if you have already have the counter then maybe you could do it i'm not sure though oh i guess it was 10 to the fourth for some reason i thought it was 10 to the fifth um like okay i guess you can before so okay so i guess if you can move first then maybe this is a yeezy but i did the gc doa um but this is n squared though oh i don't know that's really awkward because i've that's definitely too slow to be on square yeah i don't know i mean this is a little i mean i'm not saying it's hard i'm just saying it's a little bit hard for and easy definitely a lot of it or not a lot of edge cases but definitely at least like you have to really think about your edge cases at least you know or one edge case or one or two edge cases about how you want to think about it but you have to think about it um yeah anyway this is gonna be linear time linear space um then your space to do this thing you don't even really need to set i kind of just kept it in there because i it wouldn't change the answer because that's the way how gcd works but yeah and i kind of left the other thing in there just because i wasn't looking at it and i forgot about it but yeah uh that's pretty much all i have for this one this is easy but um it's marked as easy but clearly uh very easy to get wrong but that's what i have so let me know what you think stay good stay healthy to get mental health i'll see y'all tomorrow see you later and take care bye-bye | X of a Kind in a Deck of Cards | random-point-in-non-overlapping-rectangles | You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card.
Partition the cards into **one or more groups** such that:
* Each group has **exactly** `x` cards where `x > 1`, and
* All the cards in one group have the same integer written on them.
Return `true` _if such partition is possible, or_ `false` _otherwise_.
**Example 1:**
**Input:** deck = \[1,2,3,4,4,3,2,1\]
**Output:** true
**Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\].
**Example 2:**
**Input:** deck = \[1,1,1,2,2,2,3,3\]
**Output:** false
**Explanation**: No possible partition.
**Constraints:**
* `1 <= deck.length <= 104`
* `0 <= deck[i] < 104` | null | Math,Binary Search,Reservoir Sampling,Prefix Sum,Ordered Set,Randomized | Medium | 912,915 |
191 | hello everyone so in this video let us talk about one more problem from lead code the problem name is number of one bits so this problem is from the top interview question series i've been working on from lead code so if you haven't checked it out i have the link of that delays in the description of this video so go check it out okay so i will making out a lot of top interview questions from lead code the problem name is number of one fit so the problem statement goes like this that you are given a number n and that number is of that type like it is a bit representation of zeros and ones okay now you just have to tell that how many bits are set okay so bit set up by if any terms you means that how many bits are set so every number consists of bits zeros and ones that is its binary representation now if we want to like tell how many number of ones are there in the binary representation of any number that means that you just asking how many bits are set in that particular number in binary representation that's what the problem statement asks you to do now they can multiple ways to do this problem but the very standard way uh to do this problem is by using the left shift operator so this operator now how this operator works i'll give you one uh like overview of how it works so this operator is called a left shift because it is like pointing towards left and this is the right shift now left shift operator shifts the number that we are inputting by this particular amount what we are putting on the right side i'll just give you so one left shift let's say two times this represent means that we are writing down this in by this is not 100 this is in binary representation so this is equivalent to this now you might be asking how so this means that you put a one and then so let's say that you put one and then left shift it two times so when you left shear fit obviously there can not be any number or like any bit other than one so because you are not putting any bit so it zero will come eventually because you are like shifting it so you can just assume that there's some window and there is one on like uh on the left corner of like the right corner on the window and then you shift this person so like there are different seats so use like shift this one two sides and this is like a long seat like this is a very long uh you can say window but you can only see till this point and everything is zero like everything is empty you can see that everything is empty now if you tell this person one that okay left shift two positions so this person will go to this and this so when this person comes to this obviously this hole will come to this actually this will not shift because these are zeros only but still you can see that they're like this shift like this uh zeros will also shift because everything will shift by two positions so it will be one zero and that is this question so one left shift five times means that one and then five z one two three four five zeros so okay so that is one and one left shift zero one left zero which means that it is only one nothing is shifted so that is how you can check that like what does this left shift operator do now let us talk about how we can like uh check how many number of ones are there in any bit representation so let's say that you have a number that says like this 1 0 1 and you want to check how many so this is the binary representation of some number binary representation and you just have to check that how many like bits are there that are set that are equal to one so what you can do here is you can take one as a number you have okay and if you know what is and operator so what you can do is that you first do an end of this and everything is zero what is this value turns out to be this turns out to be one because when you do end of two bits and if they both are set like both are one then only it will become one so this is zero so this is also and when it turns out to be one which means that this is some number like this is not zero okay let us do one more thing you will understand more now if you do so if you do this now so all i'm doing is end operation then all of them will turns out to be zero because this will be zero this is zero because the like this bit will only be the only one when both of these are one like so both of them are not one so it will be zero so what i'm doing here is that i am doing an and operator of the number i have with a number with one at a particular position and everything is zero so one is moving from left to right at every like every position so one will be like so this particular bit is set and everything is zero then this bit is set and everything is zero and at any position if when two bits are matched then this particular value will become one and it will be all zero but this number it will be non-zero so because there is it will be non-zero so because there is it will be non-zero so because there is a bit so obviously this is the bit this number will not be zero but if you have done an and operation of this number in which this bit is set and everything is not set then obviously it will be zero because this will be zero everything will be zero so this number will be zero and thus what you can observe here is that you can use the left shift operator to do a for loop in such a way that you have one then you left shift one by one position it will become one zero when you left shift one by two position it will become one zero so you will keep on shifting one by left shifting it some number of times so that you got one at every position and whatever number you have you will do and with that number and it and if at any position this one that i'm sending and this one will coincide it will make the number of the end of this number and this number non-zero and whenever they this number non-zero and whenever they this number non-zero and whenever they become non-zero which means that this become non-zero which means that this become non-zero which means that this particular bit is set so we are just doing this for loop and because the number of times is 30 like this uh by anything is of 32 so we'll do a 32 times for loop and every time we just do an end update of the particle number we have and the number that we are forming by left shift this one by n times and then like i had time and then whatever the answer will be like by doing an annotation of both of these numbers if it turns out to be non-zero which means it turns out to be non-zero which means it turns out to be non-zero which means that the particular bit i am on is non-zero so if like it is set is non-zero so if like it is set is non-zero so if like it is set sorry if it is set we just have to count on how many bits are set that's the overall logic from this problem so that's a very small problem that total we're just doing a volume from 0 to 32 we're doing so 1 is left shifted as you can see i times so it will be 0 times so 1 time 2 time and so on so it will be like one zero then one zero and so on so we are doing an operation of this and n and if this number turns out to be non zero because if it is non zero then only this if condition will work if it is zero then this if condition would turn should be false this condition will not meet you can also tell that if this value is not zero then also you will increment your total and in the end you just return the total energy so that's the total number of bits that are sent that's all logic and code i have been posting a lot of videos on binary representation and binary problems also so you can check out all of those problems as well but this problem is from the top interview questions from it so thank you for this video till the end i will see you next month coding and bye | Number of 1 Bits | number-of-1-bits | Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)).
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`.
**Example 1:**
**Input:** n = 00000000000000000000000000001011
**Output:** 3
**Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits.
**Example 2:**
**Input:** n = 00000000000000000000000010000000
**Output:** 1
**Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit.
**Example 3:**
**Input:** n = 11111111111111111111111111111101
**Output:** 31
**Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits.
**Constraints:**
* The input must be a **binary string** of length `32`.
**Follow up:** If this function is called many times, how would you optimize it? | null | Bit Manipulation | Easy | 190,231,338,401,461,693,767 |
965 | hey guys welcome back to my channel and i'm back again with another really interesting coding interview question video this time guys we are going to solve question number 965 univalued binary tree before i start with the video guys just want to ask you that if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications or more such programming and coding related videos let's get started now so basically guys the problem statement is pretty straightforward we want to find out if this binary tree is univalued or not by uni values we mean that if all the nodes are having the same value then it's a univalued tree so in this example you can see that all the values of the tree are one so the output is true because it is unique value in uh in the second example you can see that the leaf node is having value five whereas all the other nodes are having value two so the output is false constraints are that the number of nodes in the 3 is in the range of 1 to 100 and the value goes from 0 to 100 okay so let's jump to the solution guys so just looking at this problem guys there are two ways to solve this problem one is the depth first search and one is the breadth first search so just to explain a bit uh if you're using depth first search then basically you are taking one node and then you are checking its value and then you are going to its left node and then you are going to that left nodes left node so basically you cover the height of the tree first and in that particular order you just check if all the nodes are having the same value and then you go to the next node or to the next branch right but if you are doing breadth first search then basically you are doing sort of a level order reversal that means first you check all the nodes on one level so in this case there is only one node on root level that is root node then you check all the nodes on the second level and then you check all the nodes on the third level okay so basically it's a pretty straightforward implementation of depth first such object first search but in this case we are going to solve this problem with the uh recursive depth first search approach so let's see how we can do that so basically guys we are going to take this is universal tree function and we are going to call this function only recursively to see if this tree is a unique value tree now let me just remove bfs here we are just going to use dfs so the first thing in a recursive function is the base condition right so my base condition is that if the root value is not equal to null so if the root is equally equational then basically it is a unique value tree right so if the root is not equal to null then we have to do for the things otherwise we simply return true now let's go inside this if condition now we are going to check our other base conditions the first base condition is that if root dot left is not equal to null and root dot left dot val is not equals to root dot val so basically if left node is present and its value is not equals to the root value then you can simply return false here because it means that it's not a unique value tree and the same thing i am going to do with the right node so if the right node is also present and its value is not equals to the root node then also i will return false and finally once this check is done that means that for the root node both left and right child are having the same value then we go into their own sub trees that means we'll go and evaluate the left sub tree and right sub subtree so after evaluating those we are going to return and of the left subtree result and right subtree result so if both left subtree and right substrate result is true that means both of them are unique value trees it means that our main parent tree is also univalued and finally this will return true so let's run this quote guys let's see if this works for our problem statement and there you go guys you can see that it's accepted and uh yes so there you go it's accepted not talking about the time complexity guys so the time complexity for this particular solution is going to be order of n because you can see that we are checking each and every node and assuming there are n nodes in our tree the time complexity is going to be order of n the space complexity is going to be order of h where h is the height of the subtree uh basically guys you can see that this particular function is being called for the left sub tree and for the right surface at one particular time if we are going through the entire depth so let's see if i am going to the entire depth of this subtree then at one point of time i will be holding the entire height of the tree in my recursive stack so that's why the order of the space complexity of the order of h you can also call it as order of n if you are using bigger notation okay uh if you talk about dfs guys so dfs sorry if you are talking about breadth first search if you use level order reversal to solve this problem then also the time complexity is going to be order of n um the time complexity is going to be order of n and the space complexity in that case can be order of n because you are using uh a level right so you will be having a q and in one queue at one point of time there is a possibility that you are holding n nodes okay so uh we won't be implementing bfs solution in this because i have implemented bfs in a lot of previous videos so you can go and check those out i can uh put those links in the description below the link of the coding interview playlist so that was the solution guys i hope you guys like the solution and i hope it worked for you as well if it did help you guys then do not forget to like this video and share this video with your friends and do subscribe to my channel guys hit the bell icon for future notifications if you have any questions comments suggestions better solutions please post them in the comment section below so that everybody can benefit from them and i would be happy to address them as well thank you so much for watching guys i'll see you guys in the next video until then take care and bye | Univalued Binary Tree | unique-email-addresses | A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,1,null,1\]
**Output:** true
**Example 2:**
**Input:** root = \[2,2,2,5,2\]
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `0 <= Node.val < 100` | null | Array,Hash Table,String | Easy | null |
134 | guys babybear4812 coming at you one more time today with another oldie but a goodie it's the gas station problem number one three four uh this question is currently as of uh fall 2020 being asked by amazon google microsoft facebook uber apple bloomberg so a lot of the big guns have picked it up it's an old one but it's clearly still being asked and i thought it was interesting because like most of the problems that i choose there's a um there's kind of an intuitive way maybe you want to dive into your first time around but that's not always the optimal solution there's one little neat trick to get you right over the line and so that's why i wanted to cover it if you haven't tried already pause the video give it a shot come on back you all know the drill by now so this question essentially says their n gas stations along a circular route where the amount of gas at a station i is gas of i we also have a car okay so we have a car that's got an unlimited gas tank and it costs cost of i of gas to travel from station i to its next station i plus one okay and we start a journey with an empty tank at one of the stations and so it says we start with an empty tank at one of the gas stations it doesn't tell us which one the question will essentially be tell me where we can start all right if we can at all it says return the starting gas stations index if you can travel around the circuit once in the clockwise direction um otherwise negative one they tell us also there's a solution that's unique uh both inputs are non-empty they have both inputs are non-empty they have both inputs are non-empty they have the same length and each element in the input array is a non-negative integer so input array is a non-negative integer so input array is a non-negative integer so we don't have to do any error checking we're given legitimate inputs now we're told that this is a circular road if you will with certain gas stations and we need to see if we can do one full loop around clockwise right i think i said clockwise uh yes in the clockwise direction so if you were to start out i'll call it gas station or gas station zero you can fill up one unit of gas from you can then drive three unit three we'll call it miles it's called you know gallons and miles so you can do you know one gallon of gas and then uh drive three miles but rather that's a stupid analogy that's not what it's saying at all you get one unit of gas it costs you three units of gas to leave and get to the next place all right sorry my brain's all fried today um if you can fill up one unit of gas but it would cost you three units of gas to get to the next place well that's not gonna work out also well because you know you're gonna lose all your gas before you get there um basically what their point is that the output here in this question would be three and the reason it'll be three is as follows if we started at index three right here we could fill up four units of gas all right and it would cost us one to make it over all right so let me maybe i could write these down and walk through the example where we're given one two three four five and we're given three four five one two all right three four five one two okay so this is gas this is cost and if we start right here right we're going to have essentially we're going to gain four units of gas so we're going to say plus four and then we're gonna lose one getting to the next town okay so now we're at we've netted three we get to the next town over right we're gonna gain five more units of gas but it'll cost us two to get to the end so until it'll be three plus five minus two will leave us at six all right so i know the math doesn't really check out here leave us at six we're now sitting at this town we're gonna gain one unit of gas and lose three to go over to the next town for the next gas station so we're gonna gain one that'll be seven we're gonna lose three that'll give us four so we're now at four now we'll start at two we're at this town excuse me we're going to gain two and lose four we're gonna gain two we'll be at six we're gonna lose four we'll have two finally we're at this town so remember this is where we started okay this is our starting point right here now we want to see if we can make it just over the edge and make it right back to where we started so if we have two liters or two gallons whatever in the uh in the tank right now two liters uh it caught we can fill up three but it'll cost us five to get over meaning that we'll go see we'll go from two we'll get to five it'll cost us five to get there after we fill up so we end up at zero however we did end up at our destination and so that's why we're going to return this starting index now and that's pretty much you know everything we kind of got to go through in this case over here there's nowhere you can start that'll actually allow you to do that because wherever you start you're going to lose more gas than you would have filled up and it's just not going to happen so how do we actually solve this problem well there are two trains about all i'll walk you through what i think is the more intuitive one the one that i tried the first time around and it worked but it was a bit of a longer solution so it wasn't very efficient wasn't it wasn't very efficient what i thought to myself was the following i thought well if i've got the gas and the cost at every given point surely i can you know create a new array called net right so what's the net gas that i'm getting at any given position and so i you know i figured here i'd have uh well i'm gaining one unit of gas one liter i'm losing three so here i've got a negative two game i would get one but i would lose negative two so i can't start here like it's just it's not possible right so that's definitely not an option same story over here i gained so i'm starting at zero by default from the question if i gained two liters and then spent four i would be again at negative two and that's no good three and five same thing once again net negative however once i come across this count here i notice that okay well i'm getting four and it's only gonna cost one to get the next station so this is an option for sure and then same thing over here i'm getting five but it would cost me only two to leave so i'm gonna get the three so what i did was i calculated this net array and basically started iterating through the same if i'm looking at an index i'm looking at this index over here if the gas is not negative i can't do anything i'm looking at this that gas is negative can't do anything net gas is negative can't do anything once i get to the net positive place then what i figured what i wanted to do was to say let me do a simulation here so now that i'm doing and walkers i'm going to do n more of them every time to try to simulate the actual path and jumping from one to the next and so what would essentially happen is i've got a net gain here of three and then that gain here of three and then when i start looping back around from the start i lose two so these gave me six here i lost six i got to where i needed to because at the end i had no gas left but i made it i wasn't in the red and so that kind of simulation works and it you know if i'd urge you to give it a try to code that out yourself it's not too bad um it's a bit involved and you know ultimately there's a much cleaner way to do it that's the way that i want to show you so what we can do actually is uh is we can do this in one pass so we can actually do this entire thing in one pass and there's one piece of information that we need to realize in doing it in one pass and this is what that one piece of information is and i don't think this one is obvious at all no matter where you start from okay no matter where you start from your goal is to touch every single gas station here there are five gas stations no matter where we start if you start here you're gonna have to loop all the way around and come back here at the start again if you start at index one you're gonna have to go to the end and then jump over here back to the next one every single time you're taking the same steps meaning this net calculation kind of holds no matter what right so no matter what happens the total net gas we gain and release or spend i guess or whatever it costs us that number is the same no matter where we started so one thing that we have to notice is simply going to be if our total net gas if it's less than zero then we're going to say not possible okay so if our total net gas is less than zero it's just going to cost more than we're ever going to gain no matter where you start it's not going to happen and so one way to do this is you know check for that and then if it's like okay it's not zero let me try to find the next starting point that works but again that would kind of be like a two pass solution we want to try to do this in one pass so again the crux of it here is if you can understand that the full net gas doesn't change no matter where we start from you're almost there the next thing we got to try to do is to then say at any given point let me keep track of my current gas i also start here and i said i'm going to fill up here and leave to the next time what's my current gas situation going to be well if i do that my current gas is gonna be at negative two so that's no good so that means this is not a starting point all right it can't be a starting point if i go to and this by the way i'm doing this all my first pass right now so we can even you know we don't i'm not even going to calculate this sorry i'll leave it here just visually so maybe i'll separate with the perforated line but i'm not going to be including this in my solution so this one over here clearly didn't work and then i tried here and i told myself okay if i was to have started here my current gas starts at zero um and now well i fill up two i lose four i'm not negative two so that's not gonna work my current gas is like negative i'm gonna you know burn out halfway through i'm not gonna have any gas left i'm gonna be stuck and deserted in the middle of the nevada desert and that's bad news bears we try the next one same story over here now we check over here all right so we're checking over here and we realize okay my current net gas is positive and every single time by the way every single time we're failing at one of these we see okay this can't be my start let me try the next one if i start over here and i set my starting point over and right now i'm at index three i realize okay my current gas is positive let me keep going i'm not going to move my starting point while my current gas is positive if at any point down the line maybe i have another stop here and i realize like i'm just going to lose so much i'm going to be a negative gas if i start here then i can say okay none of these starts would have worked for me because no matter what i would have lost at the end of the day my current gas would have been negative and so whenever we're going to drop this and like i said um that current gas as long as our current gas never uh never goes negative then we can actually leave the starting point where it is and we can keep on going through the end of the array we're gonna make one whole pass through the array and then if our neck has a zero we're going to return negative one right we're gonna return negative one otherwise what we're gonna do is we're gonna simply return that starting point that we actually had and that's gonna be about it so i know we're almost 12 minutes here into the explanation itself the code is going to be really simple so i wanted to make sure that this made sense let me know in the comments down below if you guys have any questions on the logic behind this one i think it's kind of intuitive but it's a head scratcher like i really had to sit in and think about this one when i saw the solution and tried to like try to internalize it but anyways like i said drop the comments if you haven't and uh otherwise we're good to go and let's take a look at the code and see what we can do from there so like i suggested at the start we would have we'd have to take care of our or we'd have to track our total gas or current gas in a starting position so obviously total gas equals zero current gas is equal to zero and as well we're going to have some start position um and i'll say start also equals zero just by default we are going to have some sort of for loop sorry i'm going to be luco's here and at the end of the day once we go through this whole loop we said that we are going to return the starting index only if the total gas ends up being non-negative if the total gas is non-negative if the total gas is non-negative if the total gas is negative that means it will cost us more than we're going to gain and we can't get to the end no matter where we start so we're going to return the start if it's actually a feasible trip otherwise we're going to return negative 1 because of our instruction so it says that to output negative 1 right here otherwise return negative 1 if it's not possible so otherwise we're going to return negative 1. now we said we're going to do this in one pass so all i'm going to do is just going to set a standard for loop and that's going to walk us through the length of these arrays and both of which again we were kind of guaranteed that they would be equal so let's say for ion range and the length of gas and that could have been cost as well um what we want to do is we want to always be adding to our total gas so we want to add the net result of how much we're gaining and how much we're losing on our both our total gas and our current gas so we're going to see that total gas plus equals gas of i minus cost of i at every step of the way i'm going to say how much gas can i gain and then how much gas is going to cost me to get to the next town we're going to be tracking this perpetually as we go and at every step of course we're going to do the same thing with kergus excuse me with current gas as cost of i and then once we do that at every single step we need to ask ourselves am i still good on gas right i do like do i have enough to get to the next spot so rather let's ask the converse am i in trouble if i'm in trouble i realize okay i can't start wherever i said i was gonna start so i need to move my starting point if i'm in a bad current gas situation right now i'm gonna have to say if curve gas is less than zero then what we're going to need to do is two things one is to say okay this is like no bueno let's reset current gas is back to zero because i'm not starting there anymore moreover oh everything up to now this whole situation is so rad we've been on this track this section of the road trip is not gonna work i can't start at any of these places because i'm gonna end up with the negative current gas so let me try the next spot over or for you guys sorry this whole section was no bueno none like not this gas station wouldn't work the previous ones wouldn't work i can't start from any of those all right let's turn a new page let's start from the next one and see if we can do it there so what i do is i'd set my start equal to i plus one and really as long as i haven't made any really dumb mistakes this should be all the code i'm just going to run it really quickly to make sure that i haven't made any mistakes i'm going gonna submit it here and there we go performs super well like i said the code was really short here but i think it was still a good problem to wrap your head around this idea of like again i'd argue that the part that's the least intuitive is the fact that our net gas purchase and gas spent always ends up being the same number no matter what and so that's going to be the deciding factor and if it's possible or not the way we decide if it's possible or not is by actually determining how much current gas we have at any given point if that goes negative then wherever i started is no go we got to start from somewhere else and that somewhere else is going to be at least where we were plus one step ahead and we might have to drag that forward if we kind of keep getting into trouble so i hope that makes sense i hope this was helpful to you guys yep excuse me any other questions you want me to answer let me know down below if you have any questions on this let me know like comment share subscribe i don't want to be one of those guys but it would mean a lot like i each my subscriptions it really does mean a lot it makes me happy when i see them and i really hope that i'm helping you guys here with you know at least in iota so that's it uh and i'll see you guys next time peace | Gas Station | gas-station | There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique**
**Example 1:**
**Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\]
**Output:** 3
**Explanation:**
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
**Example 2:**
**Input:** gas = \[2,3,4\], cost = \[3,4,3\]
**Output:** -1
**Explanation:**
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
**Constraints:**
* `n == gas.length == cost.length`
* `1 <= n <= 105`
* `0 <= gas[i], cost[i] <= 104` | null | Array,Greedy | Medium | 1346 |
130 | Loot Hello Everyone Welcome To My Channel Today 17.3 Problem Is Remedy Issa Gaon 17.3 Problem Is Remedy Issa Gaon 17.3 Problem Is Remedy Issa Gaon Intuitive Who Don't Tanning Correction Kar Actor Who Did All Reasons Why All Goals In To-Do Example Which Acts After Running In To-Do Example Which Acts After Running In To-Do Example Which Acts After Running Function Mode Ko Switch Board The To The Direction Which Knocked Change Social Media Mode On The But Not Least Not The Water And Not Connected To No A Phone In Water Will Feel To Not connected to the self to subscribe like Share and subscribe the Video then subscribe to the Page if you liked The Video Hair against first in the first row and last row and the first column last problem solved wine depot on Thursday civil defense and converted To Islam and will give for directions from this lutab skin subscribe voters and converted to and subscribe the Channel Please subscribe Thanks Lucknow will revert back temporary variable the various science paper and converted into a very simple problem subscribe implementation first day of subscribe to the Video then subscribe to the Page if you liked The Video then subscribe to The Amazing 1208 Sexual Number Running From Different Subscribe To China And This Is The Volume To Subscribe Will Spread In The First Chief I That NDA This Is 545 Drishti Yet It Is Difficult For a Difficult to Enter in Adheen Dhoy 900 Mode On Kar Ki And Boy Should Also Be Greater Than Or Equal 10 And Why Should Also Be Electronic The First Number Of Columns And Did Border Of Call Me Ishta Devi 209 The Character Revered Character Of The Days When will replace the current from water board access oil gauge temperature actor this is pain will definitely give one plus one that third stage Condition which is in place to return is second and basic implementation of defiance to dare solve already called for differ on we can also all the same for disaster in 10m air chief half minus one Maa Kamakhya Yagya in which is equal to character to end Cold Face Lifting Board And E - 110 Default Subscribe For The And E - 110 Default Subscribe For The And E - 110 Default Subscribe For The First Time And Distance For Last For Two Years For The Calling Subscribe Number Of Eggs Subscribe Is Very Rare Condition Here Egg Subscribe And Have 9 B Last Column Is Special VPN - Of Have 9 B Last Column Is Special VPN - Of Have 9 B Last Column Is Special VPN - Of Birth Sexual Plus And Minus One Servi White Hair - 150 Blast To Subscribe Now To All Subscribe Point Ideal Place For Pimples To 10 Plus Turn Off That Eye Comedy Pimples To Videos Bizarre All The Question Vighn j2j Is Equal To That X Service With Another Thing Being Replaced Back Cover Peeth Ghiskar Actors Piss Video Android Medium High Court The City Has Compiled And Were Getting Correct Answer So Let's Try One More Kasam Test Case For Different Research Soft M Trying To 2000 Replacing This Too So Let's Seal Sudhir And No Will Replace With Solution Introduction Accepted for the time complexity of this software this is the biggest building all the time complexity of mode of a main where am is number of romance and is number of which pulp columns and space is festival se space complexities of me india not writing all extract Fiction College Thank You Felt Myself Please Like Share and Subscribe My Channel | Surrounded Regions | surrounded-regions | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Explanation:** Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
**Example 2:**
**Input:** board = \[\[ "X "\]\]
**Output:** \[\[ "X "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is `'X'` or `'O'`. | null | Array,Depth-First Search,Breadth-First Search,Union Find,Matrix | Medium | 200,286 |
342 | this is power of 4 lead code challenge 342. giving an integer n we have to return true if N is a power of 4 otherwise we have to return false an integer N is a power of 4 if there exists an integer X such that 4 to the power of X is equal to n an example is here we can have 4 to the power of 2 this is 16 so we can return true 4 to the power of 0 is 1 4 to the power of 1 is 4 and 4 to the power of 2 is 16. so here if n is 5 we have to return false and then here we can have 4 to the power of zero and we can get one so if n is one we have to return true according to the constraints the value of n is anywhere between negative 2 to the power of 31 and positive 2 to the power of 31 minus one um here they are challenging us to solve this without any Loops or recursion but that's just a follow-up so in my that's just a follow-up so in my that's just a follow-up so in my solution here I'm going to use a while loop and then perhaps in another video I'm going to show you an alternative way of solving this challenge without using any Loop but for today we have a loop so the name of the function is power of 4 is taking an integer so the name of the function is here is power of 4 this is a Boolean function returning true or false and here is the parameter that we need to evaluate so my first condition is that if n is either 0 or a negative value there is no value of x here that can satisfy this condition so we can return false another thing if you look at the constraints here they give us the range using 2 to the power of something but powers of 2 are 2 times slower than powers of four so if they say 2 to the power of 31 then the maximum value we can reach using a power of 4 will be 4 to the power of 15 because 2 to the power of 30 is the same as 4 to the power of 15. so we can't reach this value anyway exactly using a power of four so I'm having this I variable here that I'm starting at zero I could call it X like I did in my previous videos but basically I here corresponds to X in the instructions so I'm going to check here from 0 all the way to 15 to match the constraints here and at every iteration I'm going to raise 4 to the power of I and verify if it's equal to n so here I'm testing for this condition if it's true I'm going to stop everything and return true here so the function will terminate otherwise if it's false I'm going to increment I by 1 and keep checking so 4 to the power of 1 then 4 to the power of 2 and so on all the way until 15. if this Loop terminates it and we never return anything it means that we have to return false because whatever n has as the value that was not a power of 4 so we have to return false so that's it for this solution let me run this code we pass the sample test case now when we submit it we've passed all the various test cases in zero milliseconds making it a very fast solution if we click on details we see that we had over 1 000 test cases if you like this video you like my tutorials and my Solutions and you want to practice more coding interview questions please subscribe to my channel and I'll catch you next time | 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 |
129 | hello guys this is expert Wanda and today we are going to see the little question that we have today is 129 and this question is uh 129 some root 2 Leaf notes and leaf numbers so you are given a root of binary tree and that containing uh this is from 0 to 9 only okay we have digits and that is 1 0 to 9. each route to leave path in the you can say tree representation tree represents a number okay so each route to Leaf path in the tree represents our number okay next for example the root to lift is one two three so one is root and two three each leaf and represents the number one to three return the total uh sum of all the root release numbers and test cases are generated so that the answer will be 15 to 32 which integers and this Leaf node is a node with no children Okay so in this sense it is saying that we have this root this is our root node and this is our Leaf Node 1 and this is for Leaf node 2 okay sorry clear if not o and leave it true okay so these are Leaf node so you can see that and how we will represent this that we will talk about later so it is saying that we have to uh represent this into the number and then we have to do what uh these numbers should be fit into 32 bits and number okay so we'll come to here again and we'll try to implement this one so first of all let's suppose uh if someone is given like this low one behavior and two we have given three and one is uh this is our root node and this is our Leaf node style so first to form one to two there is one One path is one two okay this is root node and this is our channel from one to two so if you really represent this one into a number so it will be convert one two similarly if we'll go from one to three it will become what uh one three right and if you do the sum of these two so it will become 25 correct and this should be your answer right as you can see now we will talk about another example that we have here is uh four we have and so now we have nine we have 10 we have right and so rigid API and this is 5 we have and one over here okay so if you go from here to here right so it will convert 495 okay we are going actually from here to here first time so 495 we have next time we will go with what 4 9 and 1 because this is double Leaf children okay so it means we are going to from here to here okay so it will cover four nine one next time what we have we will have only one path this path is left right so we'll go with one zero so it will convert 4 0 it will do the sum it will become six nine eighteen and uh to 20 and 222 32 2 right and 4 and there is what uh two right so become 10. so this will become one zero two six right answer now if we'll talk about uh constant right so the nodes of notes of the uh in the trees what range into two one to one thousand and value will be 0 to 9 of the node value okay this is it this is so this question is very important because this question has been asked in the Facebook multiple times and slowly Google and apple Amazon Microsoft all the other companies also asking these questions so you can say this question is very important for the interview purpose right so topic is touching the uh you can say topics that is tree DFS my research you can use right so similar question you can uh see in on the lead code that is a path sum minority maximum person and smallest string starting from the leaf if you're not able to find this question please bring in the comments okay let's go to the uh solution okay and they will try to implement this one okay so solution if we'll talk about the solution over you right so there are uh you can say uh 3DF space to uh Traverse the three right and we know that DF is uh only right if you're not aware it you can do some Hands-On using the DFS can do some Hands-On using the DFS can do some Hands-On using the DFS algorithm okay so there are three ways of uh you can say DFS to Traverse to the tree that is we have what uh pre-order tree that is we have what uh pre-order tree that is we have what uh pre-order post order and pre-order right if you post order and pre-order right if you post order and pre-order right if you know what DFS it is what the first way is uh to implement what pre-order right is uh to implement what pre-order right is uh to implement what pre-order right pre-order it will be order and then pre-order it will be order and then pre-order it will be order and then another is uh you can say post order and third one is what in order correct okay pre-order post order and in order okay pre-order post order and in order okay pre-order post order and in order and if we'll talk about the pre-order and if we'll talk about the pre-order and if we'll talk about the pre-order right we know that uh first we have to go with the left then we have to go to uh right and then we have to go to uh this one right so only for the Post order is they are in order is there right so we will see yeah you can see that later okay we have to post it on this one so actually D phase we can Implement using the three ways that is free order post order and in order so in this way we will see uh clear height and you can see poster or in order we can implement this one also okay so the you can say why we use right uh what optimal strategy we will have to solve this problem right so for the optimal strategy to solve this problem right I will go to the row to Left Right first it's about if this is root tight so we'll go to the left side right and then uh root to left will go so it is called pre-order right first we'll go root then pre-order right first we'll go root then pre-order right first we'll go root then we'll go to upper left and then if we'll talk about our another things right like right and those things so this approach will call pre-order will call pre-order will call pre-order right and uh if you go to the Post order first we'll go to Left Right and then we'll go to this uh root right similarly if you go to the in order first we'll go to the left then right and then uh faster redo and then right like this so if we are going with what root and then left right from root to left then it is what it is called DFS pre-order it is what it is called DFS pre-order it is what it is called DFS pre-order traversal and to implement it uh one has to follow the straightforward strategy that is you can say root then you can say left and then we can say right okay this is the strategy you have to follow correct and so that uh since one has to visit all the nodes right and the best possible time complexity here is linear Source right so hence if you say uh all the interest here is to improve the space complexity right so there are three ways to implement reorder that is iterative recursive and models right so if we'll talk about these pre-order reversal talk about these pre-order reversal talk about these pre-order reversal right so there is three way so in which that in the iterative way you will get the best time complexity if you're the most right approach then you will get the constant space correct and if you use the recursive progress this is the simplest one to write okay so if you are in the interview I will suggest you use the simplest one because it is easy to write okay what you have to see the what do you need the time complexity you need best time complexity need constant Express need and best way to write the program you need right so we will see the iterative approach right first because this is the best time to complete guide and will try to implement this one so if we'll talk about the identity pre-order traversal right so identity pre-order traversal right so identity pre-order traversal right so here we will here we can say will uh how will do the implementation right of the three Auditors you can say okay with hashtag first of all we'll push a root onto the stack let's suppose if this is a stack right let me see open so we'll first of all we'll push root here okay then what will happen while the stack is not empty we'll check the stack is not empty will pop out a node from this type we will remove we will get it about or from here and we'll check and update the current number right if there is a node in the leaf right which means there is a left or right so we'll update the root 2 leaves and we'll do the sum right and we'll push right and left children put into the state so only one here probably if node is leave right if this is if we will post another thing I will check if the node is leaf node then what we will update root to sum row two Leaf sum okay so we'll update there and similarly if we will push right and leave uh left children into the stack and we will return the root to leave sum we will to have to do the sum and then we each time we will update it okay so what we have to do first of all we have to push onto the we have to push the root into the stack and while stack is not empty we'll pop out the node from the stack and update the current number okay and if the number is just if the node is leave then what we will do we will update the root to leave sum and if it is right we'll push right and if children onto this type and we'll update the same thing again and again okay so if we'll talk about what I'm trying to say let's understand this so we'll take a root 2 left Leaf node right and we'll take one current number okay so I'll take one int uh there is a we can say root to leave okay so release okay root two leaves will take and uh do that we say root 2 leave also okay so we have root 2 leave and this is nothing whatever what zero and if we'll talk about another one is current number right so we'll take int current number like this and this is what we have 0 and we will update each time current number right so to do that what we will do we will take up here of three node and its integer right so and we have to take in the queue right so if we'll talk about array Q array DQ it will take a ready queue and it is what we have let's suppose you will take in the pair right so I'll take like this only so it should have appear it should have into appear and that is known onto the stack we will add on to this type and this query will take what a pair of three node and its number right so let's what I'm trying to say we have pair class and in create class will take what three node and this pair will go to where onto DQ right so we'll take DQ I will add on to here right so DQ will take what DQ will take this pair of our tree node and integer and that is called our stack I think we are good now what we should do will uh add a root onto the stack so to do that we will take stack dot will do push right and then we will add what uh new pair we should add and this pair is nothing what that we are doing right root will add and another will do at what zero any series that we have seen right root was 4 and then its value is 0 right number zero so we have initialize this one now what we will do we will uh do the traversing it how we will do that we'll check while and we'll check not null is empty his employment method and we'll check if the stack is not empty then we will go with what uh we'll take a pair and that pair will be nothing but what dot will do for and we will get this pair and this page is nothing whatever what this viewer we are getting forward this pair this speed will get from here right and we will say like this okay now if we'll talk about the once we will get the pair right what we will do we'll say root and P Dot P dot get value you will get your root value right you have got your root value P dot get and then you will get the from the pair we will get the value from peer value you can see okay next time what we will do um we should check if the root is not null right if root is not no means we have some value then what we should do we have our current number right on the current number what we'll do current will apply this formula current into first of all we'll multiply with 10 and then we'll do root Dot value so that we'll update our current number each time correct so if it's a leaf number we will update our root to leave sum right so what we'll do we should check if root Dot it's left kid have some value right or it's a not null um is null right if it is null and so we will similarly we should check with root Dot write one and if it is equal to null means both are Leaf node right if both are Leaf node then what we will do root 2 root if we have right and this root to leave will do plus what our current number We'll add on to the current number We'll add correct now what we do what we will do if these are root lift current and this one okay left and right so we'll update our route to here if this is not then we should add on to the stack right if this is the leaf node then we will find our uh we will get the root number current number and we will add on to the root Leaf right and if this is not uh you can say Leaf node then we will not update root to leave but we'll update onto the stack I think you've got so let's add on to the stack what we will do we will say nuclear and then we'll add this one like this but here what will happen here is what where will come from what root Dot left correct and on to the integer this one it will become what it will come uh you can say current number right current number why it is giving the error because we are taking this one but we will take this one because we are taking construct of this one okay now this will work okay similarly we'll take this one and we'll add here okay here we'll take right okay so if left and right is not leave right so here if left if leaf node and if not found if leave node not hot okay then we will do these things okay I think understood once these are done so we'll complete our else then we'll come to our you can say while loop and then we'll come to our this one you can say now uh method on right here so before that what we will do we will return here turn what root to leave so let me summarize this one so what I have taken first of all I have taken a method name and that is a sum and it is taking root will take we have taken book Leaf then current number so we have added a stack root onto the stack sorry I'll run the stack then we have what we have did a root Vapors and then zero we similarly we'll get our root and after doing the pop and we'll check on to the uh if it is not null we will find our current love data current number if this is root leaf or if this is the leaf nodes we will find our root to leave and similarly we will find our stack value stack dot push will do if it is not leave nodes and finally we'll get our row to leave okay so I am getting what p is uh root value right now sorry this would be key okay this would be key value function contains value as a en value okay so I'm getting errors meeting at 145 25 should be the answer okay so let's understand why we are getting here error um mm-hmm mm-hmm mm-hmm first of all what we have did let's start from here first we have taken this uh we can say uh this one right then we have taken what these variables then we have taken our wild condition in this wild condition we have taken these conditions then we have what uh um if this is root null will not completed here but will come to here okay this is the thing if this is not null correct and then we will do these things okay let me do 25 okay so if this is if this uh is not right if root is not null then we will do this one and if this is a Leaf nodes right so we'll do this one if this is not the leaf node then we'll do um root total right and current number root Dot left and left uh left and right okay so actually here we should do first we'll go to the right first we should go to the right I think yeah and then we'll go to the left 135 is coming what I'm doing is check okay I got it we got our root right we got our root but we have not updated current we have to get our current also right current is will take from P dot get key get value mm-hmm mm-hmm mm-hmm how can I do this mistake yeah let's submit yeah see you tomorrow so why we're getting the mystery word we have updated our route right but we have not updated our current number so if you'll do this update so it will work okay so first we have taken the root leaf and we'll up we'll return this Loop rootle collector so after before after that what we will do we have taken the stack and this stack will take a pair of root note and integer we will push the root first and then we'll get the row I will do the pop and we'll check on to the you can you find our root and parent number we'll check if the root is not null then we'll find our current number using this formula into 10 and then plus where root value then we'll check if this is low uh Leaf nodes and we'll update our row to leave and if not then we'll update our Stacks right like this so that's all for today so if you talk about the time complexity right if there is total number of node is n right so it will become uh right here so time complex to become what o of uh n right if n is the number of nodes right so uh we because we have to visit each node right and if we'll talk about the space complexity right so it will convert if yeah the till the height right so height of if H is the height right so we'll say o of pitch right that's all for today thank you so much guys thank you so much | Sum Root to Leaf Numbers | sum-root-to-leaf-numbers | You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`. | null | Tree,Depth-First Search,Binary Tree | Medium | 112,124,1030 |
316 | hello everyone welcome to myu programming Club today we will be solving another daily lead code challenge and the challenge name is we move duplicates in letters so you are given a string s and you have to remove duplicate letters so that every letter appear exactly one and on once and only once so for example in this string uh B is repeated twice and C is also repeated twice and in the resultant string all the characters are appearing only once so also it is further mentioned that if there are multiples such answers you have to return the smallest lexiographical order possible among some results so for let's consider for this particular string in this particular string you are having two options either you could have deleted uh let me Mark the indices one two three and four either you could have deleted this 0th index B or you could have not deleted this one and instead of that this one would have been deleted so your resultant string let's say in C let's say you deleted this your resultant string will become BCA which is not the lexicographically smallest possible so you can do better than that so uh how we will be doing uh finding the lexicographically smallest one for that what we will do is let's say we will use a stack and another list visited list or say array whichever uh you are comfortable with uh it depends upon language to language here in C plus we will be using vector so what we will do is this array will show the visited uh characters that have been used or say visited there have been included in final answer or say string now this tag will be present the final string that you will be forming in reverse order instead of storing the character what we will do is in both of these uh data structures stack and this visited array instead of character we will store the relative difference of character with small a so it will be for example for B it will be one for let's say a it will be zero so let's say c it will be 2 so on and from 0 to 25 uh your difference will be ranging from 0 to 25 so in total 26 values will be required to represent these differences let's call this character differences and the whole stack will be called character difference tag and let's begin now what we will do is uh we will iterate the string from left to right initially you will push to be in the stack since it's empty as of now we will not be opposed uh it's a relative difference uh with a small letter A will be boost because the in the constants it's mentioned that lower English let us will only be present in the string and the Order of the string will the length of the string will be your order 10 is to power so what we will do is we will push B now uh we will be visited uh also before proceeding further let's mark the indices they will be required and another data structure I would like to introduce which will be used is a vector or say array storing the last index of every character so for B its last index of occurrence is three or C its last index of occurrences for a last index on the and the only index is two so this is how your values will be stored so for a b and c A to B 3 and c will be 4. so what you will do is let's say uh now you will check if the character that you are going to push on the stack is greater than the top of the stack yeah it is the case that the character we are going to push on the stack is greater than the top of the stack so we'll push the character and we will move our pointer to the next character let's say this one okay now when we move to this character we will see uh that c is greater than a so the top of the stack is greater than the current character that is we are considering for pushing on the stack so what we will do is as long as we can adjust this C somewhere else what I'm what I mean by adjusting is that another the last index that at which C is opening is greater than the index of current character last index at which c will occur is 4 so we can leave this C and tickets last occurrence which is beyond the current index uh this is your current index so it will help us to gradually build the smallest lexicographically smaller string because a is smaller than C so we can place it before c provided C is having our friends which is at a index greater than the current index is 2 so C is also occurring at this place so we will remove this similarly we will do for B so B is also greater than a and B's last occurrence is three as of now B is zeroth occurrence is pushed on the stack so what we will do is so c will be removed from the visit redirect see uh C is no longer part of the string so also as we see B is greater than a and its last occurrence is greater than the current index which is two so we will remove it from also from the stack and subsequently we will remove it from the visited array also so these are not visited as of now only a will be pushed so it is visited as of now so V is greater than a so it will be pushed now B is uh greater than C is greater than b so it will be pushed now let's say further there are some other words also b c a these will not be pushed why because visited array is already containing them only one occurrence of each character is allowed and we have already pushed and we have built the smallest possible string which is having only single occurrence of a character so it will be in reverse order ABC I hope you are able to understand so we will try to take the smallest let me quickly change the slide we will try to just a minute yeah we will try to take smaller characters towards left most possible place now let's say let's consider a condition uh that this C character was not there I know it's a little messy oh let's say this is not here so you could not change this C because it is not having any other occurrence you have to put it here itself so you cannot Pope the values of c so this is the case in which a character is cannot be adjusted so this is the logic of the problem and the one time complexity will be o of n where n is the size of the given string and the space complexity will be also order of n where n is the size of the string it will be required for your stack and those two vectors already is so let's have a look at the implementation approach will be more clear to you in the implementation part in this particular array or say vector we will store the last index of occurrence foreign character and one thing to be noticed is it is to be noted that reduce the size of the arrays uh required to put characters we are taking relative difference of each character with smaller as our index in last index array and visited our both of these so this last index will store the last index of every character and last indices will be used to see if we can adjust the greater character at the end uh last indices will be used when uh smaller character appears after a greater character and we have to check if we can adjust those larger characters at a index beyond the index of smaller character foreign to build the smallest character possible this is this one is the all Intuition or logic so after storing the last index this is the relative difference of the character with a that I am mentioning here or you can move it so here okay then visited array will be used to it will be used to avoid duplicates in the resultant string and last is which inverse the same the simulation that I have uh demonstrated you for this particular string so if you encounter a empty stack or say a known empty stack with characters larger than the current character and those characters those larger characters can be adjusted after the current index then keep popping the values keep opening those well those characters from the stack and this is how you will be building your final resultant string and this is how you will be building your resultant string so that's pretty much it and at last you will reverse the string before returning it since in stack it will be in upside down manner at last you will return the string as we was after reversing is let's try to submit it once as you can see it's getting accepted so if you are still having any doubts please feel free to ask them in the comment section code will be available in C plus and Java both so thank you for watching thanks | 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 |
452 | That Hey Guys Welcome Channel White Udayveer A Problem Call Minimum Number Four Equals To Forget Problem That Comes In Various From Interview Video Problem 28 Without Status Minimum Number Of Meeting Rooms Spider-Man Uber Number Of Meeting Rooms Spider-Man Uber Number Of Meeting Rooms Spider-Man Uber Of Nations For Its Students Call Minimum Number Of Every Five Wickets To Control Side Subscribe Please Subscribe This Channel Problem Solve Marriage Sanskar Friends Play And 120 Dars On Ki And The Question Shezwan Jain Adi Festivals Dotted Lines To Balloons To Oriental Wed 29 Aug 09 2010 Vertically Upward Direction Is The Shooting Dec 19 2010 Position Subscribe Position A Little Boy Status Pallu Hai Natwarlal Sabs Iss Par Vishwas 80 Part Of The Year Or So And For Example Bihar From This Point To This Point Please Enter Your Location Of The Distance And Subscribe 269 subscribe to subscribe our YouTube Channel and subscribe the Channel Please subscribe and subscribe the Channel subscribe 6 Problem Stamp Vendors Invented This University 1121 1080 Boys Will Not Understand 200 Grams The Two All So Let's See Who Can File A That Solve This Problem In 24 Hours Will Follow Giridih Approach To Where Is Pay Volume Minimum Maximum Return Problem Superintendent Hai Shanti Dynamite Bhi Agni Problem Solve Person Door We Are Going To Pickup The Phone Tune With The Earliest And Will Start From This Point Now Room 9.00 Subscribe News One Example Points Of Side Effect Control Please Subscribe Us 900 Unauthorized Gemini Airplane Solves Balloons and Avoids Soft Ambient Android Clear 100 Years Boys Sauveer Win The Number Three And Not Willing To Give Way To Find Out Which All Subscribe And Share On Sent And Updated On Other Channels Best All The Volume Tower Start Exploding 100 Oil Co 514 So Let's Bulb Scorch Indian Roads Will Come True For The Number Four Books For Class Seventh Day Of Starting Point In The Same To Point Se 2.5 Will Do And 212 Others And Will Not Subscribe To That Grandma Shaitan 98898 Start Point Of The Current Balloon Is Green Earliest And Points Will Update Aryans And 128 And Will Trust Matter ₹100 Note I Left Hand Next Will ₹100 Note I Left Hand Next Will ₹100 Note I Left Hand Next Will Get 9 Votes Will See The Stars Current Bollywood This Current Affairs In This Will Be Lost Souls And Comment It Well And Would Also Request 2021 President Solution Waqt Example In And Around For This What Is This What [ Around For This What Is This What [ Around For This What Is This What Should Return Should Return Should Return Solution 810 Subscribe To 56001 Point Are Suno Point Se Reserving Ise Jahar Winning Are Two Sides With 300 Bones But And Daughters From This Is This Thank You Can Set Them In To- In To- In To- Do List Bluetooth Setting On The Con Is On Is Point To Subscribe The Points Yuvan Adhura Dashain 2070 Pims Videos Current In Points Know When To Walk Through It's A Gift For Ourselves From All The Best Current And Travels and Tours Point This Point on Pimples Current and Take No Weir That 6000 Years But Not in the Number of Weirever Current and Only Man to Start from Current and Don't Like This Towards Chut Center Point Stop This Point Forced Start Point in Points Wanted The list is requested for you dare not want to update the number of years and not brought to front end Points Idioms Appoint Soyenge Example Effect This Example Comes Up with the Stars This Current Balloon is Great Dinner and Condition to Attend Ki Andhe Updater Current and Points Withdraw in President Withdraw from 2nd ed m ed 2nd ki Subscribe Switch on the number of crops and solution Let's get a ki kya tak ho ki addressed huge minimum number of requests for user balloons and important questions for preparing for technical interview Safed Cellular And You Want Something Dedh-Dedh Please Like Share With Want Something Dedh-Dedh Please Like Share With Want Something Dedh-Dedh Please Like Share With Your Friends And Subscribe Our YouTube Channel And Fear Print Out From Its Always Near The Calling Problem Bank Government Will Open A Country Club Cutting And All Smiles At This Time Is Unique Time In Some rise | Minimum Number of Arrows to Burst Balloons | minimum-number-of-arrows-to-burst-balloons | There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_.
**Example 1:**
**Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\].
- Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\].
**Example 2:**
**Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\]
**Output:** 4
**Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows.
**Example 3:**
**Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\].
- Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\].
**Constraints:**
* `1 <= points.length <= 105`
* `points[i].length == 2`
* `-231 <= xstart < xend <= 231 - 1` | null | Array,Greedy,Sorting | Medium | 253,435 |
382 | Hello friends today I'm going to solve liquid problem number 382 linked list random node so in this problem we need to implement the solution class has two um functions the first function is solution linked node head and the next function is get random function so basically this is a Constructor function and this is a function where we are going to get a random node from the linked list so in the Constructor function in the solution function here we are going to initialize our linked list object so we will be given the head and argument and we need to initialize the linked list object and then from get random we need to get a random node from the list and the possibility of probability of getting any random node should be equal so let's see how we could solve this problem um basically here what we are given is in the solution function we need to create um initialize the object so what are we going to do is we are just going to um create a head of the linked list and store the value of the head in our linked list head and also in the get random um function since we need a random value within the linked list so how can we actually achieve a random value let's suppose if these were an array so um let's suppose if these were an array so what would we have is one two and three in an array right so for the array we also know the length of the area so we can just get the length of the array by if this is an error a we could just get the length by a that length that would give us the length of the array right suppose L is the length of this array then we can get the random value from this array by um multiplying this length with a random number which is in the range 0 to 1. so how is that possible how is it possible that this gives us a random number so since this value is a random number and this is a fixed number right so if we multiply any value with a random number we are going to get a random value so that's why we are going to use this formula for that let's just take this as an example since the length is equals to 3 and let's choose a random number between 0 and 1. let's choose a value 0.2 so what would this return uh that 0.2 so what would this return uh that 0.2 so what would this return uh that would return us 1.5 right so do we have a node 1.5 where 1.5 right so do we have a node 1.5 where 1.5 right so do we have a node 1.5 where of course not we do not have a node 1.5 of course not we do not have a node 1.5 of course not we do not have a node 1.5 we are actually going to take the floor value of this so that would mean we are taking the node at index one so this is 0 so this is one so that's we are taking this value now let's suppose we get a random number of um 0 point seven so in this case what's the value 7 times 3 is 21 right so we get 2.21 and times 3 is 21 right so we get 2.21 and times 3 is 21 right so we get 2.21 and since we are taking the floor value we get we take the node at index two so we take this node value and suppose we get a random number 0.5 that in that case we a random number 0.5 that in that case we a random number 0.5 that in that case we would get okay so I did this calculation wrong here this would be 0.6 which would be the node at index 0.6 which would be the node at index 0.6 which would be the node at index 0 and in this case this would be 1.5 and in this case this would be 1.5 and in this case this would be 1.5 and that would be node at index five one so we are actually getting all the random values right and all of these are in the range 0 2. so in this way we can actually obtain a random note from an error right but in case of linked list we do not know the length of the linked list right so what are we going to do is we are first of all going to determine the length of the linked list when we are actually initializing the object so in the solution function we will um also determine the length of the linked list so now let's do that so let the length initially be zero and then we Loop over a while loop while we have the heat um the length will keep on increasing and then we move to the next hit every single time so this will give us the at the length of our linked list and the heat so basically now we will take this length and find the random index for our um random get random function so what are we going to do is let a random value be equals to um method floors we are taking the floor value and we are using the random function from our JavaScript library to generate a random number and then multiply that with the length of our linked list so this will now give us a random value we are taking the floor value of that random number and then what are we going to do is we are going to find the right known at that index so while hit okay not 8 while Rand value minus so we are looping over okay so we also need the head oops I'm sorry so we have our head and now from that is from the beginning we are now going to iterate until unless we reach that node so here it goes to head that next and then finally we are going to return our head let's try to run our code and see if it works okay so I have oh actually we need to return the value of the hit all right since it's been accepted let's submit it awesome so the time complexity to solve this problem would be since we are um iterating over each of the node in the link list this would be and off and time complexity and in this function as well since we are iterating over each of the Heat this would also be an off and time complexity and the space complexity is constant for both of the functions we could also solve this problem in a constant in um of an um space complexity and of one time complexity for get random I mean of one time complexity for the solution function and of and time complexity for this one so how could you solve this in of one time complexity let me know in the comments below | 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 |
518 | hey hello there today's recording challenge question is coin change - it's challenge question is coin change - it's challenge question is coin change - it's a dynamic programming question so let's talk about the structure we have a few different type of coins that we can use to sum up a to a certain amount each type of coin definitely have a different value for this question we want to write a function to compute the number of combinations we can use those coins to a sum up to that amount so we are only looking at combinations we're not looking at the sequential order of the coins being picked we may assume that we have infinite sand number of coins for each kind the examples let's look at the one we have a total that's fine and we have three type of coins one two five there are four unique combinations of the coins we can do to sum up to five single phi2 to single one two and a three one or five ones so that's the four different two distinct the ways of combined or the coins we have to sum up to five the order of you know if we consider some combination that involves two different types of coins we can do two to one but there is no but two one two is not considered us of one unique combination the order does not matter so it's important to have that in mind when we reason about the subproblems so let's talk about let's look at this a little bit more graphically the initial problem for the example is that we have to make up a to five and we have three different coins one two five so one we are attempting to divide this into three different subproblems if we choose one so the total reduced to four we still have those three different types of coins at our disposal we reduce the Stono by two if we choose a coin to the total reduced to three and we still have those three different coins or we reduce the amount to zero by choosing a single file you know that's by that's if we try to set this three different subproblems to sum up a to the original parent problem there will be seriously problem for this here we choose one here we choose to what do you that which is another two and choose the one to reduce this total to zero so here will be one and on this branch if we choose continuously choosing two from now on after choosing the initial one this big reduced to two and now zero so the problem was setting the sub apartment to be only reducing the amount but not limiting the options of the coins is that we're going to have two to one and wanted to consider separately so we are basically topic hunting and in this case we actually in this set up we actually explicitly implicitly actually thinking that assuming that the order of coins being picked does count as a unique way but in fact for this problem it's not so there's problem in this sub power of the set up so what's the correct way of doing that so let's say that we are picking two and reducing the total to three the in the other branch we will actually want to eliminate the option of choosing two because whatever the combination that involves two is going to be the sub problem fall from the branch and on from this other branch anything that if we continue to have two as an option we're gonna have overlap with the other branch that's illustrated by this here so the set before the corrected sub problem set we're gonna form one of the sovereign we reduce the amount using the option the other branch we're going to eliminate that options altogether so that's the correct way of setting up the subproblems so just let me make this a little formulary CLE we have a month we have some options so one thing we can do is still you know have the option have the amount intact and then just pop out one of the options and the other branch is going to be the amount subtracted by the last options the order of the options being popped out really doesn't matter just for convenience purpose I'm putting it to us as if we're removing the last one or we can remove the first one - so the remove the first one - so the remove the first one - so the problem basically being broke down into two sub problems the this first sub problem is the same amount but with one last option the second sub problem is that we reduce the amount by the first option you know this has to be aligned with the one that being popped out so if we pop front we have to reduce the amount by the first option by the front coins value and to have the options intact so that's how we that's this transition formula the base case is going to be if we don't have any amount the amount is zero we return one that means we reached the we successfully reduce the amount into zero so we find one combination so that's the base case so whatever the options we have that's gonna be one or we still have some amount that's greater than zero but we run out of four options let's just use an empty cell here to indicate that then we want to return zero meaning that's it's not feasible so there's no not one but zero combinations through this searching so that's the base case all right what else run out of the choice or another one if we just choose one options that's just so happened to reduce the amount to be negative whatever the options we have remained it's gonna be zero as well so that's the three base case so I'm gonna just cope this top-down version a top-down version this top-down version a top-down version this top-down version a top-down version recursive version using some lazy man's memorization method in Python just for this make change a month and we are using an index instead of actually plopping callings so this is I here means we consider coins index I and on towards the end so that's a faculty popping out the first one the reason for that is I want to use LRU cache so for two using this the arguments to the function has to be hashable hash Bo so I think a list is not so that is why I'm using an index to indicating what options has been element eliminated in the in using this according to this formula so just gonna copy this function this transition function here translate that into code so the first branch supportin is the same amount but with one less option so that's why plus 1 the second the branch is we change among abstracted by the first available coin that's currently in our odd-numbered disposal our odd-numbered disposal our odd-numbered disposal so it's coins right and have the I to be the same still have all the options from I and all so that's the recursive relationship of the transition function and we just kind of put three different base case here so if a month I don't need this the other one actually can be combined so this is run out of the coins so eliminate all the options of coins or amount is less than zero so that's just to use this function to calculate requirements we're going to passing the full amount initial amount and saying that we consider all the options from 0 and lots of all the options this cash is going to handle whatever it is calculating some arguments and actually return a number that's going to cash that combination so putting this to us the keys and so that little when doing the recursive call it's going to use the already cached Evalia so that's a lazy man's memorization in Python so let's try to see if it works yeah all right so this is the top-down all right so this is the top-down all right so this is the top-down approach the tricky part is to have the correct some father setup it's important to realize the sequential order of how the coins are picked is not does not matter in this case if it that makes if that's that sequential order actually matters the problem is much easier so all we have is the amount subtracted by the option just for how many options we have we break that into how many branches that would be this naive kind of a setup it will be a easy level question instead of this one is a medium so let's talk about how we do this from the bottom and button up if we analyze this recursive really of the transitional function it's a two dimensional one we have the options and the amount so let's just say that the options are the so the amount is the rose and the options is the columns note that you know on this based on this transition function we have the options pop front that's basically saying that we are looking at a previous row sorry options is the current previous column and the samsam rule here is the same column but some previous rows so the immediate previous row so we're dropping one of the options here we drop in deducing the yeah it's the same column previous row some previous row here is the previous Colin Sam row so we noticed that this is actually can be compressed to be a single DP single one it's not even though it has two options but although here is the you know the Sam Colin some previous row or the same row previous Colin immediately previous column so it's a can be space optimized using a single one D P so instead of doing the 2d table tabulation I'm just going to do a lot one dimensional and if we only if we consider about the relationship here it's additive so it's not taking me a max and anything so we actually don't need to store the previous column all we need to do is just work row by row inside this Colin that was just adding the number and that would be done so we worked this Colin by Colin so Colin value by value and for each value we're looking at the different amount and just add the number based on this formula right so that would be the solution so yeah so let's do this actually to reason about this I think we should we could just transpose that so that it become a little bit more intuitive when we reason about that in 1d so let's just use a row as the yes we're gonna keep our row but it's going to be rotated to be a vector ring so the base case is going to be here zero is one and everything else is zero so Rho is the amount so we have a zero to the total amount so that's why I'm transposing that to have that here and I'm just going to doing that column by column so if I'm gonna go beyond the actual amount I should break otherwise I'm just gonna go and go ahead and updating that so this is pretty much just a function of amount is equal to function of amount subtracted by the calling value and that so it's a this but we are doing instead of dis abstraction we are doing the you know addition so it's kind of a reverse this is top-down this formula record this is top-down this formula record this is top-down this formula record it's basically the button up in the reversed ordering of how this works we are not adding another second term because that second term is going to be handled in the next iteration for different type of coin so that's that well the for the return is just going to be returning the last item there so let's see if it works okay sumit okay working too so that's a converting from top down to button up we analyze this here we realize even though it's a 2d but we can compress that into to be a single one-dimensional and so to be a single one-dimensional and so to be a single one-dimensional and so the way to think about this system this is going to be handled by the previous iteration over the coins and this one is going to be when we handle for this particular coin here all right so that's this question today | Coin Change II | coin-change-2 | You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000` | null | Array,Dynamic Programming | Medium | 1393 |
973 | hello and welcome today we'll be doing a question from weeks ago called K closest points to origin is a medium let's get started so we have a list of points on the plane find the K closest points to the origin 0 here the distance between two points on a plane is a Euclidean distance so that's just x squared plus y squared square root of that you may return the answer in any order the answer is guaranteed to be unique except for the order that it is in example 1 given points 1 3 and I give 2 to K equals 1 we output negative 2 to Y because the distance between 1 3 is square root of 1 plus 9 or square root of 10 and 4 negative 2 it is square root of 8 so in square root of 8 is less than square root of 10 we return negative 2 to the second example given points 3 5 negative 1 negative 2 for K equals 2 we can return either negative 3 negative 2 4 sorry 3 negative 2 4 or negative 2 4 3 since order doesn't matter um okay so this is fairly simple the easiest approach to this would just be sorting the list of points based on their Euclidean distance taking that sorted list and slicing on K or turning that this will take and log n because we do want to sort but is there a way we can do better we can actually do it in linear time o of N and it's this phrase right here you may return the answer in any order we're going to be taking advantage of so if you've ever done quick find quick select or if you know how quicksort works we're going to be using the same principle here so let's take a look at a few examples first suppose were given points such that their distances come out to be 2 5 4 3 & their distances come out to be 2 5 4 3 & their distances come out to be 2 5 4 3 & 6 and suppose K is 3 now of course we can just sort you know 2 3 4 5 6 return 2 3 4 but what I'm gonna do instead I'm gonna pick a random point and call it my pivot suppose I pick five now I'm going to go through and see how all other numbers compared to my pivot if there are less than the pivot I'm going to store it in left there greater than it I'm going to store it in right so in the end the order would be left then pivot and then right so when left I would have two four and three in my right I would just have six now what do we notice about the lengths of these lists left is three it is just the one element one and right is also one but we can just return left as is because we know left is less than pivot which is less than right so it's left if the length of left three equals K then we can just return left because we know those are three closest points and if K equals 4 then we can apply the same logic we already have left during T to be less than pivot and right and we also have pivot guaranteed to be less than right so we have 3 plus 1 4 we have our 4 closest elements and there's something really cool going on here right so if I actually sorted this list 2 3 4 5 6 where is 5 located it's in its true ordered position and with this when I did left pivot right it was the same position 5 is in now so I had 2 4 3 then 5 and then 6 so what does it mean to be sorted right if I have a list and I say it's sorted it means that every element is in a place such that all the elements before it are less than the element that almonds after it are greater than the element but in this case we don't want to apply it to all elements we just want to apply it to our pivot and that is how we're saving time so to go back to our example suppose K wasn't foreign it was - and yet still pigs pivot 5 what do we - and yet still pigs pivot 5 what do we - and yet still pigs pivot 5 what do we do now well we don't actually want to pass in the whole list again if you just pass in left and our same cage equaling - so in this case we just pass in 2 for - so in this case we just pass in 2 for - so in this case we just pass in 2 for 3 and apply the same thing again so I pick another pivots holes I pick 4 well then my left would have 2 and 3 and my right we just had nothing so in this case I see that the length of left is 2 which equals K and I would return and end there but what if K wasn't - what if end there but what if K wasn't - what if end there but what if K wasn't - what if it was 5 let's do 6 suppose we have another element here 7 so 7 would go on the right and this one can be 2 so we still pick 5 as our original pivot what do we do now well now we only need to pass in whatever is in right so now we passing right and for K we actually set it equal to K - length of left - 1 and it equal to K - length of left - 1 and it equal to K - length of left - 1 and why are we doing this because we already know we have our 4 closest taking into account both left and pivot so we need whatever is left from right so if K equals 6 we have 6 minus pole end of left which is 3 - whatever the pivot is left which is 3 - whatever the pivot is left which is 3 - whatever the pivot is which is just 1 so this equals 6 minus 2 minus 1 or sorry left was 3 so this was 6 minus 3 minus 1 which is 6 minus 4 and this equals 2 so now we pass in right 6 & 7 8 equals 2 and we just return that & 7 8 equals 2 and we just return that & 7 8 equals 2 and we just return that and this is how the logic would go now let's take a moment to understand why this is faster and for that I'm actually going to start off by saying it's not always fast what if we run into the worst case so going back to this example what if our first pivot we picked was 7 and we wanted K equaling 1 so the first pivot is 7 well then we need to make comparisons with 2 5 4 3 & 6 so that's 5 comparisons with 2 5 4 3 & 6 so that's 5 comparisons with 2 5 4 3 & 6 so that's 5 comparisons so then we take in our left and pass it in again so close now our pivot is 6 which case we're going to be making comparisons with 2 5 4 & 3 so making comparisons with 2 5 4 & 3 so making comparisons with 2 5 4 & 3 so forth and now we pick pivot 5 we make 3 comparisons and so forth until we find K in this case 1 so in this case we would be doing n minus 1 up until 1 and summing all of that up we know it's n into n minus 1 over 2 which is N squared order of N squared which is much worse than n log n however this is just the worst-case amortize on average we can worst-case amortize on average we can worst-case amortize on average we can approximately say we get around path each time we pick up ticket so we pick up pivot so that it divides the input list into hat each time so the first time we would go check n elements then make another comparison with about + / - make another comparison with about + / - make another comparison with about + / - since supposing our first pivot dividing hat then if we still haven't found our answer divide in half again and keep going until we really find it and this is just a geometric sequence that converges to 2 n which is order n which is better than n log n so this is the main concept for it let's just go ahead and code this up now the first thing I'm going to do is write a list of tuples taking in the points and their distances so for that I'm going to make a helper function to find the distance for the points point turn swear and the reason I'm not gonna ask where beat this again is because it's an unnecessary step of computation if I have a hundred and then I had 64 I know 100 is greater than 64 the square root 10 is also greater than 8 so squaring or square rooting doesn't really change that relationship since we're dealing with positive numbers so I'm gonna do Alice team I'm so consistent on this I before I and now I'm going to call my name function and okay let's write this up and if the input list has a length of K then I can just return that so it went okay now I'm gonna do i of 0 because we want to return the actual points not the distances so the points were stored in that zero with index and if this is not true so if the lens does not equal K then we won't apply our logic so for that I'm going to import random you have a random tuple from this list and now I'm just gonna go ahead and neutralize everything so empty in fact I'm gonna make another list of equal and the reason I'm doing this is if you read the question again the answer is guaranteed to be unique except for the order that it is in so if we have five points all with the same distance and K equals two I can then pick any two from the five and the answer were not unique so that can never happen so if I come across points in which their distance is equal to the pivot then I know either all of them have to be included in our answer or none of them will be included in our answer because otherwise we would be only picking some out of the whole people which just won't happen so this can actually save this commutation by keeping another list for equal so now while I less than munch probability if our different point that were looking at goes to you I and the distance of that one well if this distance is less than the pivot I mean appended to the left appendix equal else if the distance is greater than the pivot I added to the right after this while loop is over we have everything in left people right when I just wanted to check the length so if this equals K well then I just want our return so I'm going to use the same return I had up here and return it except only for left this one and if the length of left loss momentum equal people stay and I'm gonna do the same return over here with the addition of equal so same thing but this time on people and if K is less than left I'm just gonna call this function again so the salt off you find its return on left and pass on K again and Ellis if we know it's not less than K not equal to K and not equal to k plus whatever is in equal then it has to be greater than whatever isn't a plus equal in which case I return will be half from left what we have from equal and then whatever else I need from right so I'm gonna return this plus sulphate dot find on right with pay - length of left - on right with pay - length of left - on right with pay - length of left - lend of equal and that's about it so you can run this phone now eridan cookies alright so accepted it let's submit and it is accepted it's faster than 74 percent of other Python three submissions um before I leave I want to talk about another optimization you can make you can actually do this in constant space as well right now we're storing extra arrays for left-right storing extra arrays for left-right storing extra arrays for left-right equal you can actually do this in place just running Dutch flag I did this about what three hours ago just to see the difference we worsened in runtime but memory improved slightly if you want to know more about that let me know I can like talk about how I did it make another video about leaf invariants and the algorithm I use for that or just show you the code for that otherwise if you don't have any questions all see you next time | K Closest Points to Origin | stamping-the-sequence | Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`.
The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`).
You may return the answer in **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in).
**Example 1:**
**Input:** points = \[\[1,3\],\[-2,2\]\], k = 1
**Output:** \[\[-2,2\]\]
**Explanation:**
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just \[\[-2,2\]\].
**Example 2:**
**Input:** points = \[\[3,3\],\[5,-1\],\[-2,4\]\], k = 2
**Output:** \[\[3,3\],\[-2,4\]\]
**Explanation:** The answer \[\[-2,4\],\[3,3\]\] would also be accepted.
**Constraints:**
* `1 <= k <= points.length <= 104`
* `-104 < xi, yi < 104` | null | String,Stack,Greedy,Queue | Hard | null |
424 | hey everyone welcome back and let's write some more neat code today so today we're going to solve longest repeating character replacement and so this is another problem from that blind 75 list so we are going to be one step closer to completing the entire list the link will be in the description to this spreadsheet if you do want to take a look and hello to the six people that are currently viewing the spreadsheet right now you're gonna be in the next video but okay so let's get into this problem because it's another pretty fundamental problem that's really good to understand so we're given a string s and a single integer k and so basically they tell us that we can choose any of the characters in the string and change it to any other uppercase english character so in this problem every character in the input string is going to be limited to uppercase english characters and we know that there's 26 uppercase english characters from capital a to capital z and so basically we can perform a replacement on any of the characters at most k times so we are allowed to replace k different characters in the string to any other character we want and what we want to do is return the length of the longest substring containing the exact same character we can get after performing at most k different replacements so we just want to return that length we don't actually have to make those replacements in the input string so in this case when we take a look at the input string we have a b and we're allowed to replace two of the characters so what's the longest substring we could get with the exact same character well we could replace one of the b's we could basically replace both of the b's with a capital a and then we get four a's in a row which would give us an output of four and we could technically also do the opposite we could replace the a's with capital b's and that would give us the exact same result a length of four so i'm going to show you how you can solve this problem in big o of n time and technically it's going to be big o of 26 multiplied by n which we know is also reduces to big o of n but there's actually technically an easier way to do it or at least a more simple way to do it which is just going to be a flat big o of n we don't even need this 26 constant but this way is actually pretty tricky to get to so i'll be going over a little bit of it but this is kind of the main way that you'd want to solve this problem so let's say we're given an input string like this and we're given a k value now the most brute force way would just be check every single substring right and if we were checking every single sub string in the entire input array we know there's n squared sub string so that wouldn't be the simple that wouldn't be the most efficient way to do it but even if we were doing it like that what exactly are we looking for if we're looking at a particular substring how do we know if this substring is valid because remember at the end of the day we want to maximize the result right the result is going to be the longest sub string that contains a single character and we can make two replacements so let's look at this substring alone how do we know if it's valid well which character are we going to replace are we going to want to replace the b's in order to make it all be amount to match a or would we want to replace the a in order to match it with the rest of the b's of course we're going to replace the character that occurs less frequently right because the number of replacements we have is limited so we would want to replace the character that the characters that are less frequent so in other words we want all characters in a particular window to match the most common character in that window so what we're going to be doing is we are going to have a hash map or a array which is going to take every single character in this case we only have characters a and b and we're going to count the number of occurrences of each character so for example if we were looking at this substring we see that there's three b's and we have a single a so how do we know if this window is valid what we're gonna do is we're gonna take the length of the window which is gonna be four right we're gonna take the length of the window right which we know in this case is four and we're gonna take the length or the count of the most frequent character in this case we know that's b and the count of it happens to be three so we're gonna take four minus three and from that we're gonna get a one now what does this value one tell us it tells us the number of characters in our window right now that we need to replace in order to make it match the most frequent character b right we have a b here we want everything to match a b in this case we only have an a right but it could be possible like who knows maybe that we would have a c over here right or an x over here and it doesn't really matter what the characters are we just know that b is the most frequent character in the window and the other characters that are not b a and z for example are the characters we want to replace so we can calculate the number of characters we want to pull that we want to replace just like this and so we want to replace one character how do we know if we have enough replacements to do one character well of course that's our input parameter k right so what we're confirming here is that this value is less than or equal to k as long as this condition is true that means our current window is valid that means we have enough replacements to make those replacements in our current window so this is the main condition that we're going to be checking the other question is how are we going to know which character is the most frequent well the brute force way is gonna be taking a look at our map of counts and we know that the max size of this could possibly be 26 because we'd only have 26 different characters so doing finding the max character is going to be big o of 26 so that's a little bit more inefficient than we would like but it's technically still linear time like the overall algorithm is still going to be linear time the last thing that we're gonna have to do though is to this uh equation we're gonna have to add a sliding window technique so basically what we're gonna do is we're gonna take our window start at the beginning expand it as much as we can as long as the condition that we mentioned is valid if the condition is not valid then we're going to take our left pointer and then shift it as well until the string becomes valid once again so we're going to have a left and right pointer so initially left is gonna be at the beginning and right is also gonna be at the beginning and also the counts of a and b are initially gonna be zero now we're gonna look at the first character right that's where our right pointer happens to be we're gonna look at it we're gonna say okay we have a single a right we're going to take our count of a and set it to 1 now so is this window valid as in can this window be the exact same character with within two replacements of course it can right that's kind of the trivial case but we would still calculate it and the way we would calculate it is get the size of our window right now we can see the size of our window is one subtracted by the count of the most frequent character in this case we know the most frequent character is a one minus one is that greater is that less than or equal to k we know k is two so of course uh this is going to equal zero is less than equal to two which is k right so of course this window is valid that's kind of a trivial case next we're going to shift our right pointer to the next character right so now we have a b so we're going to increment the count of b in our map so b is now going to be set to 1. in this case the length of our window is 2 the most frequent character is either of these right and the count of that frequent character is gonna be one so we're gonna have two minus one equal to one so this is the number of replacements that we would have to do and looking at our current window that makes sense right we'd have to replace at least one of these two characters so we're going to ensure that this the number of replacements that we need to do is less than or equal to k which is two of course that's true so our window is currently valid i guess i did forget to update our result so since this window is valid the length of the window is gonna be set to the result right so right now the result is two is the length of the longest window that we can get so that's our result for now so now let's continue next we're gonna shift our right pointer to the third character so now we get another a so we're gonna take the count of a and increment it all the way to two and we're basically going to repeat our algorithm so once again we're gonna get the length of the window three minus the count of the most frequent character we see the most frequent character is a so the count of is two three minus two is one is that less than or equal to two which is k yes of course it is so this window is also valid we can update our result now to three so we found another window even longer so i'm going to take our right pointer once again and then shift it over to the b so now we're going to be since we reached another b we're going to increment the count of b to 2 now and so the length of our window now is 4 and the count of the most frequent character is either of these and that's going to be 2 4 minus 2 is equal to 2. is that less than or equal to k is 2 in this case so of course once again this condition does hold so once again we found a window that's longer than our result we found a window now of length four and so once again we're going to take our right pointer and shift it so now another b let's increment the count of b to three so the length of the window now is five minus the count of the most frequent character charac that character is b five minus three is this two in that and less than or equal to k of course it's still true because when you look at our window we have three b's so that means we're going to be replacing the a's so we're gonna need to make two replacements and we are allowed to make two replacements okay so now we're finally gonna get to the case that i mentioned earlier where we're gonna have to take our left pointer and then slide it to the right which is why this is a sliding window problem so now we reached an a so we're gonna take the count of a and set it to three so now we have a count three and b count three so let's take the size of our window six subtract from it the count of the most frequent character it's gonna be either of these so six minus three means we need to make three replacements is that less than or equal to k is two so we exceeded k right we exceeded the number of replacements we're allowed to make if we wanted this window to be valid we have to replace three characters in it but we're not allowed to do that so what we have to do is shrink the size of our window until we are valid so we're going to take our left pointer and shift it to the right so now the left pointer is going to be over here it's going to be at the b so since we removed this a from our window we have to decrement the count of a in our window so i'm going to cross this three out and now it's actually going to be set to 2. i kind of ran out of room but i hope this is still readable so now the count of a is two so now let's once again check is our window valid well the size of the window now is five and the count of the most frequent character is b and that's gonna be three so five minus three is gonna be equal to two is that less than or equal to k yes we are once again valid so this is technically a valid window and i think i forgot to update the result earlier when we had a window of size five so the result right now would be size five because the longest window we can make is either this window or the window that we had uh earlier with you know these first five characters but yeah and so at this point we would stop our algorithm because we did find a window of 5 that is valid and our right pointer cannot be shifted anymore so this is the general algorithm so it's a basic sliding it's a fundamental sliding window problem with this particular condition being important but there's actually one way you can do it without having to look through the entire hashmap every time you want to find the most frequent character that occurs and it's kind of tricky to arrive at the solution but it's pretty easy to implement once you can figure it out i'll explain the algorithm at a high level i don't want to waste too much time on it but basically we're going to be having another variable and it's going to be called max frequency basically the count of the most frequent character at any given time so basically you know for example if we had a as a count of three and b is count two we'd say okay the count of the mo the most frequent character occurs three times so max f is going to be three and so any time you know if we got a b we inc let's say we incremented our b all the way up to four then we want to update our max frequency to four right so we'd always want this to be the most frequent character now the one problem is if we're trying to maintain the count of the most frequent character what happens when we take our left pointer for example right and then shift it right when we do that we're basically removing a character and therefore we're gonna have to update our count map right we are gonna do that but and if that does happen right let's say we took b and then from four we decremented it all the way down to two for example then we have to rescan this entire map and then find okay what's now what's the new most frequent character right so we'd have to take our max frequency and from four downgrade it all the way to a three for example so then we'd have to set it to a three but and that would basically defeat the purpose right we'd still have to do that big o of 26 calculation to scan through this but it's technically true that you don't have to decrement this max frequency but the main idea is this the result is only going to be maximized as we find a new max frequency right because remember what we were doing we were taking the length of the window subtracted by the max frequency right whatever the most occurring character was and we wanted to minimize this right so basically we want the length to be maximized because that's what our result is going to be set to so therefore we also want the max frequency to be maximized because we want to ensure that this is less than or equal to k and k is going to be a constant so for example let's say i had a max frequency of four but let's say now the new max frequency got downgraded to a three i'm still gonna leave this as a four because it's not going to change our result because for example if i had a 6 minus 4 that was less than or equal to k which is 2 in our example and if i leave this as a 4 i'm basically overestimating what the max frequency is but we know at least at one given point in time it was a four so therefore we were able to take the length six and then set it equal to our result and now if we're ever so let's say our result is now six if we're ever going to increase the result from 6 to another number like for example 7 we would require our max frequency to increase if it stays the same or if it decreases our result is never going to change because we only change our result when we increase our max frequency because that's the only way this condition here is going to be true so if our max frequency is downgraded we don't have to actually update it we don't have to look through the entire hash map to find the new max frequency but if we increase our max frequency for example if i took this a and then from three i set it equal to a five then that's something we can check and big o of one time and then if we increase this then we definitely do want to update our max frequency and increase it and that's something we can do in big o of one time so i know i probably went a little too long into this but the main idea here i'm trying to get at is the easy way to solve this problem with a sliding window is going to be big o of 26 times n which is technically linear but there is a clever way to do this in big o of end time that honestly i didn't figure out on my own and i wouldn't really expect other people to be able to figure it out on their own like in an interview at all but i will show this the standard solution and i'll also show the code for this more optimized solution okay so now let's jump into the code and the code is actually a lot easier than the visual example that i gave a lot shorter for sure so we're gonna have a hash map to count the occurrences of each character and we're also gonna have a result which is going to tell us the longest substring that we can create with k replacements and we're going to have a left pointer which is going to be at 0 and then our right pointer is going to go through every single position in the entire string s so what we're going to do is for the character at position r we're going to increment the count of it we're going to take 1 plus whatever the count currently was count dot get this character and if the character doesn't exist in our hash map we're just going to return a default value of zero that's what this function is doing and so before what we're going to obviously do is update our result right and we want to set the result equal to the max that it's ever been and set it basically equal to the size of the window we can get the size of the window so we're going to take the max of result and the size of the window can be gotten with right minus left plus one and but before we do this before we update the result we want to make sure that the current window is valid so what i'm going to do is basically say while and i don't think you'd actually need a while here you could just do if but i'm just going to do while just because so while the window is not valid and we would know that by taking the length of the window which we have down here so i'm just going to copy and paste that the length of the window subtracted by the most the count of the most frequent character which can be gotten with max of count dot values right we're basically going through the hash map which could be size 26 and just getting the max value from it so this is the number of replacements that we have to do and if the number of replacements was greater than the number of replacements that's allowed which is equal to k that's when we would want to shift our left pointer so we'd want to increment our left pointer but before we increment the left pointer we'd want to take the count of the character at the left position and then decrement it by one and that is the entire algorithm after all of that is done after we've gone through the entire string then we can just simply return our result and as you can see this is pretty efficient it's linear time it's about as efficient as you would need i think but i'm going to make that slight optimization that i showed you i'm going to maintain the max frequency in a single variable so that we won't have to do this operation where we're getting the max of the entire hash map instead up here before we execute that loop i'm going to say max frequency is going to be equal to the max of what it currently is max frequency or it's equal to the frequency of the character that we just added a value to maybe that character became the most frequent character so we would have to update our max frequency and we can do that just like this and this is a constant time operation we're not scanning any list or anything and then once we have this max frequency we can use it in this loop execution right so we can replace this and just use max f for that and the thing is notice how even when we're shifting left we're incrementing the left pointer we're potentially removing characters from our window we're still not decrementing max f because we actually don't need to it won't end up affecting the result if we for if we just don't decrement it and that very slight optimization which is really simple in terms of code but it's kind of hard to see why we're allowed to do that watch how much more efficient it makes our algorithm so as you can see look it definitely improved it i think it was 50 milliseconds different so this is significantly faster it's hard to see why though i would definitely not expect most people to be able to figure that out so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching | Longest Repeating Character Replacement | longest-repeating-character-replacement | You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most `k` times.
Return _the length of the longest substring containing the same letter you can get after performing the above operations_.
**Example 1:**
**Input:** s = "ABAB ", k = 2
**Output:** 4
**Explanation:** Replace the two 'A's with two 'B's or vice versa.
**Example 2:**
**Input:** s = "AABABBA ", k = 1
**Output:** 4
**Explanation:** Replace the one 'A' in the middle with 'B' and form "AABBBBA ".
The substring "BBBB " has the longest repeating letters, which is 4.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only uppercase English letters.
* `0 <= k <= s.length` | null | Hash Table,String,Sliding Window | Medium | 340,1046,2119,2134,2319 |
74 | hi everyone today i'm going to be solving the lead code question search a 2d matrix so the problem is telling you to write an efficient algorithm that searches for a value target in the m by n integer matrix and you're sold and you're told that it's already sorted so the elements are sorted from left to right and the first integer of each row is greater than the last integer of the previous row so if you see here the matrix is like sorted 1 3 5 7 10 11 16 20 23 30 34 60 and you're trying to find out if a value is in that matrix so you're given like 3 in this matrix which is there and then you're also given 13 in the next example which is not in that matrix so this is the problem and since the array is sorted it already gives you an idea of using binary search which is a way that you can solve this problem but because it's a 2d matrix it's a little bit complex to do that so let me just go over a couple approaches to solve this problem and i'll switch over to my ipad to show you a couple ways you can do this problem the first one is that is the most basic brute force which is n square where you will just be checking all the rows and all the columns so and then seeing if there's a value and actually this is not n squared it would be if there's n rows and m columns it would be n times m so that would be the most basic solution uh second solution is you can actually use the fact that the array is sorted and the way you can do that is if you start off at eight you will notice that all the elements to the left of eight in that first column are smaller than eight and if you go down all of these elements so basically like to the left all of these elements are smaller and down are all these elements are greater so if you just start off at eight um at which is like the first row and the last column you can basically just make it a linear time which would just be n plus m so for example like if we're trying to find 11 what you can do is you can first start off at eight and then you'll see that eight is smaller than 11. so what we'll do is we'll go down and we'll see 20 and then once we see 20 we see that 20 is um is greater than 11 so we'll go to the left and then we'll reach 16 and we'll see that 16 is smaller than i is greater than 11 so we'll go to the left again and then we'll get to 11. so that's how you find it and basically any number you can do it with this n plus m complexity uh so for example like if we're trying to find a number that is not in the matrix like let's say we try to find uh like 40 uh what we'll be doing is we'll go to 20 and then we'll see that 20 is smaller than 40 which is the target so what we'll do is we'll go down again 60 and it will go to 34 and we'll see that it's greater that is less than 40 but there is no down because we'll go down and then we'll reach the end of the matrix and when we have this condition we'll know that um we can't find the value and it will just return false so that is a way that you can solve this problem in linear complexity instead of the quadratic that we found before and there's actually a better approach so the final solution which is the best approach is to use uh bina binary search so binary search is going to be a log n plus m solution uh because um the array is already sorted um like it's 1 4 7 8 10 11 16 20. 2330 3460 like all of these are already sorted so what you'll have to do is you just have to modify the original binary search that way that we're typically used to use uh this logarithmic complexity and i'm going to show you how i did that because that's the best approach to solve this problem okay so this is how i solve this problem using logarithmic time so there's it's basically binary search but basic you have to try to make it into a 2d matrix so it's very similar to the regular binary search so first i'm getting these uh variables to set get the matrix length of the rows and columns also m and n and then like in typical binary search i'm setting the left equal to zero um but for the right i'm doing m cross n minus one so because it's basically uh like this where we have 1 3 5 7 10 11 16 20. so the last index is basically is the right and it's going to be the greatest element uh and then what i have is two different mids so typically in binary search we'll just have one mid element like we will just do left plus right divided by two but in this case um there's a linear mid and then there's also a matrix mid so the linear mid is what is the regular mid that you would be used to in binary search but then you have to convert this into the matrix value and that's why i have this matrix mid variable so how i did this is that i first do the linear mid which is just a regular binary search left plus right divided by two then matrix mid so to find the row you actually have to divide by the number of columns like in the linear so you do divided by n and then you have to do modulo n to get the uh the column number so that's how it's like split up when we do m times n minus one um and like when you actually get it into the uh to get the values in the matrix you have to do these conversions uh and then so that's the value that we use based on the linear mid and then we if the target is equal to that then we return true which is regular binary uh binary search and then we check the other two conditions so if it's less than then we do the regular linear mid minus one and then left on the other case it would be plus one so this is just basically the same as binary search and of course like if we can't find the value we return false so the main thing of this the only difference between binary search and this problem is that is this conversion and this is only specific to matrix problems uh but like once you understand this conversion uh this problem is very straightforward and once i submit this problem you can see that it's accepted and i'm getting a run time of 100 uh which is very good so thanks for watching this video uh let me know if you have any questions about the solution and subscribe for more videos in the future | 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 |
1,171 | Hello everyone welcome to my channel with mike so today you are going to do video number nine of linked list ok the name of the question is remove zero sum consecutive notes from linked list it is a medium level question but bill will be very easy if we understand it ok From this, lead role number one seven one is fine and you have to understand the question by looking at the input and output. See what the question is by leading the question. Sorry link's question has two specialties. First, if you have made this diagram then it becomes very easy. Question because you are able to visualize the story work in the question from the second link. The story is really fine, isn't it? If I tell you then you can do the code very well by yourself. People do not need to tell anything. Okay, so let's see its input and output. Let us understand what is the question, so the question is quite simple to understand, a link has been given to you in it and it has been told to you that if the sum of the consecutive elements of the linked list is zero then it has to be removed from the notes, but see the example here. What is the value of linkluf? Here is one. Next, you are one plus 2. It has become 3. Here, as I have come, you are seeing that the sum has become zero. There is one here, this is 2 -3. Total is one here, this is 2 -3. Total is one here, this is 2 -3. Total sum has become zero, so what does it mean? We have to remove this, okay, now let's move ahead, there are 3 here, if one is done here, then this will not be removed, so look at what has gone back, just look at this is my LinkedIn child, okay and look at the head starting. Was pointing to A but now the head is pointing to the right, so many things have to be kept in mind that the head can also change. Okay, we have to delete more and the painter also has to adjust. Okay, let me show you another example like But if we take an example, our link is like this: if we take an example, our link is like this: if we take an example, our link is like this: 2 - 2 is 2 - 2 is 2 - 2 is pointing to 3, it is pointing to one, okay then both of these will be there so that there is no change in the head, here there can be a change in the head, anything can happen. It is possible, okay, the sum of any consecutive element can be zero, then it is okay, the question is very simple to understand, now let's see how to solve it, okay see, now coming to the best part, how to build the intion, okay what, how to solve it. How will they bill come up but they will see the solution? The most important thing is okay, so this is a sample of mine taken to understand it, okay, before going on the link lift, I will show you one okay, but the example. Mother, let's take this as yours, we are doing this, okay here is one, you are three, here is -3, here is four, let me you are three, here is -3, here is four, let me you are three, here is -3, here is four, let me index 0 1 2 3 4 okay, consider this as a very important thing and we will apply it in the link only. It is a very basic thing, it is a logical thing, but I look at you like see, let's see the prefix, we leave, okay, this is my forest, okay, now look, what is my prefix in the beginning, it is zero, I have not added anything yet. is okay prefix even is okay now here so one is added then one comes here so one plus tu three plus correct that I am adding the numbers no one plus tu plus three minus three so number So, the number should have been filled, the number should have been increased, 1 + 2 + 3. Look, the number is also big, after one, 1 + 2 + 3. Look, the number is also big, after one, 1 + 2 + 3. Look, the number is also big, after one, three, A, after 3, six, A, after that, Ghat, but it is okay, Ghat and when Ghat, then look at the three which is there, isn't it? I have seen this 3 nearby, look here, I saw it nearby, okay, so tell me one thing, the sum till here is looking correct to me, the total sum is three, look here, after this I added something to which go back. I went to 3 only. Okay, that means first I was three, the whole even or the sum of so many words was three, then I added something, I ask for it from the red box, after this I added something, then again I went to 3. I went, I added something to it, did I add anything, I don't know, then I have come back to 3. You see, here it was on 3, then I added something and then look again, it came back to 3, what does it mean? What would have been its value? The value that I added must have definitely been zero, that is why 3 + 0 came back to 3A. What does it mean 3 + 0 came back to 3A. What does it mean 3 + 0 came back to 3A. What does it mean that brother, this area must have definitely been zero. Okay, listen again, it is very important, question on this. If you understand that you have been vaccinated then everyone will understand. Okay, I am saying that brother, I know that till this much is even three, this is okay with you and so and this is what I am marking with a red box, but I have made this even three. I added it on this, but it came back to 3, so what would be the meaning of this, surely the sum of this box must have been zero, it is only 3 - 30, okay, it is clear till now, this is only 3 - 30, okay, it is clear till now, this is only 3 - 30, okay, it is clear till now, this thing will apply here also. Look carefully what I am saying, what is my time now, in the beginning everything is my zero, okay, prefix zero, now one became one plus you three plus three became six, till now everything was going well, it reached three but after this so much After adding the part, it again went back to three. Okay, what does it mean that this is the area, its sum must have been zero. Okay, then this thing will be known that how will you catch it, brother, how many parts. First of all, there was no tension, how many notes have to be removed, that ended my tension, how many notes, either part, have to be removed from the link list, we have found out which is most important and whose sum is zero, I have found it, brain. I thought it is by prefixing it, okay now the matter has come, let's catch it, brother, I have to curse them, I have to remove them, now how will I remove them from my link, you should understand how that too should be understood, meaning, you should understand that how you will remove it. Okay, so let's see, let's do it directly, it will become clear immediately, see how, remember, first of all, what I said that I will extract all the prefixes, so I will keep a variable for extracting the prefix, ok, prefix in the beginning. Is it zero? Okay, what did I say when I find a prefix sub which I have already seen in the paste, then I will be suspicious there, no, what is the suspicion, I will come to know there that yes, zero component has been found in it. It's time to delete it, so now along with it I will have to store in the map that brother, when did I last see this prefix and in which note did I see it? Otherwise, the map that will be mine will be something like what is the prefix we? Wait and second thing, in which road did you see it, then there is a list note, so my map will be something like this, okay, then the prefects come out, if we get starting prefix, then three prefixes, we too, I have not seen till date, it was not there in the map, so I used three. And on which note was it found? B was found on note. Okay, now here it is 3 + 3 = 6. Six is also now here it is 3 + 3 = 6. Six is also now here it is 3 + 3 = 6. Six is also not present in the map, so six was given. Here, C was given and six was found on C. So okay, now look at this very important thing, as soon as I came here, I got free again in the prefix. Okay, so I saw that three is already present in my map. Look here and where did I see this three last? I saw it in B, here's what it means, after B, till here, where am I standing now, currently, I am standing here on three, na - if I am standing here on three, na - if I am standing here on three, na - if I am standing on 3, then I am head, I am late, I am head ahead. It was flooding slowly, okay, so let's take mom, now I am standing here, okay, so I saw that okay now my prefix is we 3 and 3, I have already now my prefix is we 3 and 3, I have already now my prefix is we 3 and 3, I have already seen it in the map, so from here I came to know that and this I got this. I also came to know that from this map, take this from B to this B. How did I know that I had stored it here, after this B till the head, the notes will have to be head, after this B till the head, the notes will have to be deleted or not, okay? Let's see, it is obvious that they will have to be removed and what will have to be done to remove them. Think what I will do, brother, I will make his next head the next one. Okay, so this note was there, this connection was cut, it is right. No, this is what you are, it will start pointing to the direct four and we will have to remove this prefix from the map, no, we will have to remove the six, okay, we will have to remove this, okay, that's the only thing because now it is not in our picture, so map it. Okay, so now let's focus on what to do next. Okay, so look, I am clearing it a little bit so that we can flood further. Okay, I am removing all of these as well. I am okay, I am removing all of these as well. So now if we see the story, what was going on with us was that brother, when we came here, our prefix we 3 mine which is already we can see, where we have seen here on B, we are looking at it, okay here we have the prefix I have seen three, what does it mean that we do not need it, we do not have to enter it in the map, if it has its entry then it is not removed and does not have to be entered, like we take it for granted that we will not enter it in the map, why would we do it in the map because Here the prefix is we three because Here the prefix is we three because Here the prefix is we three and preference is 3, we have seen it in the last, okay, we have seen it here, that is why what have we done, we will not enter it, no, okay, has it gone back, no, we just have to remove it. I have to delete it's okay with you, one thing I have to do is delete it, plus one more thing, what I have to do is to delete this connection and how to move here, it's okay to delete this connection, so to do all this, I have to do this a little bit. I am cleaning it so that you can understand it well, so look, it is an obvious thing, you know that yes, last time three, where did you see it, saw it here, right here, saw it here, so let's mark here that I saw it here, okay Let's start with this, okay, and science, I will have to remove it. It's okay, if there were others in between, let's remove them too. Okay, and I have not included this in the map, so there is no need to remove it, right? So this has to be removed, now from here I will start moving from the start and will keep removing everyone until I get what I want, until I get this, I am now standing here until I want to reach here, okay So you think for yourself, then when I remove it at the end, this is the start, no, I started from here, so what will happen next, do this, I will mark it, okay, so that this link gets broken, right, it's okay. I have started with this and have kept a template which will move forward and remove all of them. If it is okay then how will our file look? File 10 note is equal, you are the head, then I will keep removing all of them till it goes on. Ok, come on, this is what you guys must have understood. Okay, what happened now? What is the value of the prefix in temp key? It is three here. There are only three here. Okay, now I have moved the time forward. Temp is here. Okay, what is the value of team and the prefix of team is stored as three and its bar is three becomes six, so it becomes 6, so what will I do, I will see in the map that okay here, the value of its prefix till this note was 6, so I also have to delete it, so I deleted it from here, made it six, okay, what did I do? MP Dot A Race, what a very six, it was 6, I erased it, okay, that's very good. After this, temp will flood my front, it will go to 10, now from here, I have removed time pay note equal tu head only, so my fruit look is finished and I have removed this from the map, this also from the map, okay. It has been removed and at the end when the follow is over, what did I say that I will make it equal to whomever is next at the start, I will make it equal to this one, okay my current one, I was standing on the head, neither is the head which is next i.e. it is only four. head which is next i.e. it is only four. head which is next i.e. it is only four. Isn't it a net of time, so what will I do, this is the start of mine, its next, now whom am I making equal to the head's next, head connections have been made equal to the head's next, these people have agreed, these people are ok, I did not enter it. We leave this in the map and when it has been entered, I removed it. I am there, these are already there, okay, these people are already there and I have made this connection of CAT, here it is, okay, so if you see. How simple will our code be? Understand the story, you do the code now. Okay, Story 2, understand it carefully. Okay, before supporting the story, think of one more thing, just a small thing as I told you, Maa, let's take the head only. The head has changed, okay, this is mine, you are mine, this is my 3, pay attention to its value, its we, it has become zero, I have not seen a but three yet, I will have to put zero also, there should already be zero in the map, so what will I do, remember. Prefix we was one here but remember in the beginning my prefix was zero, dispatch was zero but there is no note for it yet but what will I do, one I will make a dummy note, okay, I will make a note at once, okay Let's keep its value zero, let's keep its Dumin and Dum, Damini note is okay and I mark it next to the dummy note, A is okay, I mean what I am saying is that I will make a dummy note and point it to whom next head. I will point it to, right? If the head says, A will point it, okay, so now see how I will reduce it, I saw that okay, I have just got zero, I am already looking at it, okay, so I have made the map. I must have already written it and this is the dummy note which I must have inserted here in the map. I must have inserted it in the starting itself. Okay, so now as soon as I got zero again, I saw that the terminal is already present in the map. Okay, so what can I do? I will do it, I will go here, okay, I went here, this is my start, okay, and this is my temp, no, this is my temp, what will temp do, I removed it here, okay, I removed it, after that temp came here, both of them. I have removed 'C' as I had both of them. I have removed 'C' as I had both of them. I have removed 'C' as I had not inserted it. It is not necessary to remove 'C'. It is not inserted it. It is not necessary to remove 'C'. It is not inserted it. It is not necessary to remove 'C'. It is not necessary to remove 'C' necessary to remove 'C' necessary to remove 'C' yet. Okay, now look at what I said in the last section, when the wiring loop will end. So what I said was that whatever will happen next at the start, what will I do? Whom will I call next at the start? It means that what will happen now is to watch carefully, it was here, so what will I do now, it will start pointing here, okay. And in the last, know what I will do, I will return, okay, so what is the most important thing, what we have to do in the beginning is that we will make a map, okay, we will definitely make an entry in it, MP of zero, because in the beginning, my prefix we is zero, right? In this equal, you will make a note and put its address here, the land is fine and the most important thing is that if you make the land, then what will have to be done is the dog, but the dummy note will also have to be pointed, after termining the head, the next thing that will happen will also be pointed to the head. In the beginning, the value of the head should be done. Okay, this example was important. Okay, so now whatever story you will write, I will make it by asking questions from almost all the links. Okay, so in the beginning, I will have to do these three steps, that is, made the land note, next. Signed, made a map because my starting is okay, the prefix is going to be in the starting okay, the prefix is going to be in the starting okay, the prefix is going to be in the starting is okay and then my form will run from its starting until the head is null and what is okay then I prefix we come out I will remain prefix sum plus it is equal to the value of head. If it is present then it will reduce the delete one by putting a loop on the delicious one and every time the head will keep moving forward. Okay, this is very important and if you write the code now, then you will listen to the story again but I am searching you again dry and do n't forget to take this one example and return dry. Okay on this so let's code it. Now let's code it and I will repeat again please dry. Must do story you code, now we are going to convert, first of all what I said was that we are going to keep a prefix with the name, what will we keep in the variable, we will keep zero which will be in the starting, the prefix will be zero, right and we are going to keep a map in it, right in these inches. What is this, my prefix will be even and I am writing on which note I got this prefix, I am ok please MP, ok then let's make it, ok, I have made a dummy note, ok, now let's start our vile. Head note is equal, you tap this, I will keep going, okay, now you say that the head will keep changing, then in the last, that is why I am saying right next to the dummy, add the address of the head and I have done it okay, which was the actual address of the head here. But if there will be a change of head, then I don't care whom I am going to return last, whatever value will be next in the dummy note, I am going to return last, okay, so now we keep calculating the prefix as well as plus is equal. Whatever the value of head is going to be, it is okay. Now what I said is that if I get MP sum, it is okay, if I get it already in the map, then the delete one will reduce this one, now the head will be pointing to whomever it is, okay and in the last The next part of the head will keep moving, okay, now this is less of mine, this is my part, this is the part of this entire code, okay, we will reduce the delicious one, so what I said was okay, I have started a quandle. Took it, who will point to whom? MP of prefix sum, which I have just seen, I have seen it nearby, so I went there, it is good, this is where I last saw it last time, this prefix is fine with us and what I said was to keep one more. Let's is fine with us and what I said was to keep one more. Let's is fine with us and what I said was to keep one more. Let's take the name temp which will start from the beginning and it will keep moving forward and we will also keep deleting it, okay and the current is my prefix, what is we, brother, prefix equal, this is my current prefix, okay and how long will it last until the time note is equal to you. Okay, let's get the head and I will keep deleting from you. Okay, now let's see what is my tempo. This is equal to your tempo. We were moving ahead. Remember, we did the next of 10 = 10. Remember, we did the next of 10 = 10. Remember, we did the next of 10 = 10. Okay and we will also keep updating the prefix. The prefix we, which I have made here as temporary, prefix sum plus it is equal to 10, the value is fine and we will keep arranging it. mp.ej This mp.ej This mp.ej This piece is there, but look pay attention, when will we raise it, for how long we will keep doing it till. My temp may not be equal to that of the head, nor should it be equal to that of the team's head, because remember, I have not even entered the person whom the head is pointing to. It is not in the map, so even if the temp is not equal to that of the head, then We will keep racing and then later on there will be a similar break. Okay, after that when we were taken out, what did I tell you that I am going to change the start, it will become equal to the next one of the head, so I want to say, make a diagram. Okay, make a story and dry it. Do it properly. I have taken two diaries of this and one more test of mine too. Dry it on this code. It is okay. This is a very easy code. Run it and it will be cleared very easily. Okay. Let's run and see, there will be no new note, there will be a new list note. Here, now let's run and see, if you are able, you will pass the example. Okay, great, submit, let's see. Indias, they have solved this question, viewers are already ready. Have any doubt please in this common session and try help see you gas video thank you | Remove Zero Sum Consecutive Nodes from Linked List | shortest-path-in-binary-matrix | Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of `ListNode` objects.)
**Example 1:**
**Input:** head = \[1,2,-3,3,1\]
**Output:** \[3,1\]
**Note:** The answer \[1,2,1\] would also be accepted.
**Example 2:**
**Input:** head = \[1,2,3,-3,4\]
**Output:** \[1,2,4\]
**Example 3:**
**Input:** head = \[1,2,3,-3,-2\]
**Output:** \[1\]
**Constraints:**
* The given linked list will contain between `1` and `1000` nodes.
* Each node in the linked list has `-1000 <= node.val <= 1000`. | Do a breadth first search to find the shortest path. | Array,Breadth-First Search,Matrix | Medium | null |
1,611 | hey what's up guys this is sean here so today let's take a look at uh last problem of last week's weekly contest number one thousand 1611 minimum one bit operations to make integers zero okay so you know this is like a quite interesting problem you know okay given like an integer and you must transform it into zero using the following operations any number of the times return the minimum number of operations to transform into zero so which it means that you're given like a number n here and you can only perform one of those two operations so let's and so what are those two operations so the first one is that change the right most bit in the binary representation of n so the zeros bit means that you know let's say if we have 1 0 1 it means that you can only change the right most bit which is the last bit you can either change this one to from to zero from zero to one or from one to zero okay so that's the first thing you that's the first uh the first operation you can do which means you can only change the last digit and the second one is a little bit weird basically you know if you want to change the ice bit okay um for example if you want to change this the leftmost bit here in the binary representation of n here you can only change it if the and the if the i minus 1 bit is 1 and the rest is 0. so what does this mean it means that if you want to change this bit here you can only change it when the uh when the bit is like this one zero okay only then you can change this one from one two to zero or from zero to one but for this problem i there's no point of changing this one from zero to one because we're trying to move trying to change this what is n convert this n into zero so which means in order to change uh the not the none last none uh right most digits we have to somehow convert this binary strings into this format then we can change the we can change this one to zero right and then the rest will be uh what i mean will be this one okay so yeah so that's basically those two those rules of this problem okay and okay so in order to do that right i mean let me try to write something here you know for example right let's say we have a num we have a uh we have integer we have a string like one zero uh one zero okay let's say this that's the end here let's say n is equal to this one okay and so in order to change this one to zero so we have to first basically we will be look we will always try to change the left most uh digits from if it is one okay because that's basically we're trying to use it like this kind of greedy approach here basically if the left most uh digit is one we'll try to uh change this one to zero but in order to change this one to zero so we need to convert we need to do this right we need to do something like uh we need to change this one to uh to what 201 one zero okay basically we need to change this all right this part to it okay now i'm gonna do a like a comments here right so the first step is that we have to somehow change the this strings to one zero so that the net we can then change this one to uh to i mean to zero okay so now so basically from this from the first step to this step what do we have here we have i mean we have like uh somehow right we somehow have to change this one we need to change this one to two one zero step one right step one is this okay step one is this we need to change this one to that and the second step is what so the second step is we do a plus one here because the second step is that we just now we can simply we can uh we can use the second uh operations here where we added where we revert this thing the one two to zero okay so change one to zero and then how about this the second step here so the second step is now we just need to convert now the left most bits have been changed to zero now we just need to change the rest thing into a into zero so which means as you guys can see before we had like uh seven digits now we only have six that's like uh like a sign of recursion right basically now we just need to uh convert this one zero to two zero basically that's the three step uh to convert that okay and for this part for the second so basically and this one will result to one right and this one the third step uh will result to what uh assuming we have a dfs then it's going to be a one zero okay right because at here we have like at the beginning we have a beginning we have dfs right df dfs one zero right at the beginning we have that so now the first step is we are is equal to what basically we need somehow first up we need to convert this part into one zero okay assuming we have a function here we have a helper function here to help us uh convert these things right to uh to this one here and then the next one is with plus one because the next step is we plus we will convert we revert the leftmost bit okay and then we do what the rest is dfs of one zero and we have five zeros okay so that's the uh that basically that's the dfs there's a dfs transition function here right and now about this helper because remember so the dfs the definition of dfs is the uh what's the dfs the minimum steps to convert n to zero okay and the helper so what is the helper is like helper n right so how helper n is the mini mom stops to convert n to what and to uh basically one zero basically the uh the same length of n but with the is one at the first bit and the zero for the rest bits okay and so we already have like the definition of the dfs now we just need to uh consider how can we implement this helper function right which will be converting this n to uh to this uh to one zero okay so you mean okay so now to be able to convert 1 0 to uh to 1 0 zero so we also need to we have to make some observations here right so i mean they're basically they're like there are like uh two cases here i mean you guys just need to uh take a close look and so the first case is the uh if basically if the bits i'm let's say i'm defining a bit here right if the bit 0 which means the first bit y the bit value is it's zero okay so uh well actually you know what so i think the one case is easier okay so if the first the bit y the first value the first bit value is one and then we just need to convert the remaining parts into zero so and as you guys can see so this is exactly what the dfs is doing right basically if the so if the if this the bit the first bit is one we can simply do what we can simply do a one plus the dfs and this part right so the remaining part assuming like say this is the that's the case right it's going to be a 1 or you know what let's do this one x so we have uh we have 6x here right so it's going to be a uh let's see there's the s and five x here right so if the s if s is one then we have one plus d f s x five x here because all we need to do is just oh basically we don't even need the one here because we just need to convert the remaining to zero and that will give us this one zero okay and the more complicated cases if the s is zero okay so if s is zero uh and we want to flip basically we want to flip this zero to one so that we can convert these things to 1 and 0. but so again right so in order to flip this the first bit in order to flip that the first bit so we have to first convert uh these things to what to uh to s one zero right so the first step is this so uh 2.1 okay so the first step is uh 2.1 okay so the first step is uh 2.1 okay so the first step is from us this to this right because only when we have when we convert this uh this string to the form of this one then we can uh flip this ass remember this is a zero here right and then we can flip this one to uh to one zero right then we can flip that and now the remaining part is what the remaining part is we just need to convert the remaining one zero two zero and this is also happens to be the definition of the dfs here right so and now we just need to convert the these things here this uh the remaining part into zero which happens to be the dfs here so it's going to be a dfs one zero now we only have four zeros here okay so that's the second part so the first part right so the first part what is the first part is we convert these things the xx to one zero so well so what's this that's the definition of our hyper helper function right so basically you know so now we have the functions here so we basically if the first one is zero so the first step is that we have to convert this part to one zero which it happens to be our hyper function itself okay it's gonna be a uh five x here right and then after that we uh we flip the first bit right to be it to convert this zero to one so we plus one and then the remaining part is still right we still have to uh now we have one zero now the rest is just to use this dfs to convert this one zero to zero so that we will have this final answer right it's gonna be df as one zero yep so i think now we have already defined these two functions completely and we can start implementing those two functions oh but remember so for those dfs right since we also need to uh use uh like the memorizations just to save some time because with the you know for the dfs for n and helper ends here you know as long as we have define uh calculated once we can simply store those the result into a hash table so that we it can be reused so this something like a dp right and now and for the uh for the base case it'll be a little bit different uh in terms of the dfs and helper so let's see let's take a look at the base case so for the base case right so for the how for the dfs for dfs the base case is just though has the has one digit right so for one digits if it's zero what so for the zero we don't need to do anything to convert to zero so which means if this is zero we simply return zero so if one uh we return one because for to be able to convert one to zero we just need to flip the we can just simply use the first operations to do it so which means we will need a one step okay but for the helper here that right so just be careful when you define the base case for the helper remember the purpose of helper is to convert this n to one and then follows the uh follow zeros okay so which means if it's zero so we need to return one why is that because now the purpose of the top rate is to convert this value into one something and in case of only one digit it means that just one without any zero so which means we can simply use the first rules the first operations to convert to zero to one okay and if one then returns zero basically it's just opposite because if it's one then we okay we have already have the desired format we need here so that we just need we don't need to do anything that's why we return 0 here cool so i think yeah with this kind of definitions we can start uh writing the code now right so um uh so first uh we need the dfs okay we need dfs and then i'm going to pass in the bits here okay and then we all have like a helper functions here okay so halfway we also need to define like a bits because you know the input is integer but you know uh it's easier for us to convert it into a string format and then here i'm going to have like a memorization for dfs okay and also the uh another memorization is right for the helper okay i'll just call it helper here and here in the end we simply return the dfs and oh sorry so before doing that let me let's try to convert uh the string the integer into the b twice so the way in pi in python we have a function called bin here so the binary the bin like function basically will give you the uh return the string here but the binary will also returns like a string like a at i at zero b at the front so in term for example if there's a six here so uh we have this one the binary string is one zero but if you use a binaries i think it's got i think they added like zero b out of as a prefix so it would be like zero b one zero but here we only need the remaining parts so that's why we i'm going to simply use like a slice of the string here basically we just need to get everything starting from the third character okay so here yeah sorry now we have the bits we simply return the bits here so that's the uh that's the precalculation we convert this thing to the bits and then here right now we have this so first let's try to uh write this the memorization part basically if the bits in the memorization dfs okay we simply uh return that okay bits simply return it okay and then later on right so answer equals to zero and here i'm going to just uh copy and paste here so this is just like a template for the top down dp right and then return answer okay so that's that and now the uh the base case right since we have already talked about a base case i think we can simply uh write the base case here first basically if the bits uh equals to zero right so for the dfs we are converting everything to zero so which means here we don't need to do anything which means we can simply return zero or if the bits equals to one okay so in order to convert one to zero we return one because we need one step or one operations okay so now i think for the dfs of a there's a place we need to be careful because you know it could be uh possible that the df at the beats stream we pass in the first one is not zero because it could be uh zero one because later on because uh when we do this like the recursions you know even though this bin is being here at the first at the beginning this beats will not have like uh precede uh as zero as a prefix but during the calculations it's possible that the path in bits will have it starting with zero because we will be doing this like a substring later on right so for if the first one is zero it means that we don't need we don't want to handle the first case we don't want to handle the zero bit because there's no because we're getting the minimum number which means we just need to uh start our logic from the first uh non-zero our logic from the first uh non-zero our logic from the first uh non-zero bits okay so which means if the bit zero is equal to zero right so in this case we can simply you know we can do a while loop here i think and or we can just use the uh the dfs itself here right so we can simply do a df uh um let's see we have an answer here answer is the uh it's zero okay if the first one is zero and then we simply do a dfs of the bits uh one okay basically we just passed this uh the remaining parts to the answer to the two to the dfs so that when we just ask the uh try to process the remaining parts okay else right uh yeah else uh like i said so else it's this case right we just we will need to somehow convert the substring right to the one zero and then plus one and then do a dfs of this so basically here we'll do a helper here right helper is what we uh we do a helper bits from this okay that's the first step and then plus one and then plus the dfs of uh so of this right so how do we calculate that right basically we need a one at the beginning right so we need a one here plus zeros so how many zeros so assuming the length of the bits is five basically if there are like five uh digi five digits here i mean here we what we want to get is one zero that's what we're going to pass in here right so which means we have one here and how many zeros basically the length of zero is the length of the bits minus two okay so we can do a zero times uh the length of the bit and then a minus two right so that's how we get this one zero here right cool so yep i think that's it for this dfs okay now the uh the helper so the helper is i think it's quite similar as the dfs here i mean we can somehow copy these things here i mean i'll just copy this part here and then i will try to modify accordingly here of course so now we need to use this thing here right so this part and i also copy this part here that size the sr template okay so i'm going to remove this okay replace that but remember for the helper the base case is in the is reversed right when it's zero we need one wins one we need zero so that's why we have to reverse this part okay now again so now it's the time to implement this part remember in the helpers we have two cases right same thing if the bit is one okay so if the bit is one then it means that we simply pass the remaining strings to the dfs uh it's this right so that's the one case right so if it's one we simply do this we simply do a answer equals to df as uh bits one right so that's the one case and for the zero case we have this uh function here okay so else answer equals to uh like helper right helper bits one zero okay plus one and then plus what plus the uh the dfs of this part okay actually it's the same of the of this part i will just copy it here because we're also going to do a the length of the base -2 yep so that's the uh that's the implementation of the helper functions here and then yeah and then we i think we it's ready to run the code here okay so this one accept it let's try to submit it no what ah three zero why i'm returning at zero here it's it should be two here uh let me see here i thought i did everything right here so we have this things dfs 0 1. um oh here we didn't assign this thing back to the answer right that's the that's why i think here oh okay but we did a sign here weird okay uh let's try to test that three here did we return the answer okay um oh yeah sorry i why define set the value twice here okay all right okay cool so now this time it's accepted let's try to submit it here this is humiliating nine is six okay knight is six but i'm getting six but it should be 14. okay so here we have zero uh the base case and this is the bits okay helper bits plus one plus df as one zero okay helper is the same we reverse that and then if it's okay yeah i think because i know since it's always hard to type while you're talking basically we're trying to check if the first bit is one right and then yeah okay cool so i think this should pass all right finally cool so it's finally accepted cool yeah i think that's the first solutions here right i mean this is the solution that's i think it's the it's a regular approach and in terms of time complexity you know since i think let's assume assuming that the length of the bits is uh is n here or the l here right so every time when we do a bit here right we have dfs and we uh we do dfs basically every time when we will reduce the length of the uh of the bits by one until we reach the last one so i would say like the time complexity is something similar like o of l which l is the length of the uh the beat the bit string okay so yeah i think that's the first solution i want to talk about today i would be talking about another unusual solutions which is called the great code you know but first let's try to let's recap this solution a little bit basically you know for these solutions i mean the main approach is that we have to be able to utilize those two options you know and you have to be able to find out right so in order to uh to change the values of the none uh other than the rightmost bits you have to use the second rule and to use the second rule you have to be able to transfer this original string into something like this so that you can flip this the first the left most bit okay and to do that first uh you have we need the helper functions basically to uh to convert uh the remaining string into a one zero pattern okay and then late and then we can just uh recursively call the dfs to help us to uh to convert the remaining right for us and then the next one will be a sim the next one step is just to uh define the helper functions here and for helper functions here they're like there are two cases right so if the first if the left most bit is one then it's easy we simply so now we just need to uh convert this xxx to uh to zero so that's the definition of the dfs and for the zero case it's a little bit more complicated which means that to be able to flip zero to one because that's our goal state right we have we then we will go back to the second rules here so we have to somehow convert these things to uh to s 0 uh s one zero and then we can flip the first bit to one and then the remaining will be uh i mean we'll fall back to the dfs which is to convert this one zero to i mean to zero which we can just recursively call the dfs so hence this is the definition of the helper function and after that it's just like a field base case right that we need to be careful and then uh it's this right so for dfs we just need to uh be careful with the leading zeros which will be uh skipping in this case okay cool so now for those who are interested in the second unusual solution this thing is called grey code so what is a great code i mean for example right let's say we have like this uh n equals to six here right i mean if you watch it closely you mean you guys can see here so we have one zero for one zero it converts to uh zero one zero okay and then from zero and zero it goes to uh zero one okay and then it goes to uh zero one and then in the end it's zero um if you up if you observe this uh long enough you might be able to find out you know basically between each of those two adjacent numbers there's only one digits difference for example right so if for this two right the difference is this one basically the zero uh the one was changed to zero and between those two right so not the zero becomes to one same thing for this one the this one becomes to zero and for this for the last one this is the last digit it becomes to one oh sorry the last bit digit from one uh to i to zero so any two adjacent numbers the difference the only there's only one bit difference and that's exactly the definition of the gray code so you know actually there in lead code if i remember correctly there is like this midi level problem ask you to generate like the uh generate the uh a list of the uh after the grade code given like an integer so that's exactly what that problem is asking us to do and it tells you the definition of that i think it's number 89 or 98 i don't quite remember that but if you're guys interested you can take a look at that and so if you can realize that this is like a gray code uh format um so and if you are the uh for the numbers equals to three equal to three right so basically there are three uh bit digits and to generate the degree code alpha of n equals to three right so that's going to be a what it's going to be a 0 and then it's a 0 1 and then 0 1 0 and then 1 0. so the next one is i think it's a one uh let's see what's the next one so the next one is one and then the one zero one and the last one is one zero okay so that's the uh that's the one of the grey code for the digit uh for the bit size length equals to three and now you can see that so now we just need to it ha now the problem comes down to what's the how many uh the what's the numbers right what so what's the number that's uh how many steps we need to convert from the uh from zero to this one zero so how many of that so we have a one two three and four it's just it happens to be our answer okay cool so okay i know you guys still uh confused at this moment so let me comment out this algorithm here and then so i think first in order to use that the gray code solutions you guys need to know what's the uh how did we calculate that basically you know the uh to calculate the uh the grid code right the gray code is the uh we do a i in range of the uh divided by n right so and then the uh the answer is this the answer is like for example we have a list here so the greek code is answered dot append the uh what is that the i uh x or the uh i moved by one so that basically that's how the how we uh calculate the uh the grid code so why is that right and okay so first we have zero right i mean uh zero we have zero uh do a right shift by one is also zero so zero or zero equals to what equals to zero okay right so that's the that's our first grade code and now the i equals to one here right so the or one so the one moved by right shift uh by one is also zero okay but with the xor here now we have one here so this is like zero now we have one which is zero one so now we have uh we have two here okay so now i is equal to two which means is the one zero and do x or with the what with the uh so 1 0 we do a right move a right shift is going to become 2 0 1 right so with this do it with xor we have 0 1 okay and so on so first right now we have 3 here so 3 i equals to 3 is this is 1 and 1 right we do a so 1 and 1 we do a right shift by 1 it's going to be a it's also a 0 1 okay right and now 1 dual x or with 0 1 we have uh let's see what we have uh zero one zero okay now the next one is what we have uh so now the i equals to four right so four is this four is the uh one zero right to uh xor so this one moved by one is zero one zero so what do we have here we have a one zero and this is the uh the answers we need here right so it happens to be six okay i'm just doing this just trying to show you guys how do we calculate this grade code right and that's basically the formula of calculating the uh the degree code and if you guys watch closely now we have a what do we have here we have this six here right so six it happens to be the one zero and what's the uh the answer here so what's the uh the values we're looking for here basically we're looking for the i here because i is the times right it's the time that we got converted right we got to convert it how many times it's got converted to the to this one two to six here that's that happens to be our answer right because the uh you know the i represents the times right times we uh how many steps we have taken from zero to this one zero that's and that's exactly what we need because at this moment right so the i is equal to four right so it means that because you know see the i is the index as the index to get to the current state and that's the uh that's the so basically when i equals to four we get uh by doing this i do a xor with uh i shift by right to right by one we uh we get four uh we got this one zero so now the problem comes down to the uh if you want uh with this given like uh 1 0 here how can we get the i here where i with this formula okay um so how do we do that right i mean we can see we can do a simple check here right basically you know if we draw it closely basically this is 1 0 and so with i and i uh right shift by one let's say we have a b c d e and f and this is i okay this is i and so i shift by one what do we have zero a b c d and e right so this is zero okay this is the i shaped by one here and here we have it doesn't really matter let's say we have one zero uh one zero one okay and this and basically this is going to be our n here right so which is n here and this is formula can we get i here we can right so because you know uh let's take a look so with one here and we and remember we're doing like an uh an over here okay we're doing like an x or here so when we do an xor so to be able to get one here so we only get one when these two numbers are different and with the first one equal to zero it means that a has to be one okay and when a equals to one here right and a is one a is also one we have zero means same when the numbers are the same then we have zero which means b is also one and when b is one uh we have one here it means that c and b has to be different now the c is zero so on so forth we have zero okay so with zero it has it means that has to be the same so d is also zero and with d goes to zero we have zero here and e is also zero okay and with e equals to zero and we have one here so we have one dual x or then we have one here so that's so the final answer is basically one zero one and that's going to be our i here okay so that's that okay cool so now the problem comes down how can we calculate that right so as you guys can see all we need is just like up a last digit to record what was the last digit and then we just uh with uh based on the current digit the is current dj if it's one or zero we have a different logic here okay so what i mean by that is this okay i'm going to comment out these things here so for your guys reference so uh we have answer equals to zero right and then of course we have a bits uh yeah we still need the bits here okay so we have a bit here now uh like i said we need the last bit right to uh to tell us the uh what was the last one and at the beginning if you guys remember we had like a zero at the beginning right so because at the beginning we have a b c d here right and there's a b c so at the beginning the last digit is this one right which is zero okay so and cool so we have four i and bit right in enumerate numerator bits okay so and since we're going to check to flip it right and i'm going to convert this bit to its integer format first because remember so now the bit is a string here so the reason i'm doing it is it's because i'll be checking that right so uh here okay one zero okay so it means that okay so now we are at this bit here right so if the bit is equal to one so what does it means that you know it means that uh the answer we're looking for here has to be different as the last digit okay in this case it has to it needs to be one right so which means that let's say we have a current bit right we have current bit it means that it has to be uh i've been the opposite of the last bit which means if the last bit is zero uh this one will be one if it's one then this one will be zero so to do that we simply do our xor we is one that's how we convert basically how we flip the numbers of this last the last bit okay so that's that and else as it means else means if the bit is zero in this case if it's zero it means that uh our this our current bit has to be the same as the last bit okay so current bit equals the last bit okay now we have the last bit now we just need to uh do an answer here right so we have since we're calculating these things from left to right so in order to do that right we just need to do a answer uh do a left shift by one and then we plus our current bit okay that's how we calculate because at the beginning we have one here right and then let's say for example let's say the second bit is also it's also one here so what's the total number of this so we have to move this left and move this the previously answered to the left by one so that we can uh have a position for the current bit that's what we're doing here and here if we have a zero here right i mean we have to move the previously answer back uh left to left by one so that we can add this one cool and yeah don't forget to update the last bit here with the current bit okay and in the end we simply return the answer right like i said that's the answer is the i here cool let's try to run the code here accept it submit yeah as you guys can see this one is it's faster because i think for this one the time complex there is just it's one right because the uh for the bits the length of bits is fixed i think if it's in the range of 32 that's why this one is much faster cool yeah i think that's pretty much everything i want to talk about for this problem yeah if you guys do have some questions just leave a comment i'll try to try my best to explain to answer it and otherwise yeah i think thank you so much for watching this video i know it's a long video thank you so much and stay tuned i'll be seeing you guys soon bye | Minimum One Bit Operations to Make Integers Zero | making-file-names-unique | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109` | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. | Array,Hash Table,String | Medium | null |
1,254 | hi everybody today we're going to solve a graph question from lee code number 1254 number of closed islands this question is very similar to the number of islands questioned but with one additional requirement so the question says given a 2d grid consisting of zeros representing lands and once representing water an island is a maximal four directionally connected group of zeros and the closed island is an island totally oh left top right and bottom surrounded by once and then we should return the number of closed islands for this example you're given a 2d grid with zeros and ones islands of four directionally connected zeros top left right and bottom and closed islands are completely surrounded by once and you should count the number of closed islands for this example the total number of closed eye lens would be two so you're given this grid this 2d matrix and you should return 2 as the output because this grid has 2 closed islands so let's manually check the number of closed islands based in this example we can see that we have 4 directionally connected zeros here so we mark that as a potential island that's this and this so they're connected at the top at the left at the bottom and at the right so four directionally connected zeros is a potential island and a closed island is one that's completely surrounded by ones so we can see that this island is also completely surrounded by once so this is a closed island we can also see another instance of zero here this is a lone island with just one zero and that's something you might want to clarify with your interviewer but an island with just one zero is valid at least for this example and it's completely surrounded by once so it's a valid closed island so let's mark that so this is a lone island with just one instance of zero which you might want to clarify with your interviewer which is completely surrounded by once here so it's a valid closed island we do have other instances of zeros that could potentially be closed islands for this example here uh this one at the top also not a closed island because it's not completely surrounded by uh by once i'm not also sure if it could be a valid island because it's not four directionally connected zeros just one not at the left um right and it's only connected at the top and at the bottom so might be a potential island but not a closed island because it's not completely surrounded by once it's only surrounded by ones on the left side so how do we solve this question the first thing we should note is that we first of all have to determine whether something is an island before checking if it's a closed island any four directionally connected series of zeros could be a closed island so when we encounter a particular instance of zero in the 2d grid um as you know i'm going to be using the words grids and matrices interchangeably we just know they mean the same thing in this context so when we encounter a particular instance of zero in the 2d grid we can proceed to run a depth first search on its four neighbors to see if we can get a series of directionally connected zeros while doing the depth first search if we encounter a 1 we stop traversing that path and keep traversing other paths if we have fully exhausted all the paths without going out of bounds then we know that this is a valid closed island because we exhausted all the paths and then we encountered once without going out of bounds if we ever go out of bounds without seeing a 1 then it's not a valid closed island so i'm going to do a quick simulation of how this would work so we're traversing this 2d matrix and we encounter an instance of zero in this case let's say we encounter this instance of zero so when we encounter this instance of zero we then proceed to run a depth first search and check for all its four neighbors so we run a dfs here and here so if we encounter a one we don't actually stop the dfs um completely we just stop traversing that path and keep traversing all the paths so for this one we've encountered a one here so we stop traversing this path we encounter one here stop traversing this path but notice that the path on the right this path has a zero to it so in this other zero that we encounter on the right we're going to keep traversing its other neighbors we run a dfs here for each other neighbors run a dfs here uh we don't run a dfs here because we're going to have a case that checks for that since we've already checked it when the df is here and here so at the top we see that it's a one so we stop traversing this path and then keep traversing its other paths the other paths have another instance of zero that's this one here so we proceed to run a dfs on its four neighbors so that's this one at the top we don't go to the left because we've already um gone through it we're gonna have a check that checks for that and then this one has an instance of one so we stopped reversing and then we come to this other guy here we also do the same thing we go to its four neighbors which is top right left we don't check bottom we check and then we've encountered all of them have a one so we stop this path and then stop this path but notice that we already have other depth-first searches depth-first searches depth-first searches running on these paths that have zeros that we haven't checked uh the bottom neighbors the left neighbor and then we'll do that for this path as well so when we come here it's an instance of zero we check its four neighbors this also has an instance of one at its bottom neighbor so we stop this dfs we stop it here also and then we do the same thing for its other neighbors which is this one and then we come down uh you kind of get the idea we get a one and then we go to this other guy that's a zero so the guy's a zero and then they both have ones at the bottom so we stop here so this is it after we've completely exhausted all the paths and then we've encountered once without going out of bounds in this 2d grid then we know that this is a valid closed island so this is how you solve this question as always with these types of questions we need to mark the cells that we've visited so we don't count them again if not we're going to have the risk of running into a potential cycle and we don't want that so how we're gonna do this is to change the value of zeros that we've already seen as part of a series to a one so we don't get to that again so for instance when we've encountered this zero here we change its value to one uh gonna this is going to be messy we change its value to one so when we're on this path and we're checking its four neighbors we check to the left and we see oh this is a one so we don't check it so after encountering a zero in a particular series we have to change the value to one so we don't come back to it again and we're going to do this for all these zeros in this island i hope this makes sense to you and now we're going to proceed to the time and space complexity the time complexity for this algorithm would be o of n in the average case since we're going through all the cells in the grid in the worst case it could potentially go above that because uh we can also do potentially an amount of work for the dfs and while doing the iteration uh traversing the matrix we could also do an amount of work but that's in the worst case for instance consider like you have a huge 2d grid of like just once on the edges on all the edges top left right and bottom and then zeros in the middle completely filled with zeros in the middle what you'll find is when you encounter a particular instance of zero in the middle you're going to potentially do an amount of work on the dfs and you're also going to go into the iterative approach while you're iterating through to check for zeros now you're not going to hit the dfs again but you're still going to check whether because we're going to change all the zeros to once so when you're going back you're going to check whether it's a 1 or it's a 0. you're not going to hit the dfs again but you're still going to do that check but in the average case it's o oven in terms of space complexity would run in of d because we're going to have a recursive dfs search which would store frames on the cool stack and the number of frames in the code stack would be as much as the deepest path so we'll say space complexity is o of t where d is the depth of the deepest path so that's it let's dive into the code alrighty so we have our closed island function here it should return an integer we also have our input 2d grid so the first thing we want to do is initialize a counter variable so our initialized count we set it to zero and then now we're going to iterate through uh the 2d grid this is going to be a nested for loop so for an i is equal to zero i is less than i would say grid.length and then i plus i would say grid.length and then i plus i would say grid.length and then i plus that's not the way you spell length i'm gonna fix it and then you say for j is gonna go through the columns so j is less than let's say grid of i dot length j plus and now we have access to grid of i and j a particular cell in this grid and then we can check if that grid is equal to a zero so if grid of i j was equal to zero this could be a potential island so whenever we encounter an instance of zero we're going to run all run a dfs on this instance of zero because it could be a potential island let me fix the length spelling and then we're here so we're gonna declare like a method that returns say a boolean value if it's a closed island and then we add one to it so let's say boolean uh closed uh the method would be called is closed we haven't made it yet we'll make it soon bear with me and then we pass the grid we pass i and j into it and then we can check if closed if this returns true then we increase the count plus one so now let's define the close um method that we just used here so we have a public boolean is closed it takes in a 2d grid takes in a row and it also takes in a column so for this we're going to have a base case that checks this is our depth first search by the way we're going to have a base case that checks if we're not out of bounds so if rho is less than zero or the value of the row is greater than grid the length mints were so far down that we're out of bounds and then we have column is less than zero means we're so far left that we're out of bounds or the column is greater than or equal to the grid of row dot length means we're so far right that we're out of bounds if this is ever the case then we can just go ahead and return false because we know that we're out of bounds so we turn false so this is the base case otherwise if we're not out of bounds then we can check to see if this value is a zero or a one remember if this value is a one then we can just stop traversing this path so if grid of row and column is equal to you guessed it one then we can just return true and stop traversing this path so returning true because we don't want to return false and then stop the whole dfs and then if it's a one otherwise if it's not a one it's going to be a zero so if it's a zero then we have to change the value of comments change the value to 1 so we don't come here again so we're going to set grid of row and column is equal to 1. so this is a quick check that makes sure that we mark the cell as visited so we don't come here again i'm going to do a more detailed comments for the code that i upload to github so please check it out and then we're going to run a dfs on its four neighbors so we're going to have a boolean variable we call it bottom this is going to check for its bottom neighbor so this is closed we call the same function that's why it's called recursion i have grid row plus one it's going to go at the bottom and then we have column uh this is for bottom and then we have another variable this is going to check for the right neighbor let's call it right uh is closed we pass in the grid we pass in the row and then we pass in column plus one just gonna check for the right and just call this right and then we have another one for the left this is gonna be is closed we pass in the same grid same row now column minus one and then this is going to be left and then we have another one for the top and this is going to be is closed we have grid pass in the same grid now row becomes row minus one and our column remains the same and this is going to be for the top so this is going to run four dfs searches on its four neighbors and now we want to make sure that all of these return true because they're only going to return true if they encounter a one at the particular path so we return at the end bottom returns true and right returns true and top returns true and left also returns true they're only going to return true if we encounter a one before going out of bounds awesome so this is the method and then here if it's close we call this method and then we increase count plus one now the only thing we have to do is return count that's it that's how you solve this question let's run this and see what happens awesome it's accepted i'm gonna submit it yeah it's uh it's successful and it's really fast so that's how you solve this question guys uh i hope you learned something from it well in my experience asking clarifying questions is a major part of the interview so please let me know if you want to me to include some of the clarifying questions that you might ask for a particular question you know like inputs edge cases uh in my videos and i will do that so comment down below let me know what you think so that's how you solve this question if you like this type of content please consider subscribing to the channel share this video on the community smash the like button for the youtube algorithm comment down below if you have something to say and i'll see you in the next one bye | Number of Closed Islands | deepest-leaves-sum | Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.`
Return the number of _closed islands_.
**Example 1:**
**Input:** grid = \[\[1,1,1,1,1,1,1,0\],\[1,0,0,0,0,1,1,0\],\[1,0,1,0,1,1,1,0\],\[1,0,0,0,0,1,0,1\],\[1,1,1,1,1,1,1,0\]\]
**Output:** 2
**Explanation:**
Islands in gray are closed because they are completely surrounded by water (group of 1s).
**Example 2:**
**Input:** grid = \[\[0,0,1,0,0\],\[0,1,0,1,0\],\[0,1,1,1,0\]\]
**Output:** 1
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1,1\],
\[1,0,0,0,0,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,1,0,1,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,0,0,0,0,1\],
\[1,1,1,1,1,1,1\]\]
**Output:** 2
**Constraints:**
* `1 <= grid.length, grid[0].length <= 100`
* `0 <= grid[i][j] <=1` | Traverse the tree to find the max depth. Traverse the tree again to compute the sum required. | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | null |
1,046 | Effect of Come in City Will Discuss Your Problems and a Good Practice Problem Number S-10 600 800 How to Problem Previous Number S-10 600 800 How to Problem Previous Number S-10 600 800 How to Problem Previous Two Pure Problem Statement Saying You This Collection and Stones is a Stone When Positive Integer Constant Subscribe subscribe and subscribe the Channel Please subscribe and subscirbe kal su appeal will see a distinguished to example som political science the winners in three ok channel every element is point office to every time you will have to pay a and pintu highest slips to share the first hai bittu stories 80 to them inconsistent check subscribe this Video subscribe The Channel 2451 subscribe to hai next time in new topic on jiomusic to every fluid floor and to its key and differences to su 22.51 key and differences to su 22.51 key and differences to su 22.51 phone number is trick height acidity 2.1 phone number is trick height acidity 2.1 phone number is trick height acidity 2.1 difference is lineage effects to the native with a big station between itself Tasty Swayam Contested Polls While Some Differences 0 Friends Paper Solved With One And Only One Will Be Given To Last Post Hai So Alas At The Time Of Vansh Arise And That Nothing Can Visit Us At Same One Was Left With Differences 09 2012 When Glass Is Broken That And Arrival To This Position In Jawa Aa Birthday To You And Sunao Then Difficult Problems Statement Clear Subscribe To And Sunao And Laughter They Need Active Left Which Suit States Were Doing First Step More Into Every Storm On We Will Bring You To Harishchandra For 20 Minutes Sentence with same to oo ke din but this trick dil vigrate difference office to it back into the I am behind it this 1078 - subscribe to that a cigarette global economic Indian servi dil report tomorrow su up into her best to generation supporting but set And Repeating Itself Subscribe To's Comfort Is Produce Problem That Needle Normalized Money On This Photo A Superlative Inspired Other Day Updater Have To Think How To Make A Game And Where To Check The Next Come 12.28 Will Get To Check The Next Come 12.28 Will Get To Check The Next Come 12.28 Will Get Located Today Date To Eyes Difference Between The Two Retail Pack Looting Back A Victim Has Never Had To Find The Maximum Minimum Set Max Planck Institute For Looting In School Me Sonth Developed In The Other It Is Not Reflecting Upon A Time When Ever Taken Back In The Distic One Is So What Status Chakra Ki Can Help Us In This Case So Remember What Is That Don't Get A Structure Which Will Always Give Me The Highest Element Pepperment Is Remedy Hai 125 I Pick And Tagged Statement Outfits Words A Requested Status Questions Page President Will Quit Comment Questions on that this is the same and something to get a structure relative automatically modified just how to take and give me the house film the swift deliverer from the same options updates the loop this time frill slow this is so then I no numbers and you will get any If you are happy enemy but for profit subscribe to I want you to high school at you will get in we fight positive group are those who have village text sidhu loot-loot subscribe Video subscribe to the students to a hit is the good choice that Suno Koi Limit Decade Program Point How Little Things Pay Next Key Facility Program New Super Store Here Designer Maximum subscribe and subscribe the Channel Please subscribe and subscribe the Play List This Too Phone The Input Tray Weeks Hind Desh Hai Mix It 's Naresh Aggarwal Defined Usual Open Store 's Naresh Aggarwal Defined Usual Open Store 's Naresh Aggarwal Defined Usual Open Store New Delhi Stories And A Massive And Stuart And Sunao The Match Declared Photo Are Different This Film With Obscene Mail Send That New Item Different Oil Filter And Oil That Playing With This By Maximizing That Sudhir To Get So Thokta Hai A look size duets to sanch ki should be but incomplete ko suhaagin kitchen retention the sizes is vansh rate so imported to subscribe to main day bhar due to il spoch to first elementum settings hua hi is the fastest man made it's next flight 's note loot Take 's note loot Take 's note loot Take A Sweat In Return To The First Festival Securities You Got Two 200 Is All About This Cool Message Do Call Me Three Minutes Ago Vitamin Root Element And To Do Don't Forget To Subscribe And Subscribe To A New Picture App Is While That's Not Equal To That this infallible owner notification loot subscribe to is so ifin there is this new Delhi ex showroom in this manner of this example my vice president and eggs subscribe to improve time that he nautical tricks and determination and defeat at this point - 6 subscribe sunna hai i Re Written Complaint Police Complaint At Last Way Subscribe To Channel Just Stop Subscribe Suggest Hai Se Mix Itne Dot Size Were British 1221 Divya Ko Return Se Mix Itra Dots Hai Pimple Last Present Distic Institute Of Medical Research Root Element To Retail But Not To Delete Paun inch this liquid Subscribe 0 A look on hua tha so let's Ramdev was not arrested medium of your note hua tha ok so running dir with submit picture ki this distance id ki and teaching staff nurses and 210 aspirants tow here This election na tomorrow morning get fat solution 9th class and share with your prescription torch start winning MP3 money loot | Last Stone Weight | max-consecutive-ones-iii | You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000` | One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on. | Array,Binary Search,Sliding Window,Prefix Sum | Medium | 340,424,485,487,2134 |
403 | So Frog Jump So this is Lead Quote's 403 challenge so come on guys let's see what the problem is A frog crossing a river The river is divided into some number of units and at each unit there may not exist a stone The frog can jump on a stone but it must not jump into the water. It means that suppose we have given a river and somewhere in the river we have placed stones at some position, okay and whatever those stones are there is random. They will be in ascending order but the stones will be placed one after the other. This is not necessary. It is not necessary. The distance between them can be varied. It is okay. Given a list of stones positions means the positions of each stone are stored in this unit. Ascending Order Determine If the Frog Can Cross the River by Landing on the Last Stone Initially the frog is on the first stone and assume the first jump must be one unit. What this means is that our frog will initially be sitting on the first stone and assume the first jump must be one unit. The initial jump that the stone can take is one unit. This is given to us. Okay, if the frog jump was k units, its next jump must be between k -1 k and k + 1 units. k -1 k and k + 1 units. k -1 k and k + 1 units. Frog can only jump in the forward direction. So come on friend, let us understand this well through a diagram. The problem is that Google's position is actually given in the form of an array and its indices are given. Let us understand this through a diagram like this. Suppose our stone, the first stone, looks like this, the second stone looks like this, and the third stone, there is water there, okay, and the position of our fourth stone is this, and the position of our stones is something like this. What we have been given initially is that our frog is sitting on the first stone and from here he can take a jump of one unit. Okay, so we have assumed that the frog jumped from here and came here. Now how far can he jump from here? Can take jumps, if our frog had reached this stone on the second stone in the last jump, then from here he can take a jump of K, and can take a jump of K, okay, so here What was its last jump? k = 1 What was its last jump? k = 1 What was its last jump? k = 1 ok, it was reached in one jump, now from here 1 pv that is two, it can take two jumps, it is right here, it is here, from here one, two, it can reach here ok. And what is one? If he jumps only one, he will reach this stone and that is 1 minus zero. Okay, so is there any benefit in going back, so if that value is coming to zero or less than zero, then we will ignore it. Okay, so in this case, let us assume that he had reached this eye stone in some cath jump. Okay, so at this position, we will explore all the possibilities as to where else he is able to go from here. Okay, if at the end, our Frog is, out of all the possibilities, if it comes to the end stone in any one of the possibilities, then we will assume that we will return Tr. Okay, in this case, because we want to return Tr, we have to get the frog to the end index. We have to deliver the last stone or the last index which is our 17th last stone. If our frog comes here, then brother bye, if it doesn't come then return false to us. Okay, so come friend, let's see how we will approach this. What is the problem? How will we solve this? So on the other hand we can use SAP in the sense. We use the concept of Yup. What we do is we put all our stocks in the map. Okay, so our stocks. What was their position, what was it was okay, zero and 3, 6, 8, 12 and 17, let's just write down these, we will not store them, tooth 4, 5, sorry, tooth four, 5, 6, these are our cusp, we will store a set. Why should we store it, let's see, okay, pay attention, okay, now initially what we have been given is that our frog is sitting at the zero position, okay, from here it can jump to the first position, so why don't we make a set? Take the first stone cadence and store its cusp one, what is this one is ours, which is our first stone in the jump, I mean, our frog which is in the forest can jump from the first stone, it is okay, so we Here, we will take out the number corresponding to zero and from that we will see to which position our frock can go. Okay, suppose we have taken out one from it. On the cusp of the corresponding stone of the first stone, we will store that jump. Okay, here in which jump did he come, we have made 1 psv, that means two, in the second jump, that means two units of jump, in the third jump, our cusp has come, so here we store two, okay here we have paid two. Got it stored and what are the possibilities, either just what did he do? He took a jump of 1 pv. If he had taken a jump of only one i.e. if he had taken a jump of only k then he would have been able to reach i.e. if he had taken a jump of only k then he would have been able to reach i.e. if he had taken a jump of only k then he would have been able to reach here near our first stone. Okay, so first stone k. If it comes close, here we will store one that it came here in one unit of jumps and what is the possibility 1 - 1 0 friend, if and what is the possibility 1 - 1 0 friend, if and what is the possibility 1 - 1 0 friend, if zero value comes, we will stay there, if negative value comes, we will ignore it because we We don't want to go back either, we don't want to get stuck there, okay, we have explored this, we have explored the corresponding values of this stone, okay, now we come to we have explored the corresponding values of this stone, okay, now we come to we have explored the corresponding values of this stone, okay, now we come to our second stone, which of ours is corresponding to the second stone? Value store is one. One is value store. What does one mean? This is its Keith jump. Okay, here it came in Keith jump. Unit of jump came in it. Now let's explore it. Okay, we took out one. Okay, now where from one to where? It can go 1 pv ok 1 2 On our fifth index pe I mean on the fifth stone it can come in how many units of jumps it came in two units of jumps ok and what is a possibility this is only one unit jump Take, if it takes a jump of only one unit, then it will come to its third stone, third means second stone, so here we will store one, okay and 1 -1 0, again the same thing, so okay and 1 -1 0, again the same thing, so okay and 1 -1 0, again the same thing, so we will ignore it, okay this too. We have explored it, now let's come to this, first of all we will take out two and from two we will see what are all the possibilities. If we do 2 then we can take three units of jump. What will be the jump of three units from here? One or two is fine. So our sixth stone I mean one two three on the cusp of our eighth stone we will store it by taking a jump of three units, it is okay if we take a jump of only one unit from here i.e. a jump of only two units then taking a jump of three units, it is okay if we take a jump of only one unit from here i.e. a jump of only two units then one two will come here only and If we take one, then it is okay only here. We have explored one. If we take 1, then who will come here, in how many jams, two jams are fine, so there is no benefit in storing duplicates here. No, so we will use set, it will automatically ignore the duplicate, okay, we have two already stores, if we jump one unit, we will come here, there is one already store, 1 mine, if it is of no use, then we will ignore it, we also explored it. Now let's come to this, from here we will take two, now two is okay, we can take a jump of three units from here, one, two, three, okay, then we will come to the 12th stone, it is okay if we take a jump of three units. Meaning if we take only two then one or two will come here only and if we take only k -1 jump then if we take only k -1 jump then if we take only k -1 jump then only one will come here so we correspond to this 1 + 1 2 two are already stored if 1 + 1 2 two are already stored if 1 + 1 2 two are already stored if one copy is taken Already stored is 1 -1 zero one copy is taken Already stored is 1 -1 zero one copy is taken Already stored is 1 -1 zero so there is no use of it, now let's explore it. Okay, from the extract we can write a couplet. The catch here is that if our stone is at any position, I mean, which is our frog and the last one. If it reaches the stone, then what will we do at the same position, will we make it return? Yes, it is done, okay, this is our question, if suppose in the end, at some time, our frog is not able to reach here, okay here? But suppose there were different positions, then how would one become such that it is not able to reach here. If it is not able to reach here, then we will come out of the loop and we will return false there. Okay, so this is our problem. That friend, let's code this and go ahead, friend, let's come and code, what will we do, will we create a name, what will we do, store all the stones in the map, store its coding in one MT set, okay, we have stored it now. It is given to us that we can take the first jump and neither can we take the first jump of the unit, so what do we do after storing that, okay, then M of stone of zero, now let's explore all of them, let's keep it in our current stone. Let's take a set. What are we going to store in the set? Its cusp set is stored. S is equal to a of. We're going to explore this. Okay, we're going to take a look at it. Now, what we want to see is what we want to see if we look at any current. If we are jumping at a position, does the stone exist in our array or not? If it exists, then only we will go to it. If it does not exist, then we will not go, only then we have to do some work, otherwise we do not have to do it now. We have three possibilities of yours, K, P, K and K. Let's explore it. It is human, it is greater than zero. Okay, if we are doing minus then it should be greater than zero, only then we will explore that point, otherwise we will not do it. What will we do? M is off position. Let's do errt aa mine is a possibility let's do i mean insert ya how do we know that our frog has reached the end so we put a not condition here if our position is equal to If the stock of stock is equal to size mini, it means that the frock has reached the end, so we will return it and if our return is not true anywhere, then we will return it. If it is false then the answer is correct. If you try submitting then it has been submitted, ok, that's all in this video, thank you for watching and see you next time. | Frog Jump | frog-jump | A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of `stones`' positions (in units) in sorted **ascending order**, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit.
If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction.
**Example 1:**
**Input:** stones = \[0,1,3,5,6,8,12,17\]
**Output:** true
**Explanation:** The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.
**Example 2:**
**Input:** stones = \[0,1,2,3,4,8,9,11\]
**Output:** false
**Explanation:** There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.
**Constraints:**
* `2 <= stones.length <= 2000`
* `0 <= stones[i] <= 231 - 1`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order. | null | Array,Dynamic Programming | Hard | 1952,2262 |
48 | everyone welcome back to my channel so today we will solve one medium level question so till now we are solving easy level questions today we'll go with one medium question it's called rotate image let's understand the problem statement and try to solve it so it's very interesting question and let's see how uh it proceeds so you are given an n by n 2d matrix representing an image rotate the image by 90 degrees clockwise so a matrix image will be given it can be n by n okay 3 by 3 or 4 by 4 matrix will be given we have to rotate it by 90 degrees so this matrix if you see one two three four five six seven eight nine if you rotate clockwise so in the clockwise direction if you're rotated by 90 degrees what will happen whatever uh this row will there be the first row will be there right it will become the last column second row will become the last second column third row will become first call so similarly if you take this example four by four matrix same thing if you rotate by 90 degrees so this first row will become last column similarly second row last but uh last but second column this third row will become second column and fourth row will come first column so constraints also we have to see and one more condition you have to see you have to rotate the image in place so this thing he is for he has focused here so you should not take another array and you should and copy that so here you have to rotate without taking extra space okay time complete space complexity should be of one and we should not use any other matrix so let us understand how will solve this the logic will be right what we will do first we will take the transpose of this matrix and after that we will reverse this row so ah one two three four five six seven eight nine for this example if you take transpose it will be like one two three these values will come here and these values will go here and after that if you swap the rows right then we'll get the out resultant output so let's try to solve this first step find transport of transpose of a matrix and in the second step reverse each row so transpose of a matrix let us see how we can do so let's try to write the code for that what i'll do first i'll i trade through the rows current i equal to 0 i less than matrix dot length i plus so this loop is used for iterating each row okay now we'll take another nested loop here for and j equal to i j less than column length so what is a column length if you take the length of one row that will be the column length j plus so why i have taken i here if you take the first row by rotating first row will start from this first value and if you take the second row will start from the second value so here if we are only flipping the diagonal uh above and below the diagonal elements we are swapping here so we'll have to write one condition if it is a diagonal element will not do anything if i not equal to j then only we have to swap what i'll do in temp equal to matrix of i comma j next matrix of i comma j equal to matrix of j i and matrix of j i equal to 10 so here we are swapping those elements so let's take a let's do some dry run here we'll understand first row i equal to 0 and j equal to zero okay i less than matrix short length matrix dot length what is that in three okay and j less than matrix of zero dot line that is also three i equal to i not equal to j no this condition will fail again i will increment i equal to 1 sorry j will increment j equal to 1 i equal to 0 j equal to 1 now i not equal to j yes inside come inside temp matrix of i zero j is one zero comma one is two temp will have two value next in place of two what will we will add in place of two will add matrix of one comma zero is four so four will come here and matrix of one comma zero in place of that temp value will come some value what we had two so here two and four will get spam similarly j will increment j will be 2 down i equal to 0 j equal to 2 and it if this condition also will satisfy less than uh 3 so not equal to j satisfied temp matrix of 0 comma 2 3 temp will have 3 now and in place of 3 what will add matrix of 2 comma 0 is 7 so 7 will come here and in this place what will have matrix of two comma zero temp what we had three will come here next if you take j increment three so condition fails it will go above i increment i equal to one no and j will be one now so both are equal so it will come out of this if condition again increment j is 2 now i equal to 1 j equal to 2 10 what will have matrix of 1 comma 2 okay 6. so temp will have 6 in place of 6 what will have 2 comma 1 is 8 so 8 will be placed here and in place of 8 what we'll have well we'll add this 6 so here 6 and 8 will get swap similarly if you go for other iterations uh you will see that this value gets transpose of a matrix now we have got the transpose now we have to reverse each row if we have to reverse each row uh let's write the code for that as well what we'll do for int i equal to 0 same i less than matrix or length i plus next we'll iterate through the column for in j equal to 0 j less than matrix of 0 dot length j plus now for reverse what we'll do same we'll do swapping and let's take new variable let's take temp reverse equal to what we will do we will take the first element matrix of i and j will take in temp now matrix of i j with what will assign with matrix of i and last column will need right so uh here we'll take one variable column length and call length equal to this value will this length will assign there so here will iterate through half of the columns because we are swapping so no need to wait till the end only half is enough so here call length minus j minus 1 okay next what we'll do in this place we'll assign temp so what we'll do matrix of i and colon finish j minus 1 equal to temp reverse okay i think we should be good let's we are not returning anything because we have to do it in place so let's try to run here and see the output it is accepted let's try to submit yeah successfully we have uh solve this problem it takes 0 milliseconds and it's faster than 100 of solutions so this is the first medium level question we have solved and it sounds pretty good here so if it is asked right to do it anti-clockwise direction and you can you anti-clockwise direction and you can you anti-clockwise direction and you can practice that as well let me see if i can do that in the next video that's it in this video from my side thank you so much bye | Rotate Image | rotate-image | You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000` | null | Array,Math,Matrix | Medium | 2015 |
322 | Hello hello guys welcome back to take devotion in this video you will see the question problem which is the way reaction of the bond website problem and destroyed number-22 latest see the problem statement number-22 latest see the problem statement number-22 latest see the problem statement in this problem of different denominations and total amount of money to Compute the Number of Units to Make Money Ca n't Make Any Information You Need to Know That You Have a Number of Centers Problem Latest Example Subscribe Nomination Form for the Number of the Time That Nav in This Case Which Caused His Unlimited Number of Sentences and Also They can select the same in and which bag to give for the giver 910 problems very similar to 1000 problems one instance of each item in the city which you want to send me the number of subscribe this Video Subscribe now to medium possibilities which they can Take Do For This Amount Like They Can Take Your Veins And Still Get This 11212 For This Amount Minimum Number Of The Number Three And Distribution Will Be Number One Number Nine Two The Number Of Units Veer Will Not Be Able To Make The Sentence Of Number Two But Still Not Possible To Be And Will Return - One Who Can Never Give Information Will Return - One Who Can Never Give Information Will Return - One Who Can Never Give Information Center Problem And IF You Are Able To Understand That No Letter cnn-ibn Solve This Problem Understand That No Letter cnn-ibn Solve This Problem Understand That No Letter cnn-ibn Solve This Problem Will Need To Include Request Denomination Coin And Will Move To The Mission Saw It Can Be Easy and Quick Reaction 151 Lips Were Taking Lessons From Left To Right 10000 You Can Tell All The Possible Numbers Of Which You Want To You Can Come Back To Give It's Not Possible 100 To 125 Effects From Left to Right in Adhishta Pro Dushman Ban We can take this one in number of times but they should not exceed this amount so they can take 111 number of times and they can do that and they can improve 2050 number of times and still can make You OK but in this case was possible to the number of which we can give very latest time number to two years were making of the possibility of which will improve 102 numbers subscribe problem will be moving from good night while making and decision Software at this point which can take any number of intensive viewers welcome back to my channel subscribe solve this problem solving all winners will be sent to avoid a number of times when will the example withdraw share this post on reddit share 9f of these posts include this one R Rahman two fonts for improved this 123 Life Again Introduce 1.2342 Baitho Agni Friend Introduce 1.2342 Baitho Agni Friend Introduce 1.2342 Baitho Agni Friend Lotus 1.251 Again Follow Dushman Hamar 1200 Lotus 1.251 Again Follow Dushman Hamar 1200 Lotus 1.251 Again Follow Dushman Hamar 1200 Total Number of the Year Will Be Effective 1.251 Total Number of the Year Will Be Effective 1.251 Total Number of the Year Will Be Effective 1.251 Will Be The Mission 272 Will Not Be Possible For You Dare not possible to do and definition of mid day meal doordesi to in order to get or required amount because someone to be formed into which included in the number of wave width or subscribe like it will pass through the internet and the number of the nomination form. - 151 subscribe this one Subscribe to this channel During the current item which is element is set I will be decreased in this value amount recognition relieving amount sincer including The Page if you liked The Video then subscribe to the detention not Increase and will remain the same and will be the next Navy Chief plus one the designation This is Vivek Android Code IF YOU WANT TO KNOW THE CASES IN THIS PROBLEM NO NOT POSSIBLE TO INFINITY OTHERWISE NO MATTER WHAT WILL ALWAYS BE POSSIBLE FOR ANY FEAR NOT IMPROVED In quantum number 90 dissolves possible to make sure no problem subscribe pimples ok so only very many friends properties wikinews dynamic programming in this that is show latest see the population dp and status understand how to used in order to solve this problem in wearing lips Free Number Of Wave 205 And 206 Taking The Volume To Table Number One Plus One Who Want To Consider Sharing It Will Not Be Possible For This Will Be Doing So Will Be Having No Comments That Where Is Wing Zero Number Of Bones And Mod 108 Not Possible For The Amazing 10 12v Possible To Form 2018 Subscribe To 9V Feeling The Video then subscribe to the Page if you liked The Video then set alarm up two and three What is the Meaning of This Is Not Fair Have enough two points 1243 minimum nine to three use nominations for 2nd nomination can help you can see that you can give one plus one will form the total number of birth subscribe like this is the subscribe akbar to formed a smartphone gas eighth possible by Using one point not fearing amount to will be possible to from December 1872 this point and subscribe will basically Singh Divya nomination in tally solved they will be the year - 1615 one number one instance of the year - 1615 one number one instance of the year - 1615 one number one instance of nomination for the number one and all the value of printed will Get Married And Solar Total Amount To Be Formed Which To Will Know Now Be Discriminated Welcome To - The Missions Youth Discriminated Welcome To - The Missions Youth Discriminated Welcome To - The Missions Youth - 108 Persons 125 What Is The Meaning Of The - 108 Persons 125 What Is The Meaning Of The - 108 Persons 125 What Is The Meaning Of The Name Of The One Who Will Know B Coming Lord Of Improved Coma Explorer Source Pair Including This Dandruff Exactly 2051 Affair Acidity Minimum Way Latest From This Is The Worst Journalists - - - 151 Minimum Of This Is The Giver Subscribe 9 Latest Improve The First Denominations Of Minutes Ago In This One Month To both day what will be the number of birthday celebrate the current situation which is the current date and so will have to only if you liked The Video then subscribe to The Amazing Welcome to the to - to - to - Who is the current wali special 20140 Bauji Roll Number of Mines 2051 Minimum of 12121 This is Not for This is the Invention Co Switch Board The Possibility of Subscribing 12321 Plus One Two The Number 90 Bittu Plus One No Fear Having All This Reading Nominations To Gather Business Share Subscribe Button 123 Four Will Not Be Doing So Will Just Shopping subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the world will be Minimize Yourself Amnesty Exclude Country Global Informatin 3.0 Plus One two three will be Informatin 3.0 Plus One two three will be Informatin 3.0 Plus One two three will be equal to two one in the morning one not for this is a will be making a choice between 10 and improved the current coin the volume to the karate kid from lbm1 total number of oneplus one to know the total number of cases 310 Medium to two the number of which we can do subscribe nothing but a 200 this is the answer this last sale will be actually given all examinations available and examination can have infinite number of points and the given two for this dynasty increase the last salute Give the meaning of this thank you are able to understand nothing which is the problem share the problem subscribe to the Page if you liked The Video then subscribe to the these directions 1200 number of but not improved in these works advice if The Great 2000 Possible To Inform And They Will Be Writing In Adheen 9999 Coins Is The Present To You Will Not Be Able To Join And Subscribe Our Channel Otherwise Wise They Will Be The Meaning Of The Number One Key And Will Remember Simrol Okay Vikas Bhi Arvind SIM number for once again but the amount which they want to know what is not visible DJ - Festivals etc. Total amount visible DJ - Festivals etc. Total amount visible DJ - Festivals etc. Total amount for which will be created nor will just doing so will give the number of the center for solving problems and finally subscribe and subscribe the Not Possible for the Giver - 110 - 110 - 110 Jhaloo Stored in the Last Salute OK Suvidha Center Solution Receiver C Plus Code in Java Code Will Also Be Provided With At This Time You Are Able To Understand If You Have Any Problem And Comment Subscribe Like Share and subscribe | Coin Change | coin-change | You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104` | null | Array,Dynamic Programming,Breadth-First Search | Medium | 1025,1393,2345 |
412 | uh hey everybody this is larry this is day 26 of the august eco daily challenge uh hit the like button hit the subscribe button join me on discord and let me know what you think about today's problem fizzbuzz uh given one two and three and five is frizz and buzz this is silly uh okay um if you're watching this i don't know why you're watching this uh but you know i don't even know how to go into this really well i think the only weirdness is that um you know uh usually you get to print it so you can do some fancy trick you read there but uh but yeah this is just a little bit silly so i'm gonna go right into the code um you could do it a number of ways it doesn't really matter maybe practice for comprehension in python or whatever it is but i'm just going to do it as silly as possible because i don't know it's not really worth my time to think about optimizing it uh and also i did this wrong so maybe i shouldn't uh think about it too much um but and i know that you could do some stuff so that you could uh it does both of them but i don't know it's okay for me oh it's a string of x oops uh i mean it's just i don't know but yeah i hope you enjoyed this problem uh it's a little bit silly it seems like i'm just gonna test a big ish number should be okay either way uh is there a difference i wish they just told us oh i did have an off by one i knew that when i was typing it but i forgot so okay so i was a little bit too arrogant there but that's why you won tests um that's okay uh looks okay and then i just submit uh don't worry unless there's like some weird thing like negative numbers or something uh yeah uh how what is the complexity of this is technically uh two to the n uh you want to call it that because um you take you know it's linear number of uh there's o of n uh number of bits um and for each bit you have to go for every number so there's two to the end possible numbers this is a different end than the input n uh it's so it's a little bit confusing uh but if you say let's say the input is uh just say k um and as you go to the number of bits uh then this is o of two to the n uh though this is a convention that is usually talked about when you talk about complexity freely uh but on interview people probably usually know what you're talking about so you just may have to talk about it a little bit but it's not a big deal right away uh and of course in terms of space you can really do better than um the output sensitive because you have to generate every number anyway um but yeah but for example if n is this n is or k as you go to 15 uh requires like at least uh where is it four bits five bits to represent sixteen on uh four bits five bits uh and that's two to the fourth uh complexity right but anyway it's not a big deal that's all i have with this problem i'm at it maybe i'm a little lazy let me know if you have any questions for this problem because it just seems very straightforward right and i yeah i don't know how to explain this one other than just writing if statements so yeah let me know what you think hit the like button to subscribe button and i'll see y'all tomorrow bye | Fizz Buzz | fizz-buzz | Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_:
* `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`.
* `answer[i] == "Fizz "` if `i` is divisible by `3`.
* `answer[i] == "Buzz "` if `i` is divisible by `5`.
* `answer[i] == i` (as a string) if none of the above conditions are true.
**Example 1:**
**Input:** n = 3
**Output:** \["1","2","Fizz"\]
**Example 2:**
**Input:** n = 5
**Output:** \["1","2","Fizz","4","Buzz"\]
**Example 3:**
**Input:** n = 15
**Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\]
**Constraints:**
* `1 <= n <= 104` | null | Math,String,Simulation | Easy | 1316 |
73 | what's going on guys it's your boy Chuck here we have another leak code problem I actually solved it already and I got it right surprisingly on the first try I figured my solution was to some degree unique so I wanted to go over it right now I'm very new to the leak code scene I've solved 84 problems to date so I'm still getting a lot of practice but the fact that I was able to solve this one problem made me feel really good I guess I would say so uh because I at least for me it's not very often that I'm able to see a problem and solve it just right off the bat without looking up some sort of hints on Geeks for geeks or something of that nature right so that I mean that probably happens at this point at my skill level maybe 25 of the time where I'm able to just solve a medium or hard problem just off rip um now for easy problems a lot more successful but that's neither here nor there I came to talk about my solution so let's go ahead and go over this solution okay so I have my notes by my side just in case we're gonna have to or just in case I forget something in particular I don't want any bugs um but the essential idea that I had was I was going to iterate through every element that existed in this Matrix right The Matrix says given an M by n integer Matrix if an element is zero we want to set its entire row and column to zeros so I find a zero here I want to set these to zero in its row and in its column I want to set these to zero right but if we have a case like this I want to set this to zero all right and then I want to set these to zero these are already zero I don't have to set them to zero but these numbers I'm gonna have to set them to zero I'm gonna have to set these to zero and these to zero here's my Approach right knowing this I'm essentially iterating through every element in the Matrix and I use some sort of a special placeholder right so in the case of what I did before I used an asterisk because we know that in terms of what these values are actually going to be they're going to be integers right it says it right here these are the constraints are going to be integers so if I use an asterisk it can become easy to identify the asterisks later on and just change those numbers that have been asterisks to zero if that's even a word so you can change those to zero right so the way that I did it is and the way that I do a lot of just standard Matrix problems is I go ahead and get my constraints my role length right so we know that we can calculate the row length by essentially taking just the length of the Matrix you know that the Matrix has uh you know three rows inside of there so we know that is going to be our maximum length we can count the uh the column length as well the central idea is that each row is going to have the same number of columns it's an M by n right so this is going to have three elements is three columns we know this is also going to have three elements three columns and the same thing with the last one right with the last row so we have that information right so what I like to do with these problems is the same thing I did with the spiral Matrix problem is I actually I have pointers that sort of go through and do the dirty work for me this is why I say this is a mostly unique solution because I don't see people doing this very often so I can identify what my top and bottom is what this is going to do for me is if I find a zero I know that iterating from top to bottom I wanna if those are not uh original zeros like this light purple one's an original zero if those are not original zeros you say we have one here from top to bottom I want to set them all equal to my asterisks not to my zero to an asterisk and at the end I'm going to send it uh I'm going to change it to zero so you'll see what I mean in a second here our bottom is going to be the row length same thing with the left to right we're going to look in this Matrix and see okay so we found this zero here we need to start from this side all the way to the end and set those all equals zero as long as they are not um the original zero or an original zero and in this case there's two and the reason why I want to set it to an asterisk first is because if I set this to if I set maybe not this one if I set this to zero right you can imagine a scenario while I'm iterating through the Matrix okay I've seen this okay I set this to zero okay so now the next element that I see is this right here if this is a zero and my functionality is supposed to do some particular action on every zero that it's going to do and repeat that action on this zero as well so I'm going to actually have duplicate or I'm gonna have a incorrect solution because then I see this 0 here and then it's also going to set this entire column to zero that's not what we want remember we only want this to be a zero we don't want this entire column to be a zero this is why it's important to set it to an asterisk because if I set it to an ass Asterix then it's not going to run that particular functionality when it sees this again it's just going to ignore because it's not an original zero this is why I make a distinction between original zeros regular numbers and special characters this is these are the three things that we have to keep in mind okay so we have our left we know our right is going to be the column length okay so this is essentially I mean you can consider this o of one space right because this uh variable right here these are constants and this is also a constant as well it's not like an array it's not going to grow with any particular inputs not a string it's not going to grow with any particular input it's not a hash set it's not a stack not a cue not a linked list nothing just a regular primitive type so I'm going to start at zero so what we're doing here is we're just going to iterate through every single element that exists in The Matrix okay and now we gotta check if the particular Matrix if that element is equal to zero this is where we're gonna have the bulk of our functionality right here so it's important right it's particularly in this case if I see a zero right here again I don't want to override this zero I want to keep it so that any zero that you see is a is it is an original zero this is what I think of in my head I'm like okay these zeros are original zeros and these other zeros are formed from these zeros okay but we need to have these original zeros in order to be able to properly form every other zero correct so I'm going to say we want to skip a particular index now in JavaScript you can't really compare objects like you might be able to in different languages so we know in JavaScript we have primitive types and we have uh essentially objects uh and these are passed by reference and primitive types like uh booleans and numbers and things of that nature are passed by value so what I'm going to do here is I'm going to take this I'm going to join it because I want to be able to compare this with every other row column right if I just had this right here say we had 0 and I tried to see okay well is are we currently at zero I wouldn't be able to do this because what's actually being compared is the memory location I want to compare the actual Index right or the pair of indexes right or indices so I'm going to set top equal to zero I'm going to set bottom equal to row length this is to just reset after everything I can actually have this at the bottom it doesn't really matter okay while top is less than bottom so this is the case when we find a zero while top is less than bottom we're going to change all these to zeros so we know we have our top this is zero and our column is at one so we're gonna do zero one two one right for the row right now the only thing is we have to make sure that this is not equal to our skip index and we have to make sure that this is not an original zero then what we can do with this we can take top and column as our index or indices so we can manipulate each of these so we're manipulating this right here set it equal to an asterisk this we're going to skip it's an original zero we're going to set this equal to an asterisk this is the same sort of functionality we're going to have from left to right okay all we have to do here is increment top then in this case we're going to do the same thing with left to right foreign you can sort of see what's going on we start from left if it's not an original zero set it to an asterisk only in this case we're moving within the constraints of a particular row so we're in row one we're looking at left 0 1 2. okay at this point we should have a matrix if we run it as a particular set of characteristics and hopefully I did not make a mistake somewhere what happens if we return Matrix I just want to see what it looks like when we return I guess we're supposed to do this in place that's correct so nothing really is going to happen oh I forgot to change this we are comparing that particular value that we're at okay so this is perfect every time we see not a number we know that's our asterisks and all we have to do at the end and let's make sure this works with every test case all we have to do at the end is loop again see it works right here these are original zeros works right here looks right here all we have to do is Loop one more time and if we see the asterisks just set it equal to zero there we go let's submit and there's our solution it says eight percent here I promise it was a lot better than that before okay 35 it was just that what was this at maybe it was 60 something 68 I mean I'm not claiming it's the most efficient solution but it definitely should be a lot better than eight percent but uh you can't tell from that eight percent but I think it's a decent solution now there's probably better ways to do it actually I know I can guarantee there are better ways to do it but this was my first idea and it worked out on the first try so I just wanted to show you guys my thought process and that was pretty much it | 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 |
398 | hey guys how's everything going this is Jay sir who is not good at algorithms in this video I'm going to take a look at 3 9 8 a random picking next we're given an array of integers with possible duplicates mm-hmm it is not sorted duplicates mm-hmm it is not sorted duplicates mm-hmm it is not sorted random leap up with the index of a given target number we can assume that the given target number must be exist okay the array size can be very large solution that uses too much extra space will not pass the chart like this uh-huh will not pass the chart like this uh-huh will not pass the chart like this uh-huh we need for every cup pick 3 we need to return either 2 3 or 4 randomly well because the integers are not sorted and they may be disjoint right like 3 there might be 3 4 and then 3 while the naive solution would be keep index map right so cast index map we look through the nouns and if index map has I if it's not there we set it to empty array right yeah and then we push the index in to the map so the map actually will become map of index 1 thanks to something like this so we're a pick first we get in the indices Nexus this is equals this okay add this index map and get target and then being the cost random index you should be something like this right and then we just return this is Brendan I it should be right ah I'm so sorry that's right cool I submit we are accepted but very slow it's maybe because we're using too much space mm-hmm so the risk using too much space mm-hmm so the risk using too much space mm-hmm so the risk is not that bad let's try to analyze our solution with the first this is actually uh this is just a constant here so the problem is becomes here recent map actually for the word we actually will keep the index for all right keep number and yes actually we cost a linear here for space and here we traversed we yeah the time actually for this solution constructor it's a linear time Oh and a big boat for pick it's constant so is there any better solution I'm not sure let's try to look at the discussed yep a bright future yachts shuffle what is this reserve Bois sampling what javascript constant space and single want linear time solution Wow thumbs then huh pic if this length is zero return zero okay say the counts 0 and then we pick something we will look through what is this it says when we are looking through the numbers and we actually max random I'm getting the account get the previous one I can it and while we're looking into it and we get a random index if it's zero we return the root we set the result to 2 to the I see so actually this is an idea that says suppose there are three indexes looping through the first one and the second one and the third one so for each then like for the index of a for the length of one if you pick one or there are two or pick one or three we pick one it should be actually ah yeah yes wow this is clever so I come in here it says for if we're the three index the first one is i1 i2 and i3 right when we meet that I 1 we run this method random if it equals to 1 0 it means if it falls into i1 why right of course it's because it's only 1 so it must be returned one possibility but for I 2 if we're running two we into because now we get two numbers right so now the possibility the previous one actually is released there is the possibility was 1 and the possibility here for each was a 0.5 0.5 possibility here for each was a 0.5 0.5 possibility here for each was a 0.5 0.5 now I've 1 2 3 we run it so first one to anyone so 3 103 mmm-hmm why we will set the mmm-hmm why we will set the mmm-hmm why we will set the result in every time we check because we don't know how many numbers are there right so we check every time if we know the length before and we could just run the last time for the last time but we don't know how many a time I saw it there this is the problem so we will just see we were just to run it and we don't know even though the previous one right we don't know the previous number or the last time previous index or the rest second index or the third index so we just run it again and over and again every time we get the target so how would the possibilities the possibility be distributed here for first index uh-huh you see because for the first index it's actually out of three rounds right the first index we're out so suppose there are n index and I 1 is 1 so actually it 1 times 1 out of 10 and round right and if you are 2 so it's 2 the 0.2 out of 1 out of 2 times how many the 0.2 out of 1 out of 2 times how many the 0.2 out of 1 out of 2 times how many this is another how many this one so gives B and index yeah this would be 2 - wait a minute what's the possibility I'm making enemies right so for three index we will pick three times for the first time must be itself okay we set it to 1 and the second time it is no possibility of half of the chance right and this must be must use be used to we to remove the result here so that the check here is if the math.random is the check here is if the math.random is the check here is if the math.random is the previous one if it is by one we said it I to but this actually means if it is one of the chance of this is the this means and minus 1 right okay so oh yeah so this actually is a n minus a 1 out of n so for I 1 it will be I find out of 1 yeah so it's 1 and then for 2 for two okay so there will be one on up to the chance we said it on I - right - right - right you see so that's what I want is of course - so I won course - so I won course - so I won it's also one out of two when they are three you see it was a one of three we set into our three right for the rest for the three for the but a two out of three chance that we don't touch it will fall on to the previous one which means it's half of a chance all right so it's one eye - wow all right so it's one eye - wow all right so it's one eye - wow this is clever so I got this idea it's at 4 i1 i2 i3 until I end to random pick one number we could actually pick I won for the chance of one out of one pick i to fortunes of one up to pick by three or chance out of one up three pick by n for a chance of one these channels for a nice right so that previous one is the we will have the chance of an N minus one out of n as we add an S here right it was picked before yeah wow this is clever learning something cool this is very cool I'd like to clip up upload is there any theory for this one so if we think another way is that suppose there is n minus 1 I will already pick the number we already set 1 now we have an N minus a new number so what we care is that - is that when we what we care is that - is that when we what we care is that - is that when we only care is that if I n is not in a final result it's already picked randomly right if you want to add int n it must be in my 1 out of n chance so we only care for that chance to update the result i n for the other ones it will be already done in a previous loops Wow collabora and is yes of course the time and space complicit I'm would be the construction will be very nothing but the pic will actually for worst case will be in linear time for time right or for space its cost constant I think wow this is very cool for our solution actually we're using both linear time and space yeah ok so that's all for these problem see you next time bye | Random Pick Index | random-pick-index | Given an integer array `nums` with possible **duplicates**, randomly output the index of a given `target` number. You can assume that the given target number must exist in the array.
Implement the `Solution` class:
* `Solution(int[] nums)` Initializes the object with the array `nums`.
* `int pick(int target)` Picks a random index `i` from `nums` where `nums[i] == target`. If there are multiple valid i's, then each index should have an equal probability of returning.
**Example 1:**
**Input**
\[ "Solution ", "pick ", "pick ", "pick "\]
\[\[\[1, 2, 3, 3, 3\]\], \[3\], \[1\], \[3\]\]
**Output**
\[null, 4, 0, 2\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3, 3, 3\]);
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(1); // It should return 0. Since in the array only nums\[0\] is equal to 1.
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-231 <= nums[i] <= 231 - 1`
* `target` is an integer from `nums`.
* At most `104` calls will be made to `pick`. | null | Hash Table,Math,Reservoir Sampling,Randomized | Medium | 382,894,912 |
201 | all right let's talk about today's laconian challenge question so it's a it was end of number range or bitwise end of range of numbers we have a wrench end to end it's positive and so it's a bit large we've got the end that's a slightly larger than and we need to return the bitwise and of all the numbers in this range inclusive so just pretty much it would just be so if we just translate what the question is asking into code it will be something like this but I guess it will be you will be the correct all set but it will be slow because we doing an operation a mom how many numbers we have in this range so I think it will be you will probably exceed the run time limit we are looking at something that's a smarter that probably only looking at the two boundaries to figure out things so let's take a look at that so M is equal to 5 which will be a 4 and a 1 so it's 1 and a 7 so it's a 2 a 4 and one add together this one we have a sandwich the number in between which is 6 is 1 0 and if we do bitwise and for all the numbers it's basically checking for the bit that every number has a 1 in there so it's at this bit here we return 1 0 which is 4 so it appears that we can basically just shifting these two numbers towards right for the same amount until the two numbers become equal that bit should be the bit to that we have all those numbers in the meeting all those numbers or should have that bit to be one so if we ship the fight was right by two positions shipped everything here what's right we get out one that's the one and that's a one if we just shifted by one it's not equal let me actually do this in stay just look at a one zero this is a one line and this is one yes so this is what I'm talking about if I shifted the numbers towards right by the same amount and what we carry is actually the M and hang whether they are the same or not when they are the same it's pretty much we can guarantee that everything in between should have that bit at least that bit to be the same so we need to show something else before we can actually perceive as this procedure in the code is that would there be case that when the N has one extra at least one extra one towards the left and there could that be some kind of violation there let's say that M is 0 1 0 and n is 1 0 something like that so if we shifted to semi bond and just only checking for that particular bit the first a bit that this to become the same what this cost problems what we have in between this is 2 this is six so we have a couple of number in between three four five so for three it should be 0 1 4 is 1 0 5 is 1 0 1 okay so we don't need to worry about I think that the approaches should work once we moved we shifted the to number the two boundaries towards the right for the same amount and we see that the other cell should guarantee I was previously worried about if we have this one location and this one location here yeah so we should check for the whole number after shifting it's not the only that digit if we check for the whole number you should work in this case by one it's 0 1 and this is 1 so they're not the same they are not the same meaning that it's guaranteed that they are in order for this to become 1 it has to be 1 0 first so even though that after the same amount of shifted they the first the rightmost appeared to become the same for this two boundaries as long as these two numbers are not equal there has to be some numbers in between however 0 in that column in that bit so we need a shift of the two numbers for the same amount until they eventually become equal either it's all one or zero and if it's all one we just shift it back by two by the amount to get the limo we wanted for this case two and six the we need to shift for this one more time two more time actually more time together them to be equal and when they are equal they are all 0 so it's 3 times shifted to cause them to become equal and we shifted the 0 back by 3 times we get the 0 and it's indeed that there is no column among this range 2 & there is no column among this range 2 & there is no column among this range 2 & 6 so that's a 1 across the board so there's 0 make sense alright so yeah so this will be just a shifting bit shifting question and the Cystic that we are working with silly two bit integers the running time is order of silly - so the running time is order of silly - so the running time is order of silly - so it's a it's very much constant so we're going to keep track of how many times we do the shift while just two numbers are not equal we need to shift it imposed to us right in the end we just require the M the lower number the ship shifted back by the same amount so this should work let's see okay so that's a quick question today | Bitwise AND of Numbers Range | bitwise-and-of-numbers-range | Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1` | null | Bit Manipulation | Medium | null |
1,222 | hey what's up guys Nick white here I detect encoding stuff on twitch and YouTube check the description for all my information just explaining the code that goes into these algorithms data structures problem for people that don't understand them or just explaining the problems in general please like and subscribe to the channel gross thank you very much this is 12 22 newer problem on lis code Queens that can attack the King like in chess hopefully you guys have played chess before this is a medium problem on an 8x8 chess board there can be multiple black queens and one white King so multiple Queens that can attack a king right the one board has a bunch of Queens and the one just as a king left is what we're dealing with here giving it given an array of integer coordinates for the Queens so we're giving the coordinates of every Queen that is left on the board that represent the positions of black Queens and then we have also the coordinates of the King so this is the coordinates of all the Queens so it's gonna be like a giant array a 2d array where each sub array is a pair of coordinates for one particular Queen right so this is a queen we get the coordinates for every Queen right so zero one would look like this one zero would look like this and then the rest of the Queens right and then we also the King is just a one-one array and just King is just a one-one array and just King is just a one-one array and just you know x and y values for where the king is right so we know where the king is and we know where all the queens are on the chessboard so what we're trying to figure out is we want to return a list of the list of integer we just want to return a list of the coordinates of the Queens that can attack the King right so these three can attack the King if you know anything about chess the Queen can attack in any direction and it can go as far as it can on the chessboard right so this Queen can go diagonally this one can go up this one can go left the only thing is the Queen can just go through another Queen to attack the King right this can't and this isn't a perfect die like this can't just go you can't just do that it has to either be diagonal up right left down any of eight directions you can go in I can go one of those directions to you know stretch as far as the board to attack the king okay so how do we do this my intuition for this problem was some kind of like DFS thing the seams number of islands like where you start at this certain point where the king is and you expand in all possible directions right so you start here and then you start expanding in those directions that the Queen can attack from and look for the Queen's coordinates and then put those onto the list and that's similar to what we're gonna do here but the thing here is we have to handle this case the only special case where the Queen can't attack through other Queens right so how are we gonna do that we have to break basically while we're looking for the Queen's we basically have to break once we find a queen when we're expanding in these directions right so to do that we're actually gonna see we're gonna make a scene or ret we're gonna make a scene or a basically a clone of the board and we're just gonna loop through all the Queen's coordinates and put in the scene array where we've seen a queen right so let's just do that really quick first thing we could actually do is just initialize our output that's always what you should do in a question if you have an output type just set it up right just get it done that's an easy move forward and a problem so just make it I always call it result pretty much it's an ArrayList there we go boom we got our result set up so at the end you know return results right of course now first thing we're gonna do is like I said make this scene arise so the scene array is going to be a boolean array and it's going to be of size eight by eight because that's the size of the chess board and this is gonna be all the coordinates of the scenes of the Queen's not the scenes that you know are on the board so there we go it's an eight by eight array same size of the chess board you can just loop through the Queens using this shorthand int array or interact queen in Queens so Queen and Queens bad time typing right now then you can just do scene of queen of zero this is the x coordinates of the Queen current Queen that we're looping through sort of living there each Queens coordinates right so I've seen this Queen and then we put the x coordinate and then the y coordinate this is basically the board this is the 8x8 board and then we're just using boolean to say which position which index indices were are gonna they're gonna be true if we see a queen there right okay and this gonna come in handy later so there we go we get the x and y values of the queen so we set it to true okay great so what do we do now basically we're gonna have a directions array so we're gonna just say okay directions is equal to negative 1 0 & 1 directions is equal to negative 1 0 & 1 directions is equal to negative 1 0 & 1 and this is because in any certain direction if you're going forward if you're going diagonal you can either go forward or backwards if you're gonna up-down left-right diagonal you know up-down left-right diagonal you know up-down left-right diagonal you know whatever you can only go forward or backwards so one is going you know forward in the direction what negative ones go backwards zero is just going you know you're not moving anywhere right so we can loop through all we can increment basically our x and y's you know if you're if your king is here right you're gonna want to increment your x and y's in all directions right so we're gonna do all possible directions so we just loop through you know into DX in directions four-inch dy in directions four-inch dy in directions four-inch dy in directions then what this is do is doing is its looping through um you know negative 1 0 1 for all the X values so it's could either stay in the same X position you can go negative 1 or it can go negative 1 or could go positive 1 but it's also moving through all the positive the y direction so you go you know negative 1 and Y it could get a positive 1 or it can just stay in the same spot and then we'll also do them simultaneously so it covers the diagonals right it can go you know negative 1x and negative 1y or if you go negative 1 x + 1 Y so go up if you go negative 1 x + 1 Y so go up if you go negative 1 x + 1 Y so go up and to the left or you go 1 X and you know this double for loop will cover all possible directions diagonal left-right diagonal left-right diagonal left-right up-down and that's what we're gonna do up-down and that's what we're gonna do up-down and that's what we're gonna do and basically within here we're gonna get the dimension the well first of all if it's if they're both equal to 0 we're not going to do anything so we'll just continue through the loop so if GX is equal to 0 and D Y is equal to 0 then we will just continue otherwise we'll get the position of the king so we'll say king is x value is equal to king of 0 and then king of Y value is equal that with the Y value of the King is equal to king of 1 right so that's just how it is we have the x and y the king right that's what we get is the input so 3 it's gonna be a 3 so we just give those x and y values right and now we want to take those x and y values that's where we start our expansion from and start going in all of these Direction combinations we were just talking about looking for the Queen and to do that we're just gonna have a while loop where we expand our boundaries based on so it's doing all these possible combinations like I said in those four loops so now we're gonna do okay if x + loops so now we're gonna do okay if x + loops so now we're gonna do okay if x + DX is less than or greater than or equal to 0 because that's the boundary of the indices right the first index you can go on is 0 and X plus DX is less than 8 because 7 is the farthest you can go so these are this boundary checks and y plus dy it is greater than or equals 0 and y plus dy is less than 8 then in this case we cheese do is y plus dy is less than 8 in this case we can start expanding in that in those directions because we're not going to go out of bounds so boundary checks so you just do expo you know this is what we check 4x plus equals DX y plus equals dy and then down here we'll check the seen array for these coordinates because you're expanding you're changing the X and Y's to find those you're looking in every direction to find if there's a queen around and if we do find the Queen in those coordinates because we know where the Queen's are in our seen array that's why we filled it up so if seen X of Y is true then down here what we'll do is we will do results dot add a raised dot as list of X&Y basically what raised dot as list of X&Y basically what raised dot as list of X&Y basically what this does is it adds the coordinates of the queen that we found to our result because that's what we're looking for because it can attack right because it's in one of those directions one of those eight valid directions that we're expanding to we found a queen and now so that we don't find these extra Queens in the same direction we will now break out of this loop and it will stop continuing in the same direction so this is only going in one certain direction once we break it'll not it won't go in that direction anymore so we will not continue searching in that direction so we add the first queen we find in the direction and then we break so that we don't keep going in that it handles that one weird case where there's already Queens in the way so that's pretty much it and then you can just return your result that's pretty much it for this problem it's a pretty elegant solution hopefully I explained it well my main problem with these solutions right now is my typing speed this keyboard I need to get a new keyboard but yeah that's basically it I mean what do you put it's just expanding a direction you're looking for the Queen's we're putting the coordinates in this scene array tells us where they are so it's just useful to clone it so we know the array coordinates of the Queen's so that this is like a nice little elegant loop through all directions like I said you know negative 1 it goes through this twice you know it does all the combinations of these three things and yeah I mean that's pretty much it I mean I don't know what else to say you know hopefully understand let me know if you guys have any questions it's pretty straightforward let me know if you have any other solutions down here but I really like the solution I tried to do it in a little bit different way than looping through these directions like this but I think this is the best way and I like this little scenery so thank you guys for watching let me know if you have any questions please like and subscribe alright I'll see you in the next video alright peace | Queens That Can Attack the King | remove-covered-intervals | On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king.
You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing, yKing]` represents the position of the white king.
Return _the coordinates of the black queens that can directly attack the king_. You may return the answer in **any order**.
**Example 1:**
**Input:** queens = \[\[0,1\],\[1,0\],\[4,0\],\[0,4\],\[3,3\],\[2,4\]\], king = \[0,0\]
**Output:** \[\[0,1\],\[1,0\],\[3,3\]\]
**Explanation:** The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).
**Example 2:**
**Input:** queens = \[\[0,0\],\[1,1\],\[2,2\],\[3,4\],\[3,5\],\[4,4\],\[4,5\]\], king = \[3,3\]
**Output:** \[\[2,2\],\[3,4\],\[4,4\]\]
**Explanation:** The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).
**Constraints:**
* `1 <= queens.length < 64`
* `queens[i].length == king.length == 2`
* `0 <= xQueeni, yQueeni, xKing, yKing < 8`
* All the given positions are **unique**. | How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval. | Array,Sorting | Medium | null |
416 | Hey everyone Spencer, I hope people are well, today I will solve the problem Partition Equals Upset, everything is fine, this question must be scary to see, on top of that you are thinking, DP question is, I don't know how it will happen, I will please tell you very lovingly that you Till now, whenever you watch my videos, I always tell you, please watch this playlist from the beginning. If I am telling you the truth, you will be asking this question yourself, it may not be so, if I tell you now, then it will help. It will be done later, see, most of the concepts were from Zero One Up, which we have solved. It is most important to ask this question that I did not see its pistol in the lecture and if you have directly come to the question, then please do not come to this stage because you have understood the concept. You will not be able to solve such questions and start reading directly or start solving them. If you do not know the concept of DP then I am telling you the truth, you will not be able to solve it and will become frustrated and separated and by doing all this we made you fear DP. I go after that's why my playlist is relief, it always has all the relief in it, how to burn your confidence from the beginning so that you start asking questions, okay and I am telling the truth, this question is like this, before that I would recommend that The link to the question of this question is given in the description box. Please open it and attempt it once. What is the input given in it and what is the output given in it? Brother has also impressed us as much as we can by rating it. Can you find a solution sir, this thing will help you a lot, I am telling you the truth, it will help you a lot in enhancing the concept of DP, now I will talk about this lecture, the lecture is going to be very short because I read its basic thing sir. Now I have to show you the game of how people play in DP, how each question which is a template, which is zero, which has become a template on its own, how many questions can be solved on the continuation of the question, okay. I hope you must have seen the last lecture. I hope you have been in the playlist since the beginning. You will get a lot of friends in the trust. Now those who were there since the beginning felt like recension. In this way, those who are starting They will be made of DC, they will get DC online. Do you understand carefully what is the partition problem? I will tell you this 01, its proposal is just like the problem. Partition Equals. What does the problem say that you have a set of integers. I have to tell you that basically you have to divide this set of India into two partitions p1 and p2 and divide it in such a way that what is in both the partitions is equal, it is okay like if I divide it into one five and If there is 11 in this then how much is the sum of 11 and how much is the sum of this 11 then was it possible that in this life integers come you have equal subset equal all basically equal in all now divide and make two such subsets then yes true possible ok If I talk about this, p1 and p2 are fine, then is it possible? No, if you take any partition like you are three and you are here and five is here, then still we will have one back, five is here. But one will go back. Okay, so here it will burn. We basically have to find out whether it is possible to do partition in two equal subs or not. Before that, I understand a small concept and understanding this concept is very important. Hey, let's suppose input. It is given 15 11 5 ok again I have told that this will be solved like 01 up ok next one there is something or the other brother understand what basically you have to do with this is that you have to divide it into two parts p1 And p2 is fine and its sum, this sum and this sum both should be equal. Basically, whatever is the sum of integers in p1 and whatever is the sum of integers in p2, both should be equal. This is given in the question, then what can happen? That is, t1 + p2 = should be equal to even. Okay t1 + p2 = should be equal to even. Okay t1 + p2 = should be equal to even. Okay and if both are equal then tu p one it should be equal to tu even and the first partition should be equal to sum by tu. I understand what I am doing. I mean, the sum of one partition should be 2. But off friend, we are dividing equally and we also keep this constant that none of the integers should be dropped, that is, I should make two partitions in such a way that the sum of both is equal. Equal A which is done by doing all the interiors also. Okay no interiors child and let's suppose sub is equal to both of them and both are equal okay if we are doing one more divide then the p1 which will be the first partition what will be its value sum value What will be the interior supposition in it? If this is p1 then whatever integers it contains will be the sum, okay what will it be equal to, that means you understand one thing here, if let us sum up all the integers, whatever interiors we have, keep it okay. From i = 0 till i = n - 1, we have i = 0 till i = n - 1, we have i = 0 till i = n - 1, we have total sum. It should be even and only then we can divide into two parts equal partition. If this sum is odd then let us suppose that all this is 11th. Okay then you are 11. How if you divide two equal participants, then p1 and p2, how can you not do 5.5 and 5.5, p2, how can you not do 5.5 and 5.5, p2, how can you not do 5.5 and 5.5, or here there will be six, or here there will be five, only then it is possible which is not equal, okay, so this is what it means, so I will tell you this. Let me tell you, if the sum we have is A of all the integers, if and only then it is possible that we can divide p1 and p2 by one, if this thing comes odd then you can do anything, how to make partition, you can do it anytime. You cannot divide equally. You can see the example. Lately, take your example. How much did you take? If you take 15, then how will you divide 15 into two equally? Tell me, or else you will have to do exercise 7 and do it on one side. Okay, only then it is possible, that is. There will always be less in one place or the other, you can never divide, so we will first take out our check here that if the value of the sum is odd then it is okay then we will return it Jal Ki Bhaiya, divide it into equal partitions. It is not possible to do so. Let us assume the value of the sum. The value of the sum is and then we will check whether such a partition is being formed. There is such a subset being formed whose value is equal to A. Let us assume that we have got a set of integers whose value is Subai tu a jaaye toh but second which will go back the remaining integers, let me explain its value automatically let us suppose what is the example we have 15 11 5 this is what we have set off wait ok we have it saying to find the sum here what is its sum. Its time here is 11 22 ok if I halve it then how much will be the submit 11 So can we find such a set of integers whose sum is 11 A then yes how in this one five and five if we pick this So how much is the sum of 11, then what is the remainder, but its sum will not be there, so in the remainder, here only 11 is understood, we have taken out such a set of intersections whose sum is half of the total, okay? So but these are the number of remaining integers children, what will be its sum, it will be half of the total, but off is because we know what is even, what is and what we have to do is divide it into two partitions and we have taken this mother. What will be the value of the first partition, Subbaitu, if it is possible, will the second one ever be possible, what will be its value, it must be clear by now, if I explain you the conclusion here, then IF is equal to and then it is okay, let it be not possible, you divide. In these you will return equal subsets, if the value of sum is and i is like this then how will we divide p1 and p2. This set of integers p2 is a set of integers then what will be the value of p1. If you are ok then you need one thing. Now it is understood that the question has been reduced to what? The question has been transferred to whether it is possible to find a subset whose sum is the sum of the total. If we find a subset whose sub Total ka sabe tu a raha hai to but obviously the second one which went back with the remaining integer will also have its sum. We did it. We found out that yes brother, such a subset would be possible that we can divide into two equal partitions. So you understand that what was the previous question? The previous question was that you have been given the set of interior, you have given the sum and you have to find that it is possible to make such a subset whose sum is 11, okay this There is nothing in the question, friend, things have been done with you, things have been written in this question, you have just been given a set of integers, you have found out the sum by yourself, what is the total, you are right, it is possible, it is such a subset. It is possible to find out whose sum, what is the total? Yes, it is possible, but off your sir, the remaining subset child, its sum will also be the total by you, so if we divide it into two equal partitions, then we will return true, so the question is basically this. You just had to find out the value of the pay sum here yourself, this was the trick here and there was no trick at all, I hope you must have understood this thing, there was nothing rocket science in the question, just give you the ready sum here. And you found out the sum here, how did you do it with the help of the question? What is the point of the question? The question was asked again and if nothing was done then the question got reduced and we found out everything by ourselves. How did you calculate the total brother, if I do it with you tomorrow, you will literally enjoy it a lot, just stay with me in the code, okay, what did I do here, find it, nas dot size, namas dot size, what else did I do again, find here. Did you find one and equal sum? Now basically we have to check that whatever integer we have given, if its time is odd then but now it is not possible to partition both of them like this, but auto x sum is fine and What did I do here, let's make it a little bigger in size. What did I do here, sum plus equal Then I will tell you the solution of DP. Now look, now we have to find such a subset whose sum is what is the total. What did I do here? Sum = Sanvere, you did it. Okay, now we have the actual sum, which we will play by taking it here. Record only the code here which I had last run just copy it here return date seat subset sub name one we are creating crop from the record in it we will pass n passed and sampar ki sam kya aayega sam bai tu Here I have done some problem, now let's define this function A function and it will be easy, for us this is the vector of vein, okay and we have passed and the base condition of the pass will be from everything, we copy it completely. So it is said that the complete copy has been done from the base condition, there will be no problem till this point, there will be no problem, the editor will remain even, your name will be added here also, Namas will be added here also, the total will be added y2. We just checked a little bit here a little bit first, one more condition, if even. Key value and IIT will be returned, let's run it and accept it. If we submit it, then someone will come on some test and find DLP, which one we have to convert, on which DP code and how will we do it in the best way? Now I change the code here in the coming questions. Okay, what has to be done for code change, nothing. Let us create a vector which we had created in the last lecture. So we will copy this vector. Now see, in this question we just had to find the value of the sum, what will be the value of the sum, made the total vector, copied and pasted it here, passed the DP here, passed the reference here, okay and by removing this check will be done, okay, you will not check here. One more check will be removed and it will look like basically here is this and you have to pass the value of DP in all. Successfully submit. I always say that there is no rocket science in such questions, you just have to understand the question well. What is there in the question and I am telling you the truth, look at the playlist from the beginning, you too could not even imagine how much terrible looking code you can do by yourself and I did it in front of you and explained it to you. Your question is done, your task again will remain the same, give this code top code and show it after processing, okay again, after some fear, that is, after two-three seconds, that is, after two-three seconds, that is, after two-three seconds, you will see its top solution on the screen and I hope that you will solve it. For your confidence, Aldo, this is the best of the day, first we have to write the code in the recess, then after that we ice it, this is the best approach for us, we can never call the court in this, we do not have to remember, okay, we are the best. You have to write the conditions yourself, along with this, why did not you write everything in the best condition, because this problem has its own problem, I had explained it to you easily, that is why I did not do anything like this in this condition, this problem, because there was a similar problem, please. Let me know by commenting, no matter how it feels like a lecture, thanks and see you friends | Partition Equal Subset Sum | partition-equal-subset-sum | Given an integer array `nums`, return `true` _if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[1,5,11,5\]
**Output:** true
**Explanation:** The array can be partitioned as \[1, 5, 5\] and \[11\].
**Example 2:**
**Input:** nums = \[1,2,3,5\]
**Output:** false
**Explanation:** The array cannot be partitioned into equal sum subsets.
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 100` | null | Array,Dynamic Programming | Medium | 698,2108,2135,2162 |
979 | so today my problem is distribute points in a binary tree uh each turn of that binary tree will have a certain number associated with this and that number denotes how much coin that particular node has so my job is to return the number of moves that is required to make every node have exactly one coin and it is given that if you want to move one coin it will take exactly one move so if we take a look at the example one uh one move will be required to move that coin from the root node three to its left child and another move will be required to move that uh a coin from its root node to a side sub right side so that everyone has exactly one coin so the answer will be two here so uh how will we actually upload this question is firstly i will try to solve the very sub problem of this uh we'll solve and i will solve this problem on the node that has the minimum dependency and that will be the leaf node because it does not have any sort of issue of style so first let's uh see how we'll solve it on its left and after that we'll move on to the parent itself so for better understanding let's take a look at this example one this is the same example one okay so if i want to talk about this node i'm just talking about this node right now okay so there are only three possibilities here either the number of coins that it may have is equal to one either it is greater than one or either this or either it is less than one so if it has if it is if it has already if it already has exactly one coin then how many number of moves do we require we don't uh we only require zero number of moves because since it's a leaf node and it already has one coin we don't need to do anything further right so if it has exactly one coin with the number of moves that required is zero what if it has less number of coins than one then it can only have zero number coins it's not possible for it to have negative number of coins so if it has zero number of coins how many moves do you think it will require so that it gets one coin it will only require one coin right it will always require one coin so that it can get one coin from its parent that will exactly uh you know calculate uh counter as one move so that is the answer if it has uh less value than one now what if it has you know more value than one so let's uh if i take the example of this image you know if i take example of this image here it has more than one point so how many steps do you think it will take me so that this leaf node has exactly one coin so the answer is it will take two moves because it has two additional coins right so it will take me exactly two more so that it only has one coin so if we just you know if we try to formulate a for uh try to you know form a formula we will find that uh there's a certain pattern and i'm just talking about a leaf node here so the number of steps that a leaf node will require so that it gets exactly one coin will always be equal to the mod of sorry n minus one uh where n is the number of coins that it has so let's take a look let's try to for fit this formula so here it has zero points right so zero minus one give me minus one if i take a mod it will give me a value of one which means that uh i need one move so that it gets one coin and yeah that is exactly correct so if i put the formula in this image it has three coins three minus one will give me two and i only require two moves so that you know this particular node has exactly one point so yeah that is the you know that is the formula that we will use for a leaf node so we are done with the leaf node part now how are we going to solve the parent node so solving the period is pretty simple because you know once we are done with the leaf node we have already solved half of the question so the number of steps that a parent will require will depend on the number of uh the number of steps that it's uh left in the slide shall require so how many uh you know how many uh steps does this left child will require it will require two steps right so that it gets one coin now what about this child it will require exactly one coin uh it will require exactly one step so that it can get one step uh it will get uh and can uh sorry so that it can get exactly one point so if i just add both of them two plus one i'll get an answer of three and that will that shows me how many number of moves i require so that everyone get exactly one coin now uh let's see suppose uh it has three coins right so it will take me two moves so that this particular note can get two points okay so right now i have two as my answer after that i'll add one because you know uh this parent node will need to give one coin here so after that i'll add one and i'll get my answer as three so that is how we are going to solve the answer for the parent node itself now uh let's take a look at for this example also how many coins does uh sorry how many coins this uh this has it has two so how many steps is this uh this particular note required only one step what about this note it has also it also requires one step so that it can get bitcoin or it can get one coin so the total answer will be one plus one that will be two and we only need two moves so that everyone can get one coin so yes one coin will move from here to here and then one call will move from here to here so that will only require two number of moves now as for the best example let's try to understand this okay so here we have uh three coins in the sorry we have here we have three coins in the leaf node so how many steps do you think uh will require only two steps so that this particular node gets two coin right i'll just move uh push off all the overlord overall coins that i have so this will require you know it will get two points and i'll move two steps done now what about this coin i'll what about uh now what about this i need exactly one move so that i can you know push off one coin to here so after that it will get one coin and i'll get one more wall but one extra move and after that this will you know this will uh push off the one coin to this part and i'll get one extra move so the answer that i'll get will uh that i will get is four so my answer for this question will be four and that is also correct uh we only need four number of steps okay so uh if you have already noticed this then you can see that the number of steps that a parent will require will always be you know sum of how many steps its left child and its right child will require and the number of you know the number of value that the parent will return will always be equal to uh you know the sum of the left steps plus the right steps plus how much value it has on its own minus one so here it's uh it's right child will uh will give him two steps right here i'm just telling you how are we going to calculate how many how much value this particular node will return so it's right child will return it's a value of two okay so two plus how many coins it has on its own so he has zero coins okay and minus one why because you know he needs to have one coin for himself so he will return exactly one coin uh he will sorry he will return exactly one coin so it will take exactly one number of move so that is the formula that we'll be using i'll just now show you the code for this sorry okay so uh firstly i need to have a variable that will store my answer that will be self dot answer after that since i am doing sort of a dfs since i firstly need to reach the leaf node so from there i can you know i can start solving my solution so count steps here i'll pass a parameter that will be root and for the first thing that i need to check is if my root is empty or not so if my root is empty then i simply return 0 because it means that i have reached uh didn't so from here i'll return zero otherwise what i'll do is i'll sorry base my cursor okay otherwise i need to you know calculate the left steps the amount of steps that it's left child require and the right steps so for that i'll do a recursive call count and root dot left done right steps will be count steps dot right okay and uh my answer will be equal to uh so how many steps uh a particular node sorry how many you know uh a parent node will have that simple the left steps plus the right steps since the answer will depend on how many steps its left and its right child require as for the leaf node there is no need because you know it does not have any left or right side and the number of value it returns how many number of you know coins it will return i'm just returning how many number of coin it returns so the formula is pretty simple the number of coin that particular node has plus left steps plus right sorry right steps minus one so if you want you can just take a look at this uh as from the perspective of both of a parent node and leaf node so if you take up this from the perspective of a leaf node the left and the right side will be zero because they don't have any left child or right check and the number of coin that it requires is uh root minus one i'm not taking mod here i'm taking mod uh when i'm calculating the value there okay so now if you just look at the perspective from the root note as we you know as we took it in this example the number of you know the number of coins that it will return is how many number of coins it's a uh sorry how many number of coins it has assimilated on its own so that will depend on how many coins it's left inside right child has given so here his right child has given him exactly two points plus how many number of coins he has on its own that will be zero right and minus one since he needs one coin for himself so he will return exactly one coin and yeah that is correct so that is the formula that we have used in here okay so firstly this will be self answer plus equals to yeah okay so yes we are done with this just i need to call this function count steps i'll pass through return sorry self dot answer okay now let's run this code okay yeah so it works now it's submitted yeah so it works perfectly and uh this was my solution for what for this problem the distribution of coins in a binary tree and thank you | Distribute Coins in Binary Tree | di-string-match | You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.
Return _the **minimum** number of moves required to make every node have **exactly** one coin_.
**Example 1:**
**Input:** root = \[3,0,0\]
**Output:** 2
**Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child.
**Example 2:**
**Input:** root = \[0,3,0\]
**Output:** 3
**Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child.
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= n <= 100`
* `0 <= Node.val <= n`
* The sum of all `Node.val` is `n`. | null | Array,Math,Two Pointers,String,Greedy | Easy | null |
275 | Had happened Agri Badi Today's Question Advanced 221 Adhere To The Preview Ifre Have Exactly S Number Date Hai Vellu Christian And Equal To The Element Lu Ko A Super Example Another College Student Will Have Two Digits Number which number is 1251 element in total number to two hua tha som water will have no desire his life in the number dial us greater noida to the number date - total number of Total Number of number date - total number of Total Number of number date - total number of Total Number of Cases Will C - 2 - 121 Hai To Hai Lath Lekar Look Ahead In Binary Search Because Banner Research The Best Optimal Back To Find Any Valid Snow White And Valuable Total Health With This Difficult Position Such Road Anar Width Regulation And Finally Will Return and a plus b | H-Index II | h-index-ii | Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper and `citations` is sorted in **ascending order**, return _the researcher's h-index_.
According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): The h-index is defined as the maximum value of `h` such that the given researcher has published at least `h` papers that have each been cited at least `h` times.
You must write an algorithm that runs in logarithmic time.
**Example 1:**
**Input:** citations = \[0,1,3,5,6\]
**Output:** 3
**Explanation:** \[0,1,3,5,6\] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.
**Example 2:**
**Input:** citations = \[1,2,100\]
**Output:** 2
**Constraints:**
* `n == citations.length`
* `1 <= n <= 105`
* `0 <= citations[i] <= 1000`
* `citations` is sorted in **ascending order**. | Expected runtime complexity is in O(log n) and the input is sorted. | Array,Binary Search | Medium | 274 |
374 | so hey everyone today i am going to discuss the second question of the easy category under this dsa bootcamp so here the uh the question is guess number higher or lower the question says that we are playing a guess game the game is as follows i pick a number from one to end you have to guess which number i picked so it's very clear that i have to apply binary search from 1 to n so let's write 1 2 3 in let's take an example it is given here n equals to 10 right n equals to 10 and he has picked number six right so one two 3 4 5 6 7 8 9 and 10 so here my starting variable will be from 1 and ending will be 10 right then they say that every time you guess wrong i will tell you whether i have picked is the number is higher or lower than your guess so they have done like they have given a function which is present on their system only means uh i don't have to write this function here they have written predi predefined that function and i will pass uh the number which i will like to choose from start to end like at first from the middle and i will pass that number from the to the guess function and it will return us minus 1 or 0 and after that we will apply the condition of the binary search like if it comes minus 1 then the peak number will be less than num means the middle element and if it is 1 then the picked number will be greater than the middle element and if it is 0 that is the number that which they have picked so i will return that number right so let's suppose uh they have given six and my mid element is five and if i uh write this guess function then uh i it will return me five ah they have picked six right i have given five so five is less than six so this condition uh this condition peaked element is greater than num means six is greater than five so it will return us one that means that the peaked element is greater than my middle element so my start will be pointing over here start will be ah pointing to mid plus one if my condition gives one right if my condition guess then the middle element if i give then it if it comes one then my starting pointer will move to mid plus one else if it is less that means it will give minus one ah as it is written in the question that it will ah return minus 1 the predefined function uh if the peak number is less than num means the number which i will give if it returns minus 1 then i will nothing i will do end pointer to i will move my end pointer to mid minus 1 yeah then it will be good to go so let's start let's give our start equals to one and end is again and we will start our binary search right so at first i have to take the middle element and i will write start plus in minus start so i doesn't get the overflow condition of the integer and then i will uh put my condition then i will at first let's create our answer variable where i will take my guess function they have given a predefined guess g e double s and uh yeah i will probably i will uh give mid as my argument and uh it will return answer will be either minus 1 or 0 right so i will give my condition that if my answer becomes zero then i will return my middle element right if the answer becomes zero then the middle element will be equal to equals to their peaked element so i have to return the peaked element right if the answer becomes minus 1 then what i have to do i have to move my end pointer to mid minus one if answer becomes minus one that means the middle element which i have given is greater than the peak element so if the middle element is let's suppose here is the middle element and the picked element is 6 if the middle element is greater than 6 i will definitely move my end pointer to here to check our ah this range 1 to 6 so here it will be like it is and else means answer will be one if answer equals to one then i will move my start pointer to mid plus one right so it will be okay and if it doesn't uh found the number then it will return minus one right this is the code and yeah it will run fine let's run it yep it's accepting and it is also submitted right so this is the code if you have any problem then comment down below | 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,481 | hey everybody this is Larry this is day 16 of the Leo day challenge hit the like button hit the Subscribe Buton join me on Discord let me know what you uh what you think about this cont oh this man I am uh I mean you know I've said this like about a few thousand times now or at least a thousand times I guess CU my streak is a thousand days and I still don't know what I'm saying you know uh which tells you sometimes practice makes perfect but sometimes practice makes you a little bit dumb uh anyway uh no the reason why is because today I wanted to talk a little bit about um uh there are a couple things I man I feel like these uh videos have kind of been little over the place I mean they're still wearing the lead code and programming and stuff like that so let me know in the comments you know whether you find it interesting um this is very topical of course it is February 15 on um 2024 I don't remember the year but uh anyway so yeah there's a lot of debate now on my Discord um definitely come check that out about just um about all these things where basically the idea here is on leite code contest um they've been adding this thing I mean I guess it's been a couple of years now but they recently they've been kind of upping it a lot where um there's this idea of system testing which is basically after you get you submit your problem or you submit your solution for a problem for the contest and then it kind of um and if you haven't been fing up and The Saga I've been kind of talking about it in the beginning of a couple of these videos so if you're joining in here new my apologies you can skip a little bit ahead to my fault but yeah um there's this fail System test um that kind of comes up like a few days afterwards and it's because I don't know uh and I don't know my personal opinion is that it's kind of just lazy it's a little bit um I mean look once in a while it's going to happen you know people make mistakes PR Setters are human and you know um you could lower the probability of a mistake but mistakes will happen right um of course but the um and as a senior engineer as a staff engineer um this is something that comes up as a in a team as well right like um when if someone Junior on your team is able to take down the service or system or create a level five or Level One Outage depending on I don't know some companies have level one is the highest some PE some companies have level five I don't know what the highest priority right when that happens uh it is not the Junior's fault it is probably the senior fault and the staff Engineers fault uh or at least the team lead's fault for having a system in a way such that could happen of course sometimes that just happens because um the team lead acknowledges that there are tradeoffs between different um it's just a trade-off different um it's just a trade-off different um it's just a trade-off between uh this idea of like you know robustness and security and all these things security is maybe not good but I just mean like um reliability um you know you take a trade-off in those know you take a trade-off in those know you take a trade-off in those things knowing that you know for trade-offs and others right for example trade-offs and others right for example trade-offs and others right for example um just getting your product out maybe like you know you're trying to get it out by Christmas so that like certain things can happen by Christmas or something like this right um or like getting things out by super bow so that you can have a super bow ad or something I don't know right and of course in those cases it's a very deliberate choice to trade um some one thing for another right I mean that said not everyone makes those choices deliberately of course and you know uh that's the ideal case is that everyone kind of like you know make all these value judgment and figure out what is the best thing to do for the product for the company for ETC right um so yeah so definitely when the some fail you don't blame the person who accidentally press the wrong button or whatever you blame the system you blame the tech lead who is basically the head of the subsystem that you have right whether that is you know your fun uh L6 or your L7 I don't know right depend your staff your senior staff depending on your company depend on what you're working on depend on the domain depend on all these things but yeah right yeah what I thought about that is that you know I think uh I mean that was just like a general uh system thing and so as a mentor to engineers in the past um I actually have this sometimes as longer sometimes it's shorter but the variation of the speech basically say um telling my junior Engineers like hey look this is how it is you know um everything that goes down or whatever stops of me it's my fault if you're able to break it right and of course I mean you shouldn't try to break it you know obviously we're all assuming good intents and all these things of like you know uh everyone's trying relatively their hardest trying their best and being in a coachable place so that you know we're in a place to learn we're all learning even me as at that time senior or staff or whatever it is depending on the situation right like we're all learning it's okay as long as we're all growing and it's okay as long as we don't make the same mistakes too many times I want to say not even twice really um but sometimes you know things happen and there you know especially when you're dealing with big system there's just a lot of interaction and the thing about building um a robust system um versus you know coding as we have here is not just that you build the system in a way such that it is hard or I mean obviously you try but that's not a system thing right that's just a coding thing you have to build in with these errors right um and it's about you know having uh either process on a technology level or like something that's automated level or something on a manual process level like maybe it's a checklist of um to kind of being able to recover from the failure state right whether it is the system being down or maybe you plan for it so that it know the system degrades but in a way that still works um you know and these are the kind of things that people think about and things that are you know um I think I mean I think maybe I'll split this up to a different video at some point to be honest so if you're watching this now thank you and I hope you appreciate just the kind of insight that I'm having now if not then you know fast forward as well I don't know it is uh it's fine but the idea there right is that you know you try to make the best you try to figure out what is the most important to you your system and stuff like that and try to you know balance all these concerns in a way that you know it um self we themselveses right and there you know in terms of processes you know this is what makes a staff engineer um I know that there's a lot of uh title inflation and uh and all these things going on uh I feel like what and I've been in industry for two decades which is kind of oh makes me old saying it but um but you know like what people would call a staff engineer now is probably a senior engineer like I don't know 10 years ago right give a tick um I don't know to me 10 years ago is like 1990 so I have to like think about the math man this is what happens when you get olded kids don't get olded but um no but seriously though um but yeah but these are the things that you know when um and what mix a senior engineer and sa Engineers that like I think what I and don't get me wrong to be honest when I was young and when I was that age and when I was a junior I was you know I thought I was uh a hot shot say without cursing and I thought I was you know I was arrogant I thought I knew everything I thought I'm really smart I could do anything I could do you know but and you know and it's true that you probably you know as a junior if you're a very good Junior um and you learn the right things I mean obviously you still have to do some learning and progression um you learn the right things you Pro you probably say I don't know 90% as you probably say I don't know 90% as you probably say I don't know 90% as good as a as you can be as when you become senior right or staff or whatever it is now I don't know when you get more senior not just the senior position I suppose right and the difference and I mean there also Al obviously other dimensions I'm just talking about the tech um there are different you know kind of job descriptions to a senior and a staff meaning um you know there are some other responsibilities that you're you know like you know some stuff is like project management depends on Company by company and some stuff about mentorship making people around you better the a force multiplier or you know skill multiplier as you kind of read in somewhere I'm kind of hand waving a little bit because I don't want to make this a 2hour video uh and you want to listen to that 2our video maybe one day you know let me know in the comments and maybe one day I'll post something up um but yeah it 90 you'll probably be as a in terms of a programmer in terms of a coder um you're probably 90% as good as coder um you're probably 90% as good as coder um you're probably 90% as good as a senior engineer right um in theory like but you know um maybe it's a little bit of a scam but you know your title is not a programmer your title or you know you want your title to be software engineer and what that means is okay engineer uh maybe that doesn't mean anything but what it actually means though is that you know you're hired to cynically one or two things two ways to put it maybe one is to sell problems for the company or maybe even more directly make money for the company right um and yeah and programming is one of the tools that you can and you know the reason why you get paid a lot as an engineer is that coding is one of those quotequote unique-ish skills that you quotequote unique-ish skills that you quotequote unique-ish skills that you are bringing to the job however um that is a skill it is in your tool set but it is not the only thing in your tool set and it is not you know the only thing that you're trying to do for the company right um and what I would say is that you know in the it is in those 10% in those 1% of the it is in those 10% in those 1% of the it is in those 10% in those 1% of the times that differentiates you know how you handle these situations right meaning that you know people get PA that multiplier because of that 1% of the multiplier because of that 1% of the multiplier because of that 1% of the time because they know what to do when I guess you can say when everything Breaks Loose say or when a lot of things hit the fans say right I don't know why I R on a r on a rent like this a 10-minute ret uh but rent like this a 10-minute ret uh but rent like this a 10-minute ret uh but anyway going back to why I talked about this is that my point is that you know these contests have been kind of a little bit silly contentious lately on lead code and I would necessarily bring on the testers I think some people bring on testers in this sense that like they should have found edge cases that maybe they should be but that you know you don't blame on them uh maybe not even the problem set though you know I have some questions about the part one part two thing as we talked about couple of days not a fan part if your part one is a for Loop you can write other problems that are for Loops it's uh it's not impossible I believe you I believe in you um but I think that uh it's just yeah now but I think like having these lazy uh system testing kind of puts the incentive in the wrong place in that like hey we can't be lazy uh I think the biggest thing that hits you know is that well two things one is that I think Le Co has to figure out who they want to be and what they want to be especially in terms of the contest scoup and with that North Star they can figure out how do we solve things when they come up right like is it a contest platform or is it an interview platform that where the contest kind of eminates as much as it can roughly in an interview I mean obviously nothing's been perfect PRS get harder because you know you want to be overprepared then underprepared I don't know there are some arguments there but like you know and I think one thing that I would that I loved about leadco contest to be honest and I'm just saying this as a nerd um is that I could be done when I'm done like I don't have like there was a time like it's been a few years now I suppose there was a time when you just submit it you get accepted you're like okay I'm done right like I don't want to spend the next hour like not trusting the lead coach test cases and you know thinking that maybe there's some weird thing and then come to find that you know I'm wrong right and maybe I'm WR but I don't know like I feel like I don't know I feel like there is definitely in Fox of people during the contest and they bring from competitive uh programming and they bring into the these contests their background of competitive programming contest and other things and their ideas of what they should be which is like every other Contest out there look there's uh you look at you know C list right there's like I don't know I don't remember what it is but like there's like 20 30 competitions a week why are we doing Le code if it's exactly the same as all the other ones and now you know right like I don't know it would be very weird if like you know I don't know I think that's my R for now uh I think my point is just that um I don't know system testing is never a happy surprise and now they kind of especially the past week um they have been adding system testing for um for Robin C and Robin C is uh a randomized algorithm which I loved a lot uh it is one of my first string algorithms that I learned when I was in undergrad and I guarantee you that um well maybe I would say guarantee but I would say that if you use Robin C in an interview um you will get it you know your interviewer will be impressed you would do well on the prom maybe they'll ask you something about Force positives and you just give like a one line like hey this is what happened to force positive like there is some chance but you know there are things you can do to improve it with double hashing add randomization Etc right um but you know the current way that it is projecting uh TRC and the way that it is set up it is just not um it just means basically no Robin cop or at least you know I mean it's kind of already a little bit sad to be honest um because you know for me um one thing that I was a purist about with respect to Leo contest in the last couple you know for as long as I could is that I was really against copy and pasting like temporate code like um Union fine or whatever you know or segment Tre I guess is the other big one like I was very against I like to do everything off my head off my brain somebody say that you know it affects my rating negatively and you know it's a little bit of a uh trickery and whatever um and you know yeah it's fine like I like other people do it I don't have to do it right but nowadays I feel like there and this goes back to where I think like Theo is not quite sure what it wants to be right because no one on an interview will allow you to P paste in a segment tree code because if they expect you to do that they just wouldn't ask you a segmentary problem right um I mean okay look there always bad interviewers so maybe I wouldn't say always but with any reasonable interviewers um you know where they're actually trying to do something you know um or trying to learn something about the candidates that's what they should do right like um and even the last Q4 on the last contest it was just basically 90% like contest it was just basically 90% like contest it was just basically 90% like okay there's a cute observation which is fun and then the rest is just copy in a code that everyone else has done and now you make it even more tricky for some people to do I don't know I'm not a big fan of things that are Library BR I feel like that is just lazy on the prom Setter side right because I think like maybe one time two time like okay look we're all learning it's fine but you know at a certain point no one is surprised that half the people that finish on top has a library code copy paste in right and then at some point like what are you testing here what are you trying to do here what I mean you know having the library ready and like and some of the comments I get in my videos are like hey you know are we expect to no this on interview and I'm and I always have to keep saying no not really but you know anyway all right sorry friends this has been a 20 minute rent I'll actually start the pr today hope everyone having a good day in the eyes of February 15 uh on this Thursday um man it is very cold here in New yor and I'm having some sniffles for whatever reason oh man my butt sugar is very high huh and oh yeah I've been a random quick up there as I that is that I still have my uh but Sho Coast Monitor and it keeps on pinging me every time it goes a little high and every time I got I actually don't do it that much during lead code problems but during the lead code contest it actually spiked a lot so it's kind of interesting to see um because I think it's just like the body's response to quotequote stress or like the fight or fight response so it releases and um you know what happens is that your liver releases these glycogen into the butt Stream So that uh your muscles can in a way take the glycogen and put it in so that you can kind of you know use your atps as fast as POS use you know get energy into your muscles as soon as possible is what I'm trying to say except for that I'm sitting here and like just I'm just doing this to get my muscles moving I suppose but yeah anyway all right now let's get started on today's Farm 1481 least number of unique integers after K removals okay given an way of integers R and integer K find the least number of unique integers after removing exactly K elements okay I mean right off the bat it seems greedy right because basically um we moving K elements so we well there are a couple of things that you can say I mean I say greedy but there are a couple things that goes of greedy immediately right the first one is that um well I guess if K is more than one you want to remove um so basically you want to remove all of them being the same number or as few numbers of elements as well the most ele how do I say this basically you want to remove all copies of one number whenever possible right because otherwise it doesn't change the answer for example let's just take even here if you remove five you still have a five so it still has two unique numbers right so you definitely want to remove anything that you can remove to um all the numbers up for example if K is equal to two then in this case you can remove both fives or one four it doesn't matter you only have one number left and yeah and then after that then so that's the first observation and that observation allows you to group them together into a frequency table say right and then after that it just becomes well if you have two choices in a greedy kind of way would you remove the N if you have K moves would you remove the number that we appears more often or less often well less often so that you have more k for use to for later right so in that sense both you have two points of greedy and I think that's good enough to get started and in terms of implementation you could do it in a couple of ways but uh but yeah oops let's get started I'll put them in a frequency table right so now F contains uh the value and the values the uh well the values in Array and then the count of them the frequency of them and of course you actually don't need the number itself like here we can actually store this as two and one we don't care about if it's five or four so then we can do something like f do values and then we could sort based on it and now we move the Min first right so maybe we can have removed is equal to zero for v in this number right if K is greater than V then we subtract V and then we move um goes to one and then so the number that are left is just be F uh the length of f minus we moved right uh I mean then you can obviously count this in a little bit differently but that's what the I would say and yeah uh that's pretty much it this is n log in can I do better I don't know that you could do better well I mean the only way that it could be better is if is linear time and I guess you can say something about um yeah I guess you can say something about like linear um uh linear sorting or something like this because they only I don't know by the way I'm just going to go with n l and time or of n space because the numbers can be all over the place and that's all I have for this one a really quick one uh surrounded by a 20 minute rent uh but yeah I did basically the same way but I did in a funky way last time huh weird but that was like also 4 years ago now and I think four years ago I've a few things in four years so anyway uh that's all I have for this one let me know what you think stay good stay healthy to good mental health I'll see yall later and take care byebye | Least Number of Unique Integers after K Removals | students-with-invalid-departments | Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
**Output:** 2
**Explanation**: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
**Constraints:**
* `1 <= arr.length <= 10^5`
* `1 <= arr[i] <= 10^9`
* `0 <= k <= arr.length` | null | Database | Easy | null |
377 | this is a classic dynamic programming problem where we're given a set of distinct integers and we want to find the total number of different ways that we can use the set of integers to add up to our Target number so in example one you can see that with the set of one two and three there's seven different ways that we can reach our Target number four in example two with only the number nine there's zero ways that we can reach our Target of three now imagine if we had a fairly large Target like the number 100 but the set of numbers we had were pretty small like only one two and three now it'd be really tedious to find all the different ways to add up one two and three to get to a hundred but imagine if we already knew the number of ways to get to 98 and let's say it was this number X now the difference between 98 and 100 is only two so all we have to do is find the number of ways to get two in this case we could have one plus one or just two which is two different ways so the number of ways to get to a hundred would just be X which is the number of ways to get to 98 plus 2 which is the number of ways to get two so that's exactly what we're going to do we're going to create a list where there's an index for each number from 0 up to the Target so basically we're only finding the number of combinations to get to each difference and then we're adding all those up to get to Target the start is a little bit weird at index 0 we're going to put the number one because we know that for any number in our set there's at least one way to get to itself and that would be a difference of zero now the difference is that we can have are one two or three because those are the numbers in our set so for one since only positive numbers we can only have a difference of one but for two we could have a difference of one or two so we add up zero and one and we get two for three we can have a difference of one two or three so we add up one and two to get four now for four we can only have a difference of one two or three so we don't get all the way back to the zero index we only add up one two and four for a total of seven and that's our answer there's seven different ways to get to the number four with this set and this is what the code looks like basically we're going to start off by creating our dynamic programming list and then we're gonna work our way up it moving you know one two or three steps back whatever the numbers are in our set and then for that index we're going to add up all the indexes or the values for the indexes one two or three steps back and then at the end we're just going to return the total number at the end | 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,578 | Hi gas welcome and welcome back to my channel so today our problem is minimum time you make the rope colorful so in this problem statement what have we given here live score and balloons are arranged here ek ro pe ok hai colors of balloons ek aapka Casting colors have been given, okay it has colors in it, the rectangle is representing the color of the balloon, okay, what does Like have to do, he has to make this rope colourful, that is, if he gets the color from two consecutive balances, then what he has to do is one. Balan has to be removed from there, so for this she asks Bob, so what does Bob have to do, what has to be done about this disease in minimum time, what has to be made colorful, okay, then what will he do, you have given him the needed time, okay, what is there in it? How much time will it take for you to remove the rectangle balloon? Okay, so what will he do according to that, he will remove the balloon, that is, you have to make his row colorful in minimum time. Okay, so let us first understand this problem through an example, is the problem exactly ours ? Then we will see how we can solve it. ? Then we will see how we can solve it. ? Then we will see how we can solve it. Okay, I have taken the first example here. What have I given you here? I have given you the colors of N and balance. Okay, this is the color of your end balance. Whatever it is, it will be of color B. This second balloon is of another color and C is of another color. Okay, so here A is presented in blue. Now you can take anything according to you, just see that whatever you have should be colourful, meaning two colors in a row. There should not be a balloon, it is right, this is A, this is B, these two are of different color, right, two consecutive different are of different color, right, so which of these two will you give, then here is the need. It is given in the time that it is taking 3 units of your time to remove it. It is taking four units of your time to remove it, so now who will do it? You need minimum time to remove it, so it is obvious that you will do it because there are three units here. It is right, if we remove it then this will become your answer. How much time did it take, how much will be in the answer? 3 because we need to remove only one button. Okay, now let us understand through the second example how we will do it here. Look here. But what do we do and B is of two colors, so here is what we have to do, then at least how many of these three will be made colourful, if you do n't want to do so, then we have to make two colors in a row, right, so here is your 3 units to remove this. 5 units to remove this. If it takes 10 units to remove this, then who will care if you have two options, so we will not remove it. Okay, now here we come, these three are from the Scene Group. If it is of the right color then how many of these three will you have to remove, two will have to be removed at least, what will you do, now whom will you remove, then see how much does it take for you to take five, and how much does it take for three, so which of the three? Hataoge And this is the thing that now you will hate this because you are taking less time in both of them, right here it will take a unit to remove both, okay now this is a single rate so there is no need to remove it, now this scene is of group. Here there are four of this group, these four belong to this group, then which of these four will you tell, at least three will have to be removed, then what will happen is that it will become colourful, if you give the right to three, then it will be that two If you are not of color from the consecutive one then what are the options here to remove you? Five 4 8 1 Now if you are asked among these three then which one will you choose? Will you look at the lowest one? Will you choose this one? 5 + 499 5 + 499 5 + 499 plus one 10 so 108 plus 8 16 + 10 26 plus one 10 so 108 plus 8 16 + 10 26 plus one 10 so 108 plus 8 16 + 10 26 Answer Apna 26 year right ok so how will we solve this problem here what we will do is 2.2 we will do that we will take income and k 2.2 we will do that we will take income and k 2.2 we will do that we will take income and k okay what will we do from here to here We will keep checking from is our which is equal to I? So what will we actually do? What will we find the group of color from? Okay, if we find the group of color from then we will see here that it is from this color. Okay, go ahead and color from this. Is it equal to I? Is it equal to Han? Go ahead, is it equal to Kard? Is it equal to Han? Okay, so when you come till here, you will get color from Se. Okay, now see how much is there in it, we don't know that much. It doesn't matter how much is there, we just have to see that you will have to remove all of them except the maximum. Whatever be the number, you will have to remove all of them except the maximum. If there is four, then there will be three occurrences. If there is 5, then four will have to be removed. If there is six, then your punch. We know that this incident will happen, so we will have to remove all of them with one break. Right, you are leaving the maximum one, right, so what will we do in this, whatever is the maximum, we will record it in a variable, what is the maximum till now, it is our body. Ok and how much will our total unit become 3 + 5 + 10, this much will be ok, we will find the sam, become 3 + 5 + 10, this much will be ok, we will find the sam, become 3 + 5 + 10, this much will be ok, we will find the sam, so what will be this much of a group, it will be 18 and what will we do in total timing, 18 - we will do maximum mines, what will we do in total timing, 18 - we will do maximum mines, what will we do in total timing, 18 - we will do maximum mines, ok We will do maximum mines, 8 will be left, we will add 8 here, ok, this will be done, then what will we do with I, we will update it here, it will be updated and it will start from here, then we will find a group here, it will come till here, we will find a group. What will we do here also? We will find these three in advance. Sam, it's okay in 12 plus. This is done. If you come here then you will move ahead. If you come here, if you don't find them, then we will go here and take them. Then they will go. We will get a group, it is ahead of badhaaoge, it is equal to I, it is equal to ja ke banaoge or it is equal to ahead of badhaaoge, okay, we have found this one group, what will we do in these groups, we will sum everyone, fine 5 plus 499 Plus 8 17 Plus This is what we saw here, this is the same right, we will return it here, now we come to the cold part, I will tell you the parts with code, it is from both, we have to do it as I have told, it is ok. Have we taken I, taken zero K, taken zero total time, okay and N taken, whatever size the color will be, its balance will be the same, what will we do now, I should be < what will we do now, I should be < what will we do now, I should be < N, K should be < N, okay, N, K should be < N, okay, N, K should be < N, okay, now maximum time. We will take zero, the maximum time of a group, you take the current total in the procession initial, take zero, okay now the current means what is the total of any group, it is not zero, then you will see, keep incrementing J< and keep finding the maximum current. What to do in the total? Keep adding, what will happen with this? 10 In the total, you will get the total. In the maximum time, you will get the maximum among them. Okay, then what will you do to I? Okay, then what to do in the total time? The current is as much as the current i.e. Sam total. How much is as much as the current i.e. Sam total. How much is as much as the current i.e. Sam total. How much is it, min the maximum time from it and can add it to the total time, add it and what will you do with the total time in the last, dem it, right, I hope you have understood. If you liked my video, please like, share and subscribe. please do thank you | Minimum Time to Make Rope Colorful | apples-oranges | Alice has `n` balloons arranged on a rope. You are given a **0-indexed** string `colors` where `colors[i]` is the color of the `ith` balloon.
Alice wants the rope to be **colorful**. She does not want **two consecutive balloons** to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it **colorful**. You are given a **0-indexed** integer array `neededTime` where `neededTime[i]` is the time (in seconds) that Bob needs to remove the `ith` balloon from the rope.
Return _the **minimum time** Bob needs to make the rope **colorful**_.
**Example 1:**
**Input:** colors = "abaac ", neededTime = \[1,2,3,4,5\]
**Output:** 3
**Explanation:** In the above image, 'a' is blue, 'b' is red, and 'c' is green.
Bob can remove the blue balloon at index 2. This takes 3 seconds.
There are no longer two consecutive balloons of the same color. Total time = 3.
**Example 2:**
**Input:** colors = "abc ", neededTime = \[1,2,3\]
**Output:** 0
**Explanation:** The rope is already colorful. Bob does not need to remove any balloons from the rope.
**Example 3:**
**Input:** colors = "aabaa ", neededTime = \[1,2,3,4,1\]
**Output:** 2
**Explanation:** Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.
There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.
**Constraints:**
* `n == colors.length == neededTime.length`
* `1 <= n <= 105`
* `1 <= neededTime[i] <= 104`
* `colors` contains only lowercase English letters. | null | Database | Medium | null |
1,643 | hey what's up guys this is chung here so let's take a look at this week's weekly contest problem number 1643 case smallest instructions so this problem you know it's a hard problem but it's kind of tricky because this one is more like a math problem rather than a regular like or either like a dp or like other problems so basically you're given like uh i'll just skip the uh those kind of uh descriptions here i'll just use these examples here basically you're given like a destination which is the basically the coordinates of a 2d here right a 2d plane here and another k here so the process is you need to from zero and you're starting from the zero and then you end with this destination in this case which is the two and three and then as you guys can see there are like many ways you can get to this location right and every time you can either go to right or you can go down you only have those two options and if you go to right as if you're going like uh adding a h instruction which means the horizontal and if you're going down it means that you are adding like a v instruction which is the other vertical vertically and based on your choice either you go to the crease go to right or you go down you end up with a unique path okay with h and v as you guys can see here so h is smaller than v okay and here is a this is the tricky part basically you need to find the case smallest instructions among all those instructions as you guys can see here we have 10 instructions in total because we have we need to make a 3 h move and the two v moves that's why we have 10 in total and we need to find the first one so the first one is hha to vv that's why we have this one and some other examples here same thing here same destinations but this time we need to find the k equals number two which is the hh v h v right so i mean the intuition is like this basically actually it already gave us some hints here you know so the hint is this one i mean the total combinations is the what it's a and like so ncr means the combination of this row plus column yeah so here we have three h and the two v's right and the total combinations of this five letter is what is three plus two right basically we need to have like the combination of three plus two uh out of two basically we are we're selecting two values out of five so how are we going to calculate this right we have like what three times no we have a sorry you if it's a com five two so it's gonna be what gonna be a five times 4 right times 3 and then divided by two times one sorry i think it's the 5 factorial right divided by 3 factorial times 2 factorial right that's the combination which is 10. that's how we get 10 here right so actually this so this problem it's more like a math plus the dp plus a greedy you know i'll give you some examples here since we have a k here right so let's say we have a h v and then we have a x here right and let's say we have already uh fixed h v here now we're at this location here okay and assuming we have 2h and 4 vs left in this range here at this location right at this place we basically we only have two options right with the current k here with the current case smallest number we need to match here we either we can either put an h here or we can put v here okay it depends on what so depending on how many letters i mean how many can we afford putting v here so why is that because if we put h here let's see we have a like case remaining here if we put h here it's basic we're still using the smallest possible options here right so it means that we still need to make like a case bigger number than the current options here right but if we're putting a v here okay if you're putting a v here it means that okay we are skipping all those numbers all those like uh the possible numbers who is starting with h from the current k basically we're skipping that so now the problem now it's easier to solve this problem because all we need to do is just that we just need to see if we can afford putting a v here which means that by skipping this man all the numbers that starting with h if we can do that then we'll basically we'll put a v here otherwise we'll put h and then the next problem is that how can we find all the numbers that's starting with h right so let's assume we have uh in total we have six here right how about all the numbers starting with h it mean it means that you know we are we're removing this h and we have now we have five here right so we have a five we have c what c5 c54 right because that why is that because this is in total we have six here right so we have six minus one since we have fixed this uh putting h here it means that we still have uh four v's within the remaining five numbers that's why the total combinations of here is like c five 4 which is exactly the same numbers right with who is starting with h okay yeah and after we have putting a v here we'll just uh subtract that number of combinations starting with h from the k and we'll keep doing it until we have finished uh constructing all those instructions and that's our basic solution here so i'll try to explain a little bit more here so basically we have destinations right destinations so the m is the uh is it's v right and h you know out put like uh this is like the v count okay right so and this is that the h count okay so and then we have a answer equals to empty okay and uh i'm going to have like this uh for i in range uh at the beginning uh since we have in total v count plus the h count right in total and then here i'm going to have like start right start with h so all the numbers start with h how many do we have so in python we have this combination built-in functions that built-in functions that built-in functions that can help us do that you know so we have like this minus i and the minus one because that's the current okay so first thing this is the current load the uh the remaining numbers of the card numbers but since we are trying to get the numbers all the combinations starting with h so which means that after fixing h as a current i and then we will the remaining length is -1 is -1 is -1 okay and then we have like uh the downs okay so i'm also going to define another here so like remaining v okay so at the beginning we have a v count right we have a remaining v here and this is the uh the starting with h the current the combinations that who is starting with h and now we simply just need to do a check here if the k so k means that we still have need to make this case uh the case numbers who is currently bigger than the current number right because we are we're looking for this case smallest number and we still have this case remaining here basically if the k is smaller than the target than the startup is h here it means so what does it mean it means that we have this many uh this uh numbers this combination who is starting with h and even this one is greater than the remaining smallest number we're looking for so what does this tell us it tells us you know let's say uh for example we have xx right and here let's see we have a we're deciding what uh wait which number uh which instruction where we need to put it here right let's say in the at this moment k is equal to four okay and we have five numbers left right and the we only and there are only four numbers we where we need to look for right so which means that it has to be h here because here it can be like h or v h something like this but if we're putting the v here even though we're putting h here right so we're way over than this like k uh fourth smallest number at this moment at this location so that's why we have to put h so that we can make we can get after filling in all those kind of uh instructions we can get the fourth smallest number right okay so that's why here then we have to do a uh in append h here elsewhat out is pretty the other way right else we do a v so this is the other uh the other way around basically if the current k is it's too big then the uh then the case is who is uh who is starting with h then we have to put v here because we have to cut we have to skip this many numbers okay and then after doing that right we have since we have skipped all the numbers that start with h now we will basically move subtract those numbers from the k and now with the updated k is the remaining numbers we need to be uh looking for right and since we're putting a v here i'm going to also decrease this remaining v by one remain okay and here later on which i need to return the answer here okay yeah so let's run a call here okay cool submit all right cool so i mean as you guys can see here right so what if the k is so is very big okay so if case is so big you know and ideally we should have like uh oh we all know it's going to be vv v and hhh right because that's the biggest number right so how would this thing works here right so that means you know k will always be greater than the start of his h here so it means that we'll always go to the answer here right then we try to decrease the case by this and then but again the k is still bigger than this so we have to put a v here and yeah until you know until what until this like remaining v equals to zero right so let's say the k is super big and there will be a point right we have used all the other v's here and now we're at h here right so if we add h here you know the uh the combinations here right so the combination of here will be uh okay let's see um i think that so it won't happen because i just realized that you know there's a constraints here so k will not be greater than th than the total combinations of the row and the columns here so yeah so basically it won't be that case it won't happen so it will always within the range here and this will always work so how about time and space complexity right so i mean we have a let's say we have m and n here right so of course this is a o of m plus n right and how about this combination okay i mean this combination you know the uh so the way we're calculating the combinations will be uh precalculating uh a pre products from this m from m plus n and here it's going to be o of one because if we're trying to calculate this one we'll be having like a pre products here from pre-products okay preproducts with the range of the uh from this is from zero to m plus n and here we'll the use of the values we have been we have previously calculated so here it should be like a o 1 here so the total time complexity it should be o of n plus n yeah okay so i think that's it for this problem you know um i think it's a pretty tricky problem at least for me yes because i'm not that good at this math kind of math problem so this is something we all need to to keep learning you know to keep learning so yeah and again so the key point for this problem is that you know we just need to know this way of calculating all the basically all the combinations where all the remaining instructions who is starting with h and then with this number i'll given these numbers and we check if we can afford skipping right all those kind of h's if we can we go with v if we can't then we go with h right cool that's it thank you so much for watching this video guys stay tuned uh see you guys soon bye | Kth Smallest Instructions | number-of-nodes-in-the-sub-tree-with-the-same-label | Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`.
The **instructions** are represented as a string, where each character is either:
* `'H'`, meaning move horizontally (go **right**), or
* `'V'`, meaning move vertically (go **down**).
Multiple **instructions** will lead Bob to `destination`. For example, if `destination` is `(2, 3)`, both `"HHHVV "` and `"HVHVH "` are valid **instructions**.
However, Bob is very picky. Bob has a lucky number `k`, and he wants the `kth` **lexicographically smallest instructions** that will lead him to `destination`. `k` is **1-indexed**.
Given an integer array `destination` and an integer `k`, return _the_ `kth` _**lexicographically smallest instructions** that will take Bob to_ `destination`.
**Example 1:**
**Input:** destination = \[2,3\], k = 1
**Output:** "HHHVV "
**Explanation:** All the instructions that reach (2, 3) in lexicographic order are as follows:
\[ "HHHVV ", "HHVHV ", "HHVVH ", "HVHHV ", "HVHVH ", "HVVHH ", "VHHHV ", "VHHVH ", "VHVHH ", "VVHHH "\].
**Example 2:**
**Input:** destination = \[2,3\], k = 2
**Output:** "HHVHV "
**Example 3:**
**Input:** destination = \[2,3\], k = 3
**Output:** "HHVVH "
**Constraints:**
* `destination.length == 2`
* `1 <= row, column <= 15`
* `1 <= k <= nCr(row + column, row)`, where `nCr(a, b)` denotes `a` choose `b`. | Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node. | Hash Table,Tree,Depth-First Search,Breadth-First Search,Counting | Medium | null |
6 | hey guys welcome to another leak code tutorial video in this video we're going to be covering leak code number six zigzag conversion so this is a medium leak code um and as always we're going to be going through the entire process from start to finish so we're going to be reading the question breaking it down um actually kind of using logic to determine how we're going to solve this um then we're going to do some whiteboarding to determine our approach and then finish it off with writing some actual code so I really hope this video was helpful before we get into that let me just say if you are serious about um uh getting good at these kind of data structures and algorithm questions um so you have an interview coming up that you really want to Ace or whatever it is I would highly recommend checking out the link in the description top of the description if you're serious about this kind of stuff it's going to take you to the next level when it comes to data structures algorithms lead codes and just basically make you Ace every interview um if you put that work in so let's get into this question so zigzag conversion uh we have the string PayPal is hiring is written in a zigzag pattern on a given number of rows like this and so we have it here and as you can see we have PayPal is hiring um and so it's a little bit of a weird to go pattern and then so we read it out line by line so we have this top line so pawn and then a to G which is here and then Yar and so this is for three rows as you can tell so we've done it in three rows but um as you can see from here we're at the code that will take a string and make this conversion given a number of rows um that the number of roses variable so realistically we could just have one row and it would just be paperless hiring uh you know we could also have say as many rows as there are letters in this which mean it would just be one column so there's a lot of uh variability within this so uh there's a lot to kind of consider so we take a look at the examples we had the one that we were given just before PayPal is hiring for three rows and it outputs as we expected like so and so example two input so the string is the same and this time we have four rows so this is going to be a completely different output so we have PayPal is hiring and obviously it goes down to four rows um and I think it's important to notice that they do look slightly different when you have photos compared to three rows like here we just had a single letter in between these kind of columns whereas here now we have two letters and this is going to increase you know as we increase the number of rows so and then so for our third example we just have a single letter with one row and obviously it's just going to be outputting that exact string so for our constraints we can have a length of string of one to a thousand so as you can see we had one here um and then it's just going to have English letters and characters like that and then we can have one row as our minimum so those are some constraints to consider for our base cases so let's get into doing some whiteboarding so we have uh the example that we were given that PayPal is hiring for three rows so this is exactly as we have here and so I personally find this a little bit misleading and it's important to kind of consider this if you approached this question in an interview if you were given this question is that the way they're given it uh the way they give it to you might not be the easiest or most obvious and it's intentionally a challenge so they might give it to you in a way that's a little bit confusing which is in my opinion what they've done here so this is kind of misleading because it makes it kind of it makes you think that they're almost like these columns going through like I mentioned before about the columns and these rows it doesn't really look like a zigzag pattern like you can see how they breached it by doing this zigzag but it just it kind of misleads you and can sometimes make people think that they have to I don't know treat it uh like these columns as we've seen in every example before however I'm just gonna show you a different way of showing that exact same data so we have PayPal is hiring in a zigzag pattern and as you can see it's the exact same with the pan and the a to G and the yir it's the exact same but this time it's a bit clearer how we're reaching that zigzag pattern and so in this way um this is a bit easier to consider how we're going to code it so we can literally just build it as they have it here so we can build the zigzag uh using data structures and using an algorithm so we're just going to create it so it goes through every letter kind of builds that zigzag pattern and then we just output whatever is necessary so how are we going to do this basically we're gonna have a for Loop that's going to go through every single letter in the string so we're going to go through them all and then we're also going to have a list which contains uh the rows so we're going to be keeping track of what the rows are and so for this one we're going to have three rows and so if you kind of think about it we'll go through the first letter We'll add it to row one we'll go through the second letter add it to row two go through the third letter add it to row three then row two Row one row two Row three and we'll just keep doing this um and so the way we're gonna kind of handle uh oopsie Daisy um the way we're gonna handle these kind of edge cases so how are we going to handle the direction I guess is the most important question here because you can do the for Loop easy everyone can do that you can create the list of all the rows quite easily that's something that everyone can do but how are we going to handle the direction so what we're going to do is we're going to kind of uh handle it based on these boundaries here so obviously there's boundaries here and it's dependent on the number of rows so this boundary if you think about it means that we have um the row is equal to zero so row equals zero and this boundary the row equals number of rows which we are given as num rows take one so we're going to have um sort of an increment variable and if we're going this way we're increasing the rows so the increment is going to be um one and then as soon as we hit a boundary if we hit this boundary the increment goes to negative one so then we can start going backwards and then we hit this boundary increment goes to one hit this boundary increment goes to negative one and that's how we're going to have this zigzag pattern is we're just going to base it off the off of these boundaries and then we're going to add it to our list of rows um so that we can kind of keep track of Row one row two Row three and then eventually once we've gone through all the letters it's simply a matter of adding concatenating Row one so it's going to be Row one plus Row 2 plus Row three and that's going to Output whatever we wanted so um yeah that's really the entire process for solving this question um it's a lot simpler when you at least in my opinion when you go from this which is a little bit complex a little bit confusing a little bit like how did they get this representation and then we bring it over here and we see oh it's literally we can literally just go through every single letter and add it to a row and then combine them all so it's a lot simpler in my opinion um than it's made out to be so now let's actually write some code so um I think the first thing we need to consider is the base case so uh the most important base case in my opinion for this is the one that it's just one row so in that case if we have a base case where we've got a single row then it's just gonna output the string that we've given so if num rows is equal to one then we're just going to return s because if you think about it if we had one row here it would just be PayPal is hiring along one row so now that we've handled that base case we need to create our list of rows so this is how we're going to be keeping track of all the strings um the strings of the rows so we can keep adding new letters to the relevant rows but we need to initialize them first so the way I'm going to do that is we've got a list of a list which means what contains one string here and then we're going to multiply that by the number of rows so if we add 2 if the number of Roads was 2 this would just create a list with two empty strings which is exactly what we want and now we need to actually handle zigzagging so we're gonna add all of the letters in a zigzag so we'll need to initialize the current row so current row equals zero then we need to have that increment value this is the one we're talking about so if we're starting here obviously we want it to be starting as one so we're going to set increment uh equal to one and then now we need to actually go through every single letter in the string so full letter in s um the first thing we're going to do is actually add it to the relevant row so uh rows current row and add that letter so this is just going to go through and add the letter to the corresponding row and then now we need to change that direction if we fit that boundary so we've added it to the relevant row now it's a matter of checking these two boundaries here so if current row is equal to num rows take one so this means it's hit this boundary here then increment equals negative one because now we want to go backwards uh else elif then current row equals zero so this means we've hit this boundary here which means we were going backwards and now we want to set increment to one to go forwards again so increment equals one um and then we just update the row count based on the increment by adding that increment and finally we just need to combine the strings again so all the rows rather so this can be done in Python quite easily with a little one line here um with a empty string dot join and then rows now I've done some things to uh for syntax purposes for example just to make it easier to write so this is one such thing so yeah they're just going to combine the rows uh and concatenate all of the strings and this as I'm in here before just creates a list of empty strings for the number of rows we have so if I submit this as you can see it was successful um top 99.16 in run time and top 96.15 in 99.16 in run time and top 96.15 in 99.16 in run time and top 96.15 in memory so um you know really great algorithm really efficient but yeah thanks so much for watching I really hope this was helpful if it was it would be much appreciated if you would like um And subscribe the video it would mean a lot to me so thanks so much for watching have a good one | Zigzag Conversion | zigzag-conversion | The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: `"PAHNAPLSIIGYIR "`
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
**Example 1:**
**Input:** s = "PAYPALISHIRING ", numRows = 3
**Output:** "PAHNAPLSIIGYIR "
**Example 2:**
**Input:** s = "PAYPALISHIRING ", numRows = 4
**Output:** "PINALSIGYAHRPI "
**Explanation:**
P I N
A L S I G
Y A H R
P I
**Example 3:**
**Input:** s = "A ", numRows = 1
**Output:** "A "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
* `1 <= numRows <= 1000` | null | String | Medium | null |
1,979 | Hello hello everyone so in this video write updates problem number 90 definitely comment device of problems and worst when invented the number zero number in nashik aaj tak latest comment device of two numbers in flu positive integer david number 100 index problem statement input device maximum and Minimum element should be a 100 dresses not problem statement and all can understand this matter so that he is example either in life behaving in all of us petis having to 5660 element 100g to how to add tank so This is a problem statement so they can solve this point will not give a in the dark a great man maximum the men and women and return yes only that I have to know a positive they can find a series of harmful sexual function in which CDO AEG chief to be one bp that just meanwhile kumma a model OBC 110th news in surplus solid straight city plus hua hai jhal ajay ko a solar water end and scored fastest way to give every day this appears setting on The minimum and maximum and on Thursday the maximum and minimum is then the industry if in first this statement of just Greater Noida near river in the city that is petting maximum on admin sir pass minimum can be written statement 200 point where will I have so let's friends Quotes for the Temple Trust Morning Vinegar Date Is Not Known Sources That Teacher Names Aap Think Se Ek Chapter Electronic All The Best Kaise Ho Member Captain Soft Thank You For Watching This Video | Find Greatest Common Divisor of Array | maximum-number-of-people-that-can-be-caught-in-tag | Given an integer array `nums`, return _the **greatest common divisor** of the smallest number and largest number in_ `nums`.
The **greatest common divisor** of two numbers is the largest positive integer that evenly divides both numbers.
**Example 1:**
**Input:** nums = \[2,5,6,9,10\]
**Output:** 2
**Explanation:**
The smallest number in nums is 2.
The largest number in nums is 10.
The greatest common divisor of 2 and 10 is 2.
**Example 2:**
**Input:** nums = \[7,5,6,8,3\]
**Output:** 1
**Explanation:**
The smallest number in nums is 3.
The largest number in nums is 8.
The greatest common divisor of 3 and 8 is 1.
**Example 3:**
**Input:** nums = \[3,3\]
**Output:** 3
**Explanation:**
The smallest number in nums is 3.
The largest number in nums is 3.
The greatest common divisor of 3 and 3 is 3.
**Constraints:**
* `2 <= nums.length <= 1000`
* `1 <= nums[i] <= 1000` | Try to use as much of the range of a person who is "it" as possible. Find the leftmost person who is "it" that has not caught anyone yet, and the leftmost person who is not "it" that has not been caught yet. If the person who is not "it" can be caught, pair them together and repeat the process. If the person who is not "it" cannot be caught, and the person who is not "it" is on the left of the person who is "it", find the next leftmost person who is not "it". If the person who is not "it" cannot be caught, and the person who is "it" is on the left of the person who is not "it", find the next leftmost person who is "it". | Array,Greedy | Medium | 2191 |
1,954 | hey everybody this is larry this is me going with q3 of the weekly contest 252 minimum garden perimeter to collect enough apples uh hit the like button hit the subscribe button join me on discord especially if you like these contests people go over the contest right after the contest so if y'all are looking for somebody to kind of do the contest with come on in uh come hang out i'll probably be doing that more as well but yeah so this one i struggled a lot with during the virtual contest as you can see it took me 32 minutes though i would also say that this is a product of my virtual contest because i definitely might have uh cheated if i did this in an actual contest and the reason is because um and you can actually watch me solve this live during the conte during my virtual stream and i stopped in 32 minutes maybe watching 2x or something like that but i go from my really full process so let's go over the long way that i did it and got a seat on and then we'll go over the cleaner ways of doing it um so the way that i did it to be honest is that i proved first i prove i have this code here i prefer spur pattern i you know for each length um i kind of looked at you know the total and from that to be honest i looked at the pattern and when i saw the pattern here for just some small ends i thought okay what about the derivative of that right and i just took the delta and i print that out and then i noticed that the delta of the deltas the second derivative um had a pattern so that's basically what i have here um when i print it out i saw a pattern i don't know if this is a riseable to be honest but i guess i had some uh intuition about it um but sometimes i would also say that one um this is probably not gonna be an interview question don't you know knock on wood maybe i'm wrong on this one and if so then good luck um two is knowing myself i know that i'm really bad at math though maybe i could have gotten this one if i did this more smallly but i was just stuck for a little bit and when you're stuck sometimes just do the best you can um grind it out and that's basically what i did um i did the brute force i just looked at this pen for a long time i know that i said everything about like oh just do it after second there the second delta other stuff uh in like you know one minute but actually it took me like half an hour to kind of look at that pen one at a time and once i did that once i saw the pattern i actually implemented the pattern uh and this is my solution one and this is very funky but basically i matched um i tried to match well from well for well this output to what i have here um and i if you watch the video i actually do this literally to kind of generate this ridiculous looking formula um so yeah i don't know how to explain it so i mean i will explain it but i don't explain it in the context of what i did because what i did was that's what i did i basically did a while loop here um the one thing i would say is that i ran this for 10 for the 15 to make sure that it's a small enough number um so that this folder worked in a linear way um because my intuition when i first saw this problem was that there's gonna be a formula and i'm gonna binary search on it and that's how you would get the answer right and that is a solution i'm gonna you know don't look ahead just yet that is the solution but i didn't know how to do it that way i have to do this linear way and with this linear way uh i had to get it to be fast enough unfortunately the inputs are small enough that this works for this one but you know i don't it is what it is i get in that sense i'm a little bit lucky but i also try really hard for it so you know um but maybe i should have thought about it another way sometimes you're stuck sometimes you have bad days but if you grind hard enough hopefully you just get it uh good enough um yeah um and then but i would say um if this was an actual contest i would have cheated um and how about i cheat well as i said earlier i've did brute force for pattern and if you watch my actual video i actually talk about oh just think oh yeah as a bit and at a certain point about maybe five minutes in something like that i actually don't remember the timing i basically said okay if this was a real contest i would have cheated and how do you cheat well it turns out that because this is a sequence you can use this thing called the online encyclopedia of integer sequences which is very often abbreviated as ogis people talk about this all the time but basically literally if you prove if you ran the brute force for the first five numbers you would get something like this and then you could literally search these the sequence and then you would have seen the sequence and then the sequence you know you have this formula right and we gave a formula then it becomes trivial uh well what is a lot easier and it becomes a lot easier because this formula as you can see it's going to be monotonically increasing um this is just an intuitive i mean you also know because you could take the derivative and then you see the derivative is always positive etc um we will skip the calculus for now but just know that for this formula it's binary searchable so yeah so given that i actually copy and paste it here i actually implement this after the contest this is correct um yeah so basically i have this formula i binary search on it and this is straightforward binary search stuff basically for oh yeah i think one thing that you have to return is the parameter so this is basically what i did to kind of convert it from the number of boxes or whatever the number of offset times two to get you know on both sides and then times four to get the parameter right so this is basic parameter stuff i also have it here hopefully that's understandable um but yeah uh and apparently people also say that uh if you have the pattern you can also use wolfram to calculate this but yeah also the other thing is that well let me finish this binary search thing first so the binary search is it's um binary search on the answer it's something that comes up a lot on lead code and code force and competitive and maybe a little bit less on interviews but it's still a good technique it's basically the answer of hey if there's a if we had as you can see this formula will always be increasing and then therefore you go okay let's say you have needed apples right you could change this to a binary um function of boolean function of true or force by okay let's say we have f of 10 um does f of 10 have enough apples and so forth right so that's basically how you do binary search and you kind of work it out because this is always increasing you would have you would answer the question you know for some x um you would have force well no and then at a certain point you do have enough outposts and it becomes you know phosphorus was true right and then the and the way that i always said it is that you know your bounce i'm going to choose my banks to be inclusive i need to set up i need to just record a binary search video because i think this comes up a lot i keep on doing it um but yeah so this is inclusive what i mean by inclusive is that left this is left and right and that means that both left and right could be a possible answer actually i guess there was not a possible answer but that's okay because that's always force anyway and then here that means that if because it's inclusive when left is equal to right that means that your inclusive bound is has one number um and that is your answer so if you get off by one you know that's basically something i would do middle it doesn't matter and then here basically what i do is i actually visualize this right um let's say min let's have a pointer if this is let's say you know let's just point at a ran uh at a true thing right so this is true let's say f of x have enough apples and what does that mean that means that our answer where is our answer right our answer is going to be on it's going to be mid where the pointer is at and to the left because we know that we will this will never be the answer because this is the answer right so this is never the answer and everything bigger than this is will never be the answer so that you can remove it and remove it by removing it you set the right to mid because now you want to set the right down to this one including this one um similarly let's say you have your arrow here let's say you have a force what does that mean well we know that this is no longer a possible answer this is no longer possible as well answer and everything to the left of that is no longer a possible answer right so i'm just going to write x so this is x double these are no longer possible so that means that the possible answer is going to be everything to the right which means mid plus one which is here you know i know this is first but it's a possible answer because we don't know this yet and everything to the right so then that means the left is equal to mid plus one for that reason because this is again inclusive bound meaning that left and right are both inside the answer and that's pretty much the idea here that's how much um and once you kind of ask yourself the same questions this should be clear as binary research so uh so another way to do it apparently is by roof room uh i actually did not do it this way but you can actually do an inverse function um because you know you have this formula that's let me type this in i don't know how you just went from that well but okay well yeah but the idea is that this is a function where you can find the zeros right this is literal um you want to set you know this formula as you go to needed apples so you can actually do this down all one per se but there are ways to do it this is literal um what's it called numerical analysis there are a lot of ways to kind of uh come up with this answer right so that's basically what i would say um and you can do this in much faster time it'll converge better than this bisection thing um but yeah so that's basically the answer there is a more intuitive answer but i was able to get it because i'm really bad at these visualization stuff to be honest so yeah so basically i'm going to give some credit to lonely dreamer on the forum um i think this is probably my favorite um thing that i kind of scan through for visualization but the idea is that okay for each ring you know you have this thing right uh for example for five you have fives plus six for seven plus eight residuals ten so then now you kind of just you know you can make the observation and you can do the math with respect to um you know the sum of numbers which is in this case is just five plus six for seven plus eight plus nine plus ten and then you times that by um you know you times it by four and then you also plus the one that is five plus six plus seven plus eight plus nine and you times that by four um i think they actually go over here yeah and then you have these answers and then you could do it that way to kind of either binary search or just get the program um binary search or just get uh yeah and then you do it that way um hope that makes sense um i could draw it out a little bit but basically the idea here is that okay yeah let's just say for example in this case you have five um five right so five is going to be five plus six plus seven plus eight plus nine or another way is that x plus one plus x plus two plus you know dot x plus x minus one right um oh well so you have this thing times four and also you have this thing times four i'm a little bit fast here probably but i think once you have this visualization you can kind of figure out why this is um and here of course this is just four times um the summation which is x uh maybe i might be off by one here actually x times x plus one over two minus oh okay so yeah you can expand this to uh okay fine let me just instead of writing the formula this is equal to four times sum of the first x plus x minus one numbers minus sum of the first x number or x minus one numbers right and of course this is a formula that you can derive uh i'm gonna leave it as a homework at home because i'm gonna get an off by one somewhere but given enough time i trust you can do it uh this is you go to the sum of the first x plus x or x times two numbers minus sum of the first x minus one numbers um so now that you have these two you can again either do the linear thing or um if you kind of just do the math and then some of this to get a formula which is probably just this formula and then you can now binary search on it so that's basically the i the way that probably is the proper way to solve it um yeah uh so here and yeah that's all i have for this one um hope i gave you a lot of possibilities an explanation for how to solve this one uh let me know what you think and yeah you could watch me attempt this problem it took me half an hour or more than half an hour on this problem uh you could kind of see how i grind for it watching 2x maybe even 3x um just to kind of you know sometimes you know you don't know the answer you know there are other ways to do it as long as you keep trying and keep grinding and keep going at it um cool uh yeah and you can watch me subject just from during the contest live next what a real problem uh okay let's go to three minimum like enough apples upon every okay minimum formula of a plot such what a weird problem today weird set of problems need uh inside or outside family okay so this is one we need one apple a square part of side length one does not contain any apple why not side length of one let me read this again oh because okay i see because it has the thing so this is just binary search with some kind of math i think we started writing a search review you're minimizing it but try to figure out the font name of the function or the function so okay so there's eight for two or the yeah i mean that's just call it one i think they do the silence to fool you one two this is where i need pen and paper and i wish i had pen and paper with me um some napkins but i don't have a pan how do i want to visualize it okay so instead of visualizing it let's proof force this a little bit when minimum parameter of a plot okay so it's parameter and parameter is just four times the length this is so much math so weird um okay fine let's play around with let's actually call that code that out because i'm too lazy to figure out or maybe i have a pen and paper okay let me put in range of one to say 10 just to print it out um print gold length what is it so okay for x and range of negative one or negative l to l plus one for y and range of negative l plus one um yeah okay i think my length is off by a power too but that's okay um yeah right i guess i only i don't really need this but it should return the same thing every time and also just print out names so i have something to print on okay so i might write on this one this is 12 which is i don't think this is right because this oh wait no this is right it tells you that this is 12. it's just that this is the parameter okay so 1260 168 360. what is the pattern here do i know the pattern paladin 1248 108 just a different delta what is that 12 48 and this is what i write on a paper a bit um but i don't have paper right now so does that make sense as a pattern maybe not i think one thing that i could do to cheat is odis but maybe i'll just because i'm practicing this isn't even a live contest i would just hold up a little bit more on 198 192 is a magic number and then 300 okay do i know anything about this delta progression as well it feels familiar but i don't and also to double check inside the math one because that would be really sad i've done that before well of length two what does this mean that means that it shows up one two three four five six seven eight times and then for um distant two it would be yeah this is the distance too so actually hmm and this is distinct way for five this is like the triangle numbers or something weird yeah because once we figure this out this uh pattern out we can binary search on it as my answer but this is where pen and paper would be very helpful um this is not just multiply because it has the same x y as well but now it's 2 1 and 1 2 and so forth so it's a little bit more awkward than just straight up this is a little bit unexpected 438 now 428 is that right this minus that yeah i guess that's right no way 432 i can't do math right now okay 432 that's not the number i'm familiar with unless i'm just wrong this is so mathematical okay is the way i can abuse symmetry okay i keep on saying 8 but this 12 so 12 is for one this is so math mathy like the algorithm part isn't that interesting the math3 part is interesting but not maybe not in a good way i think the other thing i can do is actually um do something like this just to see where it goes to so maybe this is actually too slow um sometimes so what i'm doing here is just trying to see if it grows too fast if it's cool if it grows fast enough and maybe this is something that i would have done um on my computer instead of on lead code but i'm it's too lazy to set up the thing is that if it grows fast enough then i actually just couldn't brute force for small numbers and then you know but this one seems like three million um i think the answer's like less than a thousand for or maybe not maybe more than a thousand uh maybe ten thousand is probably the answer for ten to fifteen but we still need a slicker way to do the math because the way that i'm doing it is clearly not gucci um this pattern doesn't really make sense to me okay should i cheat uh okay so yeah if you see something like this on the contest i would actually do oh yes and honestly to be honest if i was doing this on a real contest i would do odis but now because i am doing it as a practice virtual contest i would have gotten it because in the virtual you know oh yeah i guess i probably saw just in like five minutes and i moved on to the next one but that's okay we're here to learn we're you know it's a virtual contest so i can take some luxury here but i am reaching a uh a point of confusion actually no i like so i said ten thousand but actually they tell you oh i know this isn't 10 to 15 so i think my 10 000 is probably still right that the max number is probably ten thousand if you can do this you know one time you don't even need to do binary search possibly depending on your function is this formula right i guess some and this is 5 98 is that right 588 both of them are real numbers okay is there another way to think about this 2 is this way 48 why is this only 108. it's gross in a way that is weird to me so it has let me think about this for a second so going to two try to figure out a recurrence that makes sense so for each number so we times two okay so we had at least times two and then for each number we also so times two just scaling in one way but then we have basically one two three four well one two three four five six seven eight things to consider and that doesn't even make sense for greater than two huh really don't know how to do this one in a way that isn't cheating 432 oh and this is the parameter so actually this is even a thousand for the ten thousand so my ten thousand is by ray custom mistake um so we can definitely pre-calculate it if we pre-calculate it if we pre-calculate it if we so one thing that you can do um if i really if i'm feeling it uh a thousand cube is only a billion right so i could do this in a server and then i would actually print out um a thousand numbers as a precalculation and then just do a binary search on that one or something like that um so that's every answer so i already know how to do in two different answer way but i'm trying to do it the clean way of just um hmm let's try to find a pattern can i do just something dumb no i mean yes no i can probably just do something done with breakfast search maybe but i'm not sure that's any faster than this to be honest hmm weird q tv did i mess it up no 192 is right this is so weird i actually expect this to be at least times two but maybe now as well now that doesn't make sense to times two part because everything doesn't project so then you have to get numbers that are gcd and then it becomes like almost like a sieve but i don't think that makes sense spent a lot of time with this problem let's look at where this grows okay so this is what i thought it would be but can i is there a pattern here in this in every row 16 84 six hmm um i mean this is your pattern but this is such a weird pattern isn't it there's a delta of 24 on each row thought i saw it okay i mean this is quotable now so i have the answer but to be honest i don't know this is you know learnable uh okay so what does this mean that means that the second derivative is 24. oh man what does that mean right so the third derivative yeah just because this is the second derivative and the derivative is 24. um yeah you can do this in linear things so we should do it linear then uh yeah so okay so x is equal to 1 total is equal to 0 1 is equal to 0 say now let's just say 12 and this is 12 uh let's say 24 um yeah so then while true total is added to the number in a row at i think i'm missing one derivative this is such a weird way of writing it too not gonna lie but sometimes yeah you just have to do how you do okay i think i'm off here but okay so because one is 24. total is less than needed apples something like this maybe i'm off by one or two or maybe a lot let's print it out and see okay that's all and i just comment this for a second yeah whatever let's do this okay that was useless um also we want this times parameters four and this is actually this is times two maybe right this shouldn't give me a one though but oh no it is right let's see five or four eight okay so i'm gonna buy something that's a little bit unfortunate actually but that's okay uh to say this is this the number that we had before 24 60 144 i don't think so i'm printing the right thing yep so one is 12 2 is 48 so i'm actually off by a little bit in the starting frame this is such a weird problem yikes um so 2 is 48 so the delta here is maybe i need this delta first right this is right but i don't want it to keep my paste to my basement that's why uh okay oh geez hmm okay so this is right even though i'm not gonna lie i'm not proud of it um is this right i actually forget my sequence i don't think this is right this is off a little bit still or somehow gets the right answer i guess it's just close enough but it's going to get me wrong answer somewhere um okay so we have what's the sequence that i get so it's 12 48 108 so that's already wrong so we want this to be one away we want the delta to the of the delta to be plus 24. this is such a weird way of doing it um larry why are you weird let's step back a second and do it again so what are we doing here so we so this is the so i'm printing out this is the total this is the delta and then the third delta is the second derivative is the one that's this funky number and it starts at what's this 36 oh my i mean this is doable it's just annoying at this point so okay so 160 so we have 48 is the derivative and then you have second derivative which starts at 36. total we have 12 for the second row we detected uh this is such like i might as well just cheated on this one to be honest because this is such a uh this is such a mess also with that my setup nope i'm okay so this minus 24 so this is 36. oh man actually we want this someone like this let's see this is still well am i closer though tell me why this is not going too fast this is such a silly way of doing it but this is what happens when you're not good at math and i'll be the first to admit i'm not good at these kind of mafi geometry e things so but you know sometimes you just have to do what you have to do and this is what i have to do let's actually copy and paste this a little bit so i could at least i don't have to keep on re-running this when i on re-running this when i on re-running this when i do it this auto bracket fingers keep on messing me up okay so we want two to be 48. now this has to be 6156 is that right no 60 168 um and out first down to his first derivative is 48. right so i'm not right nope this isn't right the doubter should be less now this one is exhausting especially the way that i'm doing it i'm trying to build from this formula which is terrible it's probably a easier formula i'm doing it a stupid way all right let's take a look instead of scrolling back and forth i need more than one screen uh also that's beside support so here the delta is say 48 but now this is 26. 36 i 36 48 row is so we should go from here to the first row has 12 how am i doing this i think i'm just doing this in a weird way spending so much time on this one okay this is this 96 what does that mean that means that's the next row not the current row so maybe so this should be 108 actually not 48 so we started at 48 and then we want to add 60 right this is 60 but instead we added 48. okay is this closer let's see this would work better if the code uh was not so slow can i get any ring light there's better there's probably a better solution to this that's okay to refresh manual formula time from 60 to 16 this is not right this is such a sad one okay let's see if bo is let's just come on now let's start it off right okay let's say row 60 we let no that's not right row is 48 so we add this okay and then now the next row is plus 60 well the 48 to delta is actually 60 say am i'm getting very confused to be honest okay maybe i just need to do this what am i doing is this not right okay i mean this is this matches at least i believe let's see i just needed to step back and refresh my mind and everything apparently uh let's see 6168 saying okay so this is the formula though i'm not proud of it but hopefully at least um at least it shows you that grinding helps and also 6 30 is yeah i get the right answer uh let's try the max case while we're here since we only took a lot of time anyway so what's it 10 to 15 6 9 12 15. i had to oh isn't it 10 to the 15 maybe i have an extra zero now i've got to remove the print statement the price of brand 60 okay wow actually was wrong in that one i thought it'd be at less than 10 thousand so this may actually take too long so we might need to do a binaries well i can't do binary search the way that i did it unless you have a better formula okay let's just give it a yolo am i good enough to yolo let's give it a yellow i always spend too much time on this problem okay this is clearly not the way that i would recommend it but you know an ac as an ac okay let's see uh 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 other problems whatever you need to do i'll see you later to stay good stay healthy to get mental health see you later bye | Minimum Garden Perimeter to Collect Enough Apples | replace-all-digits-with-characters | In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it.
You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`.
Given an integer `neededApples`, return _the **minimum perimeter** of a plot such that **at least**_ `neededApples` _apples are **inside or on** the perimeter of that plot_.
The value of `|x|` is defined as:
* `x` if `x >= 0`
* `-x` if `x < 0`
**Example 1:**
**Input:** neededApples = 1
**Output:** 8
**Explanation:** A square plot of side length 1 does not contain any apples.
However, a square plot of side length 2 has 12 apples inside (as depicted in the image above).
The perimeter is 2 \* 4 = 8.
**Example 2:**
**Input:** neededApples = 13
**Output:** 16
**Example 3:**
**Input:** neededApples = 1000000000
**Output:** 5040
**Constraints:**
* `1 <= neededApples <= 1015` | We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position | String | Easy | 878 |
118 | what's up guys in this video we'll take a look at pascal's triangle problem difficulty level is easy so we're given number of rows and for that many rows we need to generate parcels triangle so obvious question what is pascal's triangle right let's go to the wikipedia let's see what pascal's triangle is so if we just look at this image that's all we have to do as we can see previous row helps you form the next row in particles triangle so let's look at this one now so third row one plus one two one fourth row is two plus one three that forms third row fifth row three plus one four three plus three six three plus one four so likewise so each previous row helps you form the next row and that's your pascal's triangle uh you guys can read this article like i was named after french mathematician blaise pascal there were other people using it like indian mathematician chinese germany italy persia everybody but it was just named after him so uh it's there on wikipedia so uh now that we understand what's pascal triangle is we need to implement it so let's see how we'll tackle it how we'll approach it and then we'll come back and run the code okay this is our pascal's triangle white board uh for simplicity we'll take five rows that's enough uh we can extend it just same approach but for more rows so for simplicity we'll just do five rows so obviously the first two rows are straightforward it's just one and then one right there's nothing into it so we can take that now what we do is we take the current row or the previous row in our row variable and what we do is we insert one more one at the start so let's do that so we did that and now we i trade or loop over that row and we add the current number and the next number except the first and last so let's see what that means so we'll take first number as is now we'll add this number and next number so 1 plus 1 will be 2 and we'll take last number as is so 1 so that's our next row in pascal's triangle right so we'll add it to result one two one now this is our row variable we repeat the process what did we do last time we added one at the start and then we iterate over the row and keep adding numbers so we'll take first number as is then we add these two numbers three and then we take last number as is that's our next row right one three one and you guys know what we'll do next right we add one at the start and then we loop over it to add the numbers we take first number as is 3 plus 1 4 3 plus 3 6 3 plus 1 4 and then last number as is and that's our fifth row one four six four one and likewise if we keep doing that we'll keep getting the next rows so that's it guys let's go to the visual studio code let's make sure that we are able to handle the list of integer and then list of integer to hold the result and how we actually do it so let's do that okay so this is our java code for pascal triangle yeah we are having a result array which is like list of list and then we have row which is our list of integer and what we do as we discuss like we add one at the start of the row and then we loop over the row and then we add the current element and next element except for first and last and that's how our that's how we get next row for the pascal's triangle and then once we have it we add it to the result and note that while adding it to the result we create a new array list of rows so technically we are copying that row into result if we just add row as is we would be adding by reference and then when we come back for next iteration it'll change that reference that we added so we don't want to do that we want to copy that whole items in the result and then we want to move on to the next row so that's why we do new arraylist so that's kind of like deep copy kind of thing if you are like from c plus world if you know pointers and everything then you know what is like deep copy and shallow copy and all that so uh there you go guys uh straightforward code so but uh by the way like do you guys know like uh pascal is a programming language yeah if you guys don't know then yeah you should i should check it out like uh yeah they made us like when i was in colleges like back in like 2001 2002 we had like a one class for pascal programming language and then they made us write programs in pascal similar things and then that's it i mean even during those days pascal was old like c plus was already like in and everybody was doing c plus but we still had pascal and i never did pascal after that so thankfully so let's run this code uh it's for firos so there you go uh we have our puzzle triangle for phyros obviously we can change number of rows and we can get bigger triangle let's just run it once and let's see uh how it looks so yeah there you go obviously like i didn't print it properly like once you have double digits the spacing calculation just went away so uh that's your particles triangle so there you go guys uh if you like the video give me thumbs up let me know your feedback and suggestion in comments and then as usual subscribe to the channel for more videos see you in next one | Pascal's Triangle | pascals-triangle | Given an integer `numRows`, return the first numRows of **Pascal's triangle**.
In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown:
**Example 1:**
**Input:** numRows = 5
**Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\]
**Example 2:**
**Input:** numRows = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= numRows <= 30` | null | Array,Dynamic Programming | Easy | 119 |
54 | all right what is up nerds programmers coders whatever you guys want to refer to yourself as today I'm going over spiral matrix I spent like a long time on this one yesterday I don't I just got stuck in the conundrums of it's actually not as hard as I made it out to be and just I don't know maybe I'm just an idiot but um giving a matrix of M by n elements M rows and columns return all elements of the matrix in Spile order so it's just like a snake so we're going one two three then three six nine eight seven four five so it seems like an easy concept a little bit harder to implement in code you have to be really careful it's very easy to make mistakes I was making mistakes yesterday so this one is one two three four eight twelve ten eleven ten nine five six seven there's some like edge cases I guess you'd call it that you have to check for so the way I did it is I just did it layer by layer so this matrix could be you know huge you could have huge layers so I recursively called it as you can see here I have my notes written out so recursion for bigger matrices so I just added the top row and then I added the last column then the last row and then the first column and you have to check adjust all the indices correctly and that's how I did it and I just recursively called it in case it was a big bigger matrix so you can add them all and we just add that to our new spiral matrix basically so right here I have our base cases if matrix is null or make certainly not equal zero or matrix zero dot length then we just return a new array that's actually wrong I don't know why that was even there so new beret integer we're just gonna return to new array list integer because that's actually what we have to return an ArrayList and I just so alright so first thing we want to do is to check to see if we are out of bounds actually I'm gonna code this up here so we're gonna want to create our actual list of integers that we're gonna return so I called the spiral new array this and then I just called this is so this is a function I already wrote I didn't want this video to take so long so I did kind of like the pseudo notes for it already it could have turned into 20-minute video and I did not want it to 20-minute video and I did not want it to 20-minute video and I did not want it to do so I'm passing this is where we're spiraling through it basically so we're passing in the spiral which we've just created the matrix which were provided we're gonna pass in the first row last row first column and last column so let's do exactly that and when we're calling it up here it is not recursive so let's pass in spiral matrix and since it's not recursive we're just passing in the first row which is 0 and the last row so that is matrix dot length minus 1 and then the first column which is 0 and then the last column which is matrix of 0 dot length and that should be it and then we just have to return spider at the end of this function so now let's code our main function so the first thing we want to check is if we are out of bounds this will make sense for when we're recursively call because we're going to let me show you on my iPad when we're going to shrink the rows and columns by one each so we're going to push this column in one so we're gonna add one to the here and we're gonna shrink them rows add a row from the first row subtract the row from the last row and subtract a column from the last column so it's like shrinking by one I'm each of them and if they're greater than or equal to so if the first row is greater than it's not greater than equal to I'm sorry if I said that this greater than the last row or the first column is greater than the last column then we just want to return so now we have our top row we're gonna calculate our top row so for int I equals 0 oh no it's of I so I have here we're going through I'm looking at my iPad so we are right here right now so we want to loop through one two three four so we're going to go through I equals last column because there's three of them so we're gonna go through the last column ernõ sorry its first calm we're setting it equal to the first column but it has to be while it's less than or equal to last column and we're going to increment it and we're just gonna add so now let's think what do we want to add we want to stay in the same row so matrix you want to stay in the same row so we want to stay in the first row and then we're incrementing the column so I and that's it for the that one and then we're just going to be last column so we're on row bar at the four we have to start here we want to grab these three next so for int I equals first row plus oh yeah so we're in the eve we're in the first row plus one so right here first row plus 1 Rho plus 1 because we already added 4 to it so we got to go down a row and while I is less than or equal to last row because we want to add you want to add 12 here so that's what the equals is for I plus and we're adding columns here so we want the columns to say the same this time so we have smiled add matrix I and it's going to be last column because we're in the last column right there and here is four weird cases where like the I think it's when we have this is exactly for this when we have an odd number of rows or columns they will end up when we add a row when we bring this one down so now it's here and this one up they'll equal each other so we'll have already processed it up here so we have to check for that so if first row equals last row we don't want to this is to prevent the duplicates or for first column equals lost comm then we're just gonna return and so now we have our bottom row so for int I so we are we're at 12 so we were at our last column so we want to do last column minus 1 because we already added 12 so let's do now we're going backwards so last column minus 1 I believe greater than yeah because we're gonna be decrementing I so I greater than or equal to first is it first row first let's see greater than or equal to first column I'm sorry it's first column and we're decrementing I and now let's add that to our spiral so spiral that ad matrix so we're adding a row so we want to roast the road to say the same so we're going to do last row since we're in the last row and we're going to do I because that's what we're changing B column we're moving along in the columns and then lastly we're at the now we're at the first column so we're into I equals so now we're at 9 and we need to go up so we're at last column minus 1 our last row I'm sorry last row minus one and here's a little tricky part because this is the we already added one so we don't want to add one again I accidentally added one and on my first try so I had a duplicate so the way we prevent that is if I is greater than or equal to first row oh that's not even first row goddamnit first sorry guys plus one so we're adding the plus one because we already have this one in it and if we do greater than or equal to first so we're gonna add the first row gun we're gonna be in the wrong position so yeah this is I minus as well because we're going backwards and now let's add that to our spiral so many tricks and we're in our first column so first so this is I because we're adding to comp riding the no I is that right I am first calm yeah okay that's what I taught my first column yeah I'm sorry I started to doubt myself for a second and that should be it and then this is the recursion for the bigger matrices in case there's lots of layers so let's just call spider matrix again and this will check to see if this is a if the matrix has an even number of rows or columns such as this one down here the so we're going to here I'll just coat it out so you guys can see the spiral matrix and then we're adding first row but will you have to increment it by 1 because we want to you know push it down we already solved that row so we already added that wrong sorry and then last row is minus 1 so we're shrinking down the layers and then first column plus 1 and last - Oren and so when we have an even - Oren and so when we have an even - Oren and so when we have an even number of rows or columns because we're adding one in subtracting one they're gonna equal each other so that's what this is checking for if they're the same then we've already processed them all so that's why it returns that's what that's for so let's run this code hopefully it works on my first try you know of course it does not where is it asked before Oh it's a semicolon instead of computer comma of course not notes I think it was a leak code error but one thing I did forget is I did forget to decrement the column length minus one so that was one little mistake but yeah now it works so let's submit this and a hundred percent so awesome so the runtimes over N and open space complexity as well if you guys have any question please don't hesitate to contact me and if you guys want me to solve any problems let me know and any criticisms on the videos would greatly be appreciated and I'll see you guys in the next video thanks for watching | Spiral Matrix | spiral-matrix | Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,3,6,9,8,7,4,5\]
**Example 2:**
**Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\]
**Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 10`
* `-100 <= matrix[i][j] <= 100` | Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not. | Array,Matrix,Simulation | Medium | 59,921 |
2 | sometimes when you come across a problem it feels super simple right but just because of the way it is written and described it becomes super confusing one such example is add two numbers on lead code it is a quite popular problem and ask in a lot of coding interviews and when you read it feels pretty straightforward you are given two numbers and you have to add them right but these numbers are given in form of a linked list and they are in a reverse direction as well so that causes a little bit of confusion let us see what we can 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 going forward we are going to discuss some of the edge cases and then we are going to see how you can arrive at an efficient solution and what are the use cases of this problem and as usual we will also do a drawing 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 of statement correctly in this problem you are given two linked lists which are storing two numbers right so the link lift entire on its own is one number each correct and the given condition is that these numbers are stored in a reverse order where each node of the linked list if representing each digit that is present in the number along with it you have certain more conditions like both the numbers are positive and even in each node you will find positive digits correct now given all of this you just have to return me the sum of two numbers and this should also be represented as a lift in itself where each node of this new list will represent the number and that too also has to be in the reverse order so what if all of this mean let us look at one of our sample test cases in our first test case you have a lift that is 2 4 and 3 and the second lift is 5 6 and 4. now the confusing part about this problem is although you are traversing the list as two then four and then three the actual number is in the reverse order so this number is 342 because you have to go in the reverse Direction similarly the next number is 465 when you read it in the reverse Direction so now you have got both of these numbers you just have to add them So eventually our problem turns out to be 342 plus 465 and its sum will be 807 correct now you have to return this result in the same format so this digit 7 this should be the first node the digit 0 this will be the second node and then the digit 8 this will be the last node so for this particular test case 708 this list will be your answer you can see that when you read it in the reverse Direction a to zero seven this is in fact your answer right similarly let us look at one more test case at this time there is a difference between the number of digits in both the numbers so at five number is 99999 represented as this first list and the second number is 999 represented by my second left you can once again see that these numbers are represented in a reverse Direction so behind the scenes what is actually happening is you are adding 99999 along with triple 9 correct and when you add them you will get the sum as one double zero double nine eight right and now you have to return this answer in the exact same format so it will be your first node and one will be your last node correct so for this particular test case my answer will look something like this you can see that I can find the number when going in the reverse Direction and that is 1 0 9 and 8. for now if you feel that you have understood the problem statement even better feel free to first try it out otherwise let us dive into the solution to understand this problem even better let us look at some of the edge cases that you may encounter so first of all let us say I have the sample test case in front of me and I have two numbers so you know that these numbers are actually in the reverse order so the first thing that you should notice is that the presence of zeros in this linked list so for example if I add a 0 over here right then this will not crop towards the actual number because this number will actually become zero nine five nine four correct and this view does not mean anything whereas if this 0 was at the beginning of the linked list then what will happen this 0 will eventually come over here right and this actually multiplies the original number by 10. so this kind of becomes the first thing that you should take care about you have to be bothered by zeros in the beginning and not by zeros at the end the second scenario is I know that as soon as you see this problem you will be tempted very much that okay I will just convert this lift to a number and then add them mathematically so when I convert these two lists to a number it will look something like this correct you add them and okay you found this as your answer now it is very tempting that okay you will just iterate through this entire result and create a new list correct and that will be your answer right but it will only work when you are in your integer limits or you can go up to Long limit right but what happens if your linked list has 100 elements or a thousand elements that means your number is thousand digits long how will you store that number in those cases all of your test cases will fail so certainly that is one Edge case that you need to be careful about and the third Edge case you need to be careful of if that what happens if your result has more digits than the actual original input lift so right now you have five digits and three digits right and this in turn gives you a five digit answer right but what happens if you add numbers like 99 and 9 what happens there in your output you will get three digits right so you need to be careful when you're writing your code and account for the extra node that you might be adding for now keeping all of these things in mind we can try to come up with a solution so first of all what we can do is we can have two pointers to start off with the first list and one pointer to start off with a second list right and now what we're gonna do is we are gonna start adding each digit one by one because you know that when we are doing addition you start from the last digit correct and this in fact is the last digit right so what I will do is I will keep two variables one is a sum and one is the carry now simply start adding the digits so first of all you will add 4 and 1 and that will give you five so the sum is 5 and the carry is 0. so I start off my new list and I assign 5 over here right now move both the pointers to the next position this time you get 9 and 9 correct so its sum will be 18. since there are two digits you will not write down 18 itself you will write down the sum as 8 and the carry will be 1. so to process this what I will do is I will create one more node over here and assign the value 8 in here right after this we will move both our pointers to the next value this time add 9 and 7 is 16 but this time I have one more carry right so 9 plus 7 plus 1 that will give you 17 correct so once again I'm gonna write down 7 in the sum and 1 will be the carry right for create a new node and assign 7 to it move to the next point is I move to 5 over here and notice that I am at null now that means I do not have any more digit in the second number so this time what you're going to do is you will take up this file and you will see if you have any carry since I have a carry I will add 5 plus 1 so that will give me 6 and the carry is now 0 right just take the 6 and assign it to a new node we are just left with the last element and we move on to 9. so this time my sum is just 9 and the carry is once again 0. so I create one more node and write down 9 over here for your fee we have traveled both the lift and we have arrived at our answers the addition of these two numbers will be 96785 and in fact this is your answer so as a river you will just return this head node and this in fact is your answer now let us quickly do a try and of the code and see how it works in action on the left side of your screen you have the actual code to implement this solution and on the right I have these two lists L1 and L2 and they are passed in as an input parameter to the function add two numbers oh and by the way this complete code and if test cases are also available in my GitHub profile you can find the link in the description below so to start off things first of all we create a sentinel node this is a revert node which will store our actual answer right and to initialize it I just initialize it with a value 0. so I will have my node something like this correct and at Point PTR a new variable to my result going ahead I also initialize a carry variable that is 0 right now correct and moving on I start a while loop that will keep on running until both of the lifts have reached their end that means both of the list have reached the null position correct and every time what do I have to add the two digits with the carry correct so first of all I initialize sum and I add the carry to it so when you're starting of things everything will be 0 correct now what do you do if L1 is not equal to null that means we are looking at the first node so what you're gonna do is you will add the first node to your sum So currently I just add 9 over here right and what I'm going to do is I do L1 equals to L1 dot next so this will move my pointer to the next node similarly moving on look at the digit from the second left L2 is not null right now so I take up this number 9 right and I add it to my sum correct and then what I will do is I will do L 2 equals to L2 dot next so this will move my pointer L2 to the next position right once you have got this sum I got 9 and that in fact equals to 18 right but you have to split out the sum and carry and that is exactly what I do in my next step if I divide by 10 then I will get the carry and that is 1 and if I do a modulus 10 then I will get the sum and that is 8. so what happens is in the carry I get 1 and in the sum I will get a 8 correct for you see I am done with my first digits now and this means I need to create the first digit of my resultant node so what do I do now I create a next node and assign the sum value to it so I will get 8 over here and then I do PTR equals to PTR dot next for this time my PTR will point at 8 right this Loop will go on and this time I'm gonna add 9 and 9 again this will give me 18. I have a carry as 1. so I'm gonna get 19 when you divide the sum and carry the sum will be only 9 and I will have one as per carry so I will get a 9 in here and this PTR will move to the next position correct one thing to notice over here is that the result variable still points at zero because that is where we started things right so this Loop will go on and ultimately you will have your entire answer over here and once you break out of this Loop if you had a carry remaining you just add one more node with the value one because that was your carry in fact right and once all of it is done just return revert.next because your entire answer revert.next because your entire answer revert.next because your entire answer will be after the next variable of the beginning node the time complexity of this solution will be order of n where n is the length of the larger link lift and the space complexity of the solution is also order of n because there could be n digits in your resultant lift I hope I was able to simplify the problem and its solution for you as for my final thoughts I just want to say that try to think where this problem is actually used you don't have to actually add two numbers and create a code for it right but then why do you even need it why is this problem aft think about it there are data structures where you can add huge numbers right the number can have hundreds and thousands of digits and then to your data structure can add them what happens behind the scenes this is what happens behind the scenes so these kind of problems give you some kind of idea how a larger program is made out of smaller tiny modules right so while going through this problem did some thoughts come into your mind that okay this could be a use case I can use it in this scenario or did you face any problems did you find any other problems that work on the same concept or any of the problems where you are having a doubt somewhere around this concept itself tell me everything 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 | Add Two Numbers | add-two-numbers | You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
**Example 1:**
**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,0,8\]
**Explanation:** 342 + 465 = 807.
**Example 2:**
**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\]
**Output:** \[8,9,9,9,0,0,0,1\]
**Constraints:**
* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros. | null | Linked List,Math,Recursion | Medium | 43,67,371,415,445,1031,1774 |
253 | hey what's up guys john here again so today as promised uh let's take a look at this like uh meeting room problem number 253 uh meeting rooms number two so you know on lead code there are like a series of different meeting room problems or you can call it interval problems right basically you're always given like a list of the after intervals in this case it's the start and end time okay so and for this one they're all like the start time and end time they're all inclusive okay and then this is like a very classic question it basically asks you to find the minimum number of conference room that's required to uh basically to host all these kind of off meetings okay um so for example this one right so you need to you need a root meeting room one like uh room one to host uh 0 to 13 right 0 to 13 and then you need another meeting room too to host five to ten because they have like intervals based uh intersections right so you need another one to host uh five and ten okay and then for the third 15 and 20 right you can reuse the same meeting room two here because those two they don't have any uh intersection okay so basically actually so this problem is it's the same as the uh basically what's the maximum right what's the maximum inter like intersection what's the maximum intersection right across all those kind of across all the intervals okay so in this case it's like uh 15 20 right yeah so it's the same as the uh getting uh trying to get the most intersections right the max intersection so in this case it's two right that's why we have a we have uh we the answer is two so this one since there's no intersection that's why the answer is one okay so for this kind of like uh interval problem you know a common strategy is we either sort we basically not common we always need to sort right either sort the start date or the end date okay and for this like minimum number of conference room required we need to sort by the start date okay so we start by the start date and then every time when we have like uh when we see a new meetings right and not only not we have uh besides the start date we also have like end date okay let's say for example so the if after sorting by start date we have a meeting room one here right oh sorry we have a medium one here at zero to thirty and now we have an ending time of 30 okay now the set the second one is 5 to 10 okay so we have a 5 to 10 and one every time we have a new start date here right we basically will be checking if there's any rooms that we can reuse okay so to be able to find the room to reuse we basically we need to find the meeting that's ends the earliest okay you know so to be able to find i mean which meeting will be ending earliest right across uh for the meetings that we have already scheduled before uh we need to basically we need to sort we need to store it by the uh the end date right how can we sort by the end date we can use the priority queue basically every time when we see the new meetings we push we uh we push this new ending time to that priority queue so that every time when we have a new meeting start time here we can always uh look for the first element of the priority queue right and that product the first element will give us the earliest ending time right and then and we will know that and uh basically we know how many if we can reuse any of the uh the meeting rooms right and if we can reuse that basically we'll basically will basically pop or pop that uh will pop that earliest ending time from the priority queue okay and in the end the length of the priority queue will simply be our answer here so why is that let's see so we have a priority queue okay so that's the priority queue the first time the priority queue will have 30 in it okay second time the second meeting is five we see uh is five greater than the earliest ending time which is not right that's why we will be uh pushing this 10 into the priority queue now the first element in the product here will become to uh 10 and 30. okay so this so basically the maximum priority queue actually the maximum length of the priority queue means the uh the mid the maximum intervals right we'll ever get right okay now let's continue so now we have 15 here right so the 15 is greater than 10 okay then we know okay so we can reuse one of the endings the meeting room who's ending with 10 now we just remove it from the 10 i remove it from priority queue and then we push it into we push the 20 into it okay yeah so that's the in the end i think the i mean we can either like return the length in the end the world we can just uh every time when we have a new meeting room we just check the length of the priority queue i think either way is fine yeah we can either check the i think for this problem we can just simply check the uh the length of priority in the end because that will be the our final state right um yeah of course pretty straightforward let's try to implement this thing so and first we need to sort by the by start time right so we can simply do a sort right because by default right it will be stored by the first element and then the second element which is the volumes we need right so we don't have we don't need to do a lambda functions here and then uh priority queue okay so um so for intervals right for intervals uh actually start and in intervals okay and uh if start um if not priority queue okay if there's nothing in the product here we simply do a particular.pen and the end time okay particular.pen and the end time okay particular.pen and the end time okay so that's the first step elsewhat else we uh we check right we check the if the start as if the start is equal uh greater or equal than the priority queue zero okay because the first element will always be the smallest in the product queue right if that's the case uh we will do a heap keep q dot heap pop okay priority queue right this means that i mean uh we can reuse since this the start time is the is it's later than the earliest ending meeting room which means we can reuse that right so we just push that oh sorry and then we just pop that pop this like the smallest the earliest ending room from the uh the priority queue and then in the end we just do a uh hip q dot heap push right priority q dots uh end okay in the end we simply return the uh the length of the priority queue yeah i think that should just work okay run the code okay this thing yeah cool yeah pretty straightforward right i mean it's not a hard one but it's very classic one so i think you guys need to master well remember understand the concept of this kind of like intervals problem you know you always sort by the start time right that in that case you can uh basically you know which meetings uh will i mean which meeting starts i mean what's the sequence of the start meetings right but besides the starting time you also need to keep like keep know uh keep another like data structure that can tell you which meeting ends the first okay and every time when you when the meeting ends right the earliest end meeting and then you can just use the current start time to uh to check okay if i we can if we need a new meeting room or not okay so the time complexity is uh actually the sorting itself right so the sort itself is already unlocked in here okay and uh here we have a n here right and to uh to do a hip pop and hip push right it's a login so here's an analog and the four rule is also a n log n so in total it's also n log n and the priority q here it's the uh the space complexity is it's o of n okay yeah because the worst case scenario right so the worst case scenarios we need to push everything basically we'll be pushing everything into the priority queue if there's no uh meeting room we can reuse basically we'll just keep pushing uh all the other meetings into this uh into this priority queue so the worst case scenario will be needing uh n meeting rooms in that so where uh in that case the size of the priority queue will be the size of n that's why the space complexity will be a whole n here yeah cool i think that's pretty much i want to talk about for this problem you know very classic one it's not a hard one but it's uh it's a very important one so i hope you guys can uh can really understand uh i mean the thinking process behind this kind of like intervals or meeting room problems and how you can utilize the sortings and then and also be able to get the earliest ending meetings right among all the scheduled meetings cool i think that's pretty much it thank you so much uh for watching the videos guys uh stay tuned see you guys soon bye | Meeting Rooms II | meeting-rooms-ii | Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** 2
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 104`
* `0 <= starti < endi <= 106` | Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied.
If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room. | Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue) | Medium | 56,252,452,1184 |
387 | hey and welcome today we will solve personal repeating character interview question which mostly asked by Bloomberg as less other companies like so we will explore a hashmap solution so without further Ado let's Dive In first example here as you can see there are few characters that repeated only once like l t c o and D but we are only looking for first one's index so we will return 0 which is for L second example L is repeated twice as well as o but V is repeated only once so we will return index 2 which holds character V and last example those A and B repeated so we might return negative one indicating that we found nothing in this string let's see how we are going to solve this problem the solution for this problem is super simple the first half of solving this problem is we need to trade over our string since we need to keep track of every character but for the tracking part itself we need help of some kind of storage like a hash map we need to know every occurrence of characters inside of our string actually how many times they've been repeated and gradually increments its respective value within our hashmap as we go through the string the second half of this solution is this time based on our map of characters we should be able to detect that which characters only has one occurrence that means another iteration over our map to find the actual result that we are looking for but we need to only know the first one before we jump into the code there are two important things about this problem that I need to make sure that you understand it clearly first one is we will use JavaScript map for or tracking storage and not objects and the reason for that is no matter what JS map will keep the order of item that we are adding into it I'll put a link from stack Overflow in the video's description in order to address the problem that I'm thinking about but probably this should not be a big problem in our case since we are dealing with characters I think you can use objects too but that is actually a big reason which could become handy to use JavaScript Maps over objects then the order of the insertion is important for you as well as this problem where we want the first non-repeating character want the first non-repeating character want the first non-repeating character second is I think the key takeaway from this problem is to teach us some minor thing about time complex City we have two for Loops in our solution but the time complexity will be o of N and that is because no matter what if you have two Loops as long as they are next to each other and not nested within each other you will have all of 2N there we skip the constant part when we represent the time complexity so keep that in mind too it's going to be o of n we should remove the constant part I soon create some videos short videos actually about these kind of topics so make sure to subscribe to the channel in order to not mess them up so without further Ado with that being clarified let's jump into the code here we are in lead code first we will create our tracker map now it's time for our iteration over string inside of this loop as I said we will keep track of letters occur so the key for our hashmaps entries will be our character but the value will hold two things first will be the index of the letter and second will be the occurrence count for that character we need the letters index because this question wants us to return the index of character not the character itself but that is for when we see the character for the first time and we need to check if we start before in orbitration because that is the opportunity for us to update the occurrence count inside of our if check basically we are going to update the occurrence current I'll put everything into variables for you to better understand the code and or readability reason but you don't need to do that you feel free to just put all in one line now after we've done with our iteration of our string it's time to find a character that only had one occurrence for that this time we are going to trade over our tracker we will use for of loop for that but remember that for our convenience we can play pluck hard stuff from or item now we already know what to expect from occurrence array first element is the index of the character and second is occurrence count we will plug them out again now we will do our simple check if our occurrence is one then we will return the respective index of that character and at the end if we haven't returned anything within our second Loop then we can return negative Bond indicating that we haven't found any character that only occurred once and probably all of the characters were repeated more than once now if I run this tests are passing and test submit we are in a good shape here now let's jump into this Live support time and space complexity analysis for time complexity as we discussed before it's going to be oauth 2 and where n is the length of our string and we will drop that constant 2 which will become o of n based on what we discussed before for space complexity it will be up n where n is going to be the length of our string because we are creating a hashmap that tracks every character in our string so that was it for this video I'll put the link for Strings playlist in the description to check it out thanks for watching and please leave a like comment and subscribe to the channel for more videos and finally hope you enjoyed this video and stay tuned for the next one | 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 |
70 | hey guys welcome back to the channel in our previous video we solved this problem lead code 70 climbing stairs which we solved using the top down approach using a memorized recursive function okay but now let's start using the bottom up approach right here and just so we know we developed this out in our previous example but now yeah we want to solve it using the bottom-up approach and the bottom of bottom-up approach and the bottom of bottom-up approach and the bottom of this we know the base case we established that for n less than or equal to three our return value f of n is just going to return n so meaning we can create an array okay and say we were given for example i'm going to use this f of 5 example we've been using again f of 5 okay we can create an array initially of zeros okay of length n minus one okay so there's first gonna be zeros in all of them okay let me write the indices so we know so this is index zero this is index one this is index two this is index three it's the index four this is the next five remember n minus one since n is five we need six items in the array we're creating okay it's going to be applied okay i'm going to say length and plus one okay that's the area we're going to create so we know our base cases right like you said we said if n is less than equal to three we just return so we loop through this array and say if n is less than equal to three okay we're just going to put n in there okay so let me go ahead and wipe some of these guys off that is less than or equal to two okay in this case is less than equal to three okay so while we're looking through it in this case index is zero right we're just going to put n in there zero in this case index is one i'm going to put n in there one right in this case index is two we're gonna put two in there in this case is three now for everyone else after this point everyone is after this point it becomes n minus one okay becomes f of n minus one plus f of n minus two which is the same formula we created here okay so for this guy is going to be the sum of this guy plus this guy so this guy's gonna be five okay because two plus three is five i believe yeah and four five is going to be the sum of this two guys okay it's gonna be eight and i believe this is what it is okay so this is called the bottom of approach and you're gonna see how we code in one second using an array like always we use python three and uh let me go ahead and make this bigger so we can see it okay and just so we know i'm just gonna put a comment in here and say bottom up okay we're using the bottom approach okay so now what do we want to create like we said our results is going to be equal to for now an array of zeros multiply okay and plus one this literally like we discussed we're creating an array size n plus one m plus one of zeros okay so now we wanna iterate for i in range okay what do we wanna do for i in range and plus one okay because we want to iterate up to keep in mind that the range is exclusive of the top okay so we want to evaluate up to n okay for i in range up to those points so what do we want to do so our if statement says if i is less than or equal to n okay we just want to put result of i is going to be equal to n okay this is just our base case kind of like we developed here okay it's going to be n up to till this point okay if i is less than or equal to three actually not m three okay we're just going to return air okay else now we do the fun stuff okay this is the real part so let's make it a l statement else okay result of r is just equal to the previous two years it's just equal to result of i minus one plus result of r the summation of the previous two guys okay and at the end we're not going to return result once we're done populating the loop we want to return resolve yeah i don't know i don't really know how to spell today of n okay let's go ahead and run the screen and see what happened okay accepted let's go ahead and submit it hopefully we don't exit our timeline since we're using an array okay so for the fourth so something is wrong with our approach so we expected five but we're getting eight so let's think what could possibly be wrong with our approach everything looks correct let's see if we return n minus one maybe when we're turning an index too high okay it's still around so something's wrong with our approach and it could be because of this right here so let's just manually let's return and let's take this back to return and let's just manually create this guy let's create this guy okay let's just create him manually which is the best way okay so then this means our range is gonna start from three and go up to n okay that's where our range starts from but however let's create this guy so we're just gonna see results of zero equals one result of one equal one and results of two equals two okay we're just manually creating our base cases okay let's try this out now let's run it we accept that let's do this index out of range results oh okay so this is the case where let's take this guy out okay let's take this guy let's just have our two base cases okay uh let's try this now okay so since we took two out this guy has to start from two i'm sorry if i'm just creeping today since we took two out first two we left two at zero when we initialized them okay now this is oh wow this is 98 percent so let's compare them to our previous okay oh we didn't would have previously this is so fast so again i'll text this i'll take this i don't want to stop here i want to take it one step further to be honest let's visualize what's going on so again since we made the correction we took two out let's make the correction here and let's start from two okay let's see what's actually going on let's go ahead and visualize this program okay so i just so we at this point we've called that function okay this is a global scope and we initialized our array of zeros 15 okay up to 15 okay so again i'll try to skip through fast but just watch it so we're just next okay so we're going to initialize results of zero is going to be one so we will put one in here so we're going to do the same for results of one okay now we have one in these two places okay so now starting from two we're gonna be in a for loop okay from two to n plus one okay so now we've added these two and saved it into for three we're gonna do the same we're gonna add this two and save it in three so three is gonna be three okay for four we're gonna do the same add this two and save it in four okay for five we're gonna do the same you just keep at it so you see how it's iterating adding the previous to you guys i'm placing him in the right spot okay all the way to 15. see how quick it can grow okay so this is called a bottom-up approach this is called a bottom-up approach this is called a bottom-up approach this is because we started from the base case and counted our way up literally so that's for this video guys i hope it was helpful and i'll see you guys on the next one you | Climbing Stairs | climbing-stairs | You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45` | To reach nth step, what could have been your previous steps? (Think about the step sizes) | Math,Dynamic Programming,Memoization | Easy | 747,1013,1236 |
1,697 | hello guys welcome to deep codes and in today's video we will discuss liquid question 1697 that says checking existence of edge length limited paths so guys this question is a very unique question and also interesting one so uh by going through this equation and writing the code you will learn a different use case of DSU or Union find data structure so yeah guys like this video and stick the end here you are given the undirected graph of end nodes consisting of edge list that represent the edge between node U node V and the distance between these two nodes u and v and we note there can be multiple edges between two nodes so if you see this graph ah here there is a one node one and node zero so there are two edges one edge with a distance to another edge with a distance exchange so that means that between two nodes there can be multiple edges right further you are given one added queries where queries of Y represent the node P node queue and the limit and your task is to determine whether that exists a path between node p and Q such that the edge on the path has a list is strictly less than limit option that means if all the edges that come along the path p and Q must have their length less than limit obtume right less than the limit so we need to return the Boolean at an answer for each query so guys if you take a look at the first example so here you are given one graph with three nodes and these are the edges one Edge between one and two of our length four two and zero for distance rate one and zero uh of a distance 2 and 16. now the first query says that a node 0 and Node 1 0 and 1 and 2. this is the limit is two do you do we have any Edge between 0 and 1 with less than two no we have we don't have at Max it is I means the minimum is two and we want less than two because the equation says strictly less than the limit so yeah that's why there is no such path that's why we return false now between 0 and 2 0 into do we have any path where all the edges are strictly less than five so see if you look at this path here this Edge is of length is of distance to this edges of distance four so in along this path all the edges have the distance is strictly less than five that's why we return true so we have got this understood the question now talking about the second example here you are given five edges and these are the queries right between 0 and 4 is there a path available where all the edges are of distance less than 14 between 0 and 4. so you can see that all this edges 10 5 9 13 they are less than uh 14 right so you have been written true between 1 and 4 is there any is there a path less than 13 no see here this path is of length five this is of distance 9 or length nine here this is of 13 and there is no other weight from one to four apart from this so that's why there is no such path with the edge distance less than 13 or for all the edges then so yeah for that be written false so I hope you guys have now some understanding what this question is trying to tell now in order to solve this question see what you can what one way you can do is uh you can see you are given this is list you can create the adjacency list right adjacency list now for each query what you can do is you can make a BFS a traversal in a query you are given like this node one node two and limit so you can make a BFS trouser from a node one and what you can keep track is along with node one you can keep track of maximum Edge in current path so you can also track this variable so in a queue you can take a pair and you can track this the current node as well as the maximum Edge in a current path maximum distance Edge in a current path so yeah if you will uh by doing BFS you can approach different parts and for each path we will trigger is the maximum match right and if you find any such path uh we whose maximum Edge length in the current path is less than limit then we would return true now in that case we would return true got it now the question here is does this satisfies the time complexity so for that let's check how many queries lens see queries length are up to 10 to the power 5. okay and the edges length is also up to 10 to the powerful right so let's say there are 10 to the power five queries and each time you are making a BFS phone so for BS BFS calls there are n nodes so each time you have to Traverse this and nodes okay or basically you are traversing if you are trousing all the edges and also it will take 10 to the power five so the overall time complexity here would be greater than 10 to the power 9. this is greater than 10 to the power and so that's why this will give you tle or time limit accented atom so guys if you try to do this approach by doing BFS each time for each query then it will give you Theory this is because that in a BFS you are repeating some of the tasks let's say uh in node one to node two mold 1 to node three you have to find the uh in the 120 you are given to find the distance between node one to know three and another you are given to find node two to node three so if you have computed here node one to node two node three the minimum path for these then again you have to compute this right node to the nodes this is repeating these things is repeating if you make a unique BFS for each time so yeah guys in order to stop this we have to think of some better approach now what can be a better approach so what if we make a graph dynamically we make rough dynamically so let's say what we can do is we can first thing you can sort query based on limit sort query based on the limit the let's say we did this so if you have some query like this N1 N2 let's say here it will be N1 and 2 and let's say 10 and 2 and 3 7 and 1 and 4. 6 so yeah we sorted like this n one n four six and two and three seven and N1 and 2 10 okay we sorted like this now what we will do is we can do one thing that we can dynamically build the graph we will take all the edges from The Edge list whose a whose distance is less than six and with those I just create graph with those edges create graph now afterwards for this query we will check is N1 and N4 connected and if you if they are connected then written true L false because in the current graph we have all the edges whose distance is less than six and in this current graph if N1 and N4 are connected then and we will return true yeah got this so this is one way to approach right we can think of this approach that we will dynamically create the graph we will create based on adding those edges whose distance is less than the current limit and in the current graph if N1 and 4 is connected then return true see this way it will works because the next query will have limit greater than the current limit and yeah previously edges are added so the edges that are not added then only that only we have to look for right now how to create a graph by adding edges uh whose answer is whose distance is less than current query limit how we can do this right this is our equation how now this can be done efficiently by using a famous data structure that is destroyed Centurion or you can say Union fine so this Union fine function Union fine data structure has two main function that is make Union and find parent and we will use this to function efficiently see adding the edges can be easily done by this make Union this function and whether N1 and N4 are connected so we need to check whether these two nodes are connected or not also this also we need to check so this thing can be checked by find parent right so this switch set Union has all the functionality that we need to perform this right in order to perform this DSU has all the functionalities that will help us to perform this right now see here we are adding the edges whose distance is less than limit we are doing this add Edge with distance less than limit so we are doing this but how we can do this for that what also we what else we can do is we can sort this we can sort Edge list this array is that we can solve this Edge list based on distance right so this will help us to I to keep up uh idea that how many ads list how many edges from The Edge list are remaining to it and how many are added we can simply put one pointer and Traverse all the edges right edges in the edge list and add those edges until the distance until age list of i n 2 means the distance that is the second parameter is less than limit so until this thing what we can do is we can run a loop and make Union right make Union is nothing but add the edges in the current graph right so yeah we can also sort these edges again that you will make us easily identify how many edges are remaining how many edges are added with the help of this I pointer right so yeah now combine all these things what we are doing is we are sorting the given query area we are sorting the edges list then we are using this DSU to make the union that is at the edges inside the current graph and then after that we will check in the for the current query for the given nodes are these two nodes connected if they are corrected then we can say yeah uh the reason a path between this N1 and N4 such that each Edge distance is less than the limit then only we can see so we will return true for that so yeah guys combining all these things let's move on to the coding part see this dh2 data structure I took it as it is this course snippet I didn't change anything from the course name head right it is as it is I have used you now initially I took the number of queries and number of edges in this variable and first thing what I did is since we are sorting this queries array but we need to return the answer variable based on the queries index so we need to keep track of queries with their Index right so that's why I took another Vector of vector 2D Vector queries with index and store the query so to store the queries what I read is I first store the limit then the node one node to end the pointer or the index I this is nothing to track the index right but I store the limit in the first parameter so that we can directly solve them we can directly sort them now to store to sort the edge list what we have to I we have to compare based on the distance right based on the distance we have to sort so the distance is the second parameter so that's why we have to write this function else it will sort based on the first parameter only that is the zeroth in the experiment but the distance is there the second index so yeah additionally this function is required right now then after that we took the answer there is a Boolean vector and the current Edge index so the current Edge index is the last Edge that you added to our graph you can say like this so now we will Traverse for each queries and we will build the graph dynamically okay we'll build the graph dynamically so here what we are doing is uh these are just two uh to keep track of the uh all the current query the nodes that are present the current query so here this while loop is very much important so here what we are trying to do we are looping until the current Edge index is less than any that is total number of edges and the edge list of the current Edge index is less than limited is the current Edge index distance is less than limit so all the edges which uh which are less than limit we are taking them and we are forming this graph by using make Union we are forming the graph right so inside the size list we have we also have node one and node two there are two nodes between whose the edges is there and we are making the Union right and then incrementing current Edge list so see this current energy list is outside this for Loop it is here so the next time the edges that are already added we don't add them back right because this is uh Global for the current this is global for the for Loop and the while loop right it is declared here so yeah guys the all the edges that are already added we don't add them back and only the remaining edges whose distance is less than the limit are added right and at the end after this while loop ends we check whether the P1 NP weather the Node 1 and node 2 is connected the node one off for this query NO2 for the q1 query are they connected to know whether they are connected or not we check for fine parent if their parents are same then we can say they are connected this is how DSU works for all the nodes in a current component dh2 does what DS to make that parents the same so let's say in this component you have N1 and 2 and 3 and 4 and 5 nodes the DS2 doesn't it makes that parent same it's it does this it will make all this nodes pattern same so yeah we will check if there is some connection between Node 1 and 02 then we will return true to the index of the answer right and the end we didn't answer so yeah guys I hope you understood this question and this is the approach that we are trying to do I know it's a bit hard to build the intuition for this question right if the intuition building part is very much hard because uh this uh you must know that with DSU also with DSU what we can do is we can dynamically build the graph you must move this and then only you can think of DSU otherwise intuition building goes hard for this type of patient because if this question is a unique One of a Kind so yeah that was the reason now talking about the time is space complexity the time and space complexity are easy to guess here see the time complexity is nothing but we go fan that would be taken when you initialize the DSU plus Big O of uh number of queries that are the n q log of NQ because we are sorting all the queries plus we go of any that is number of edges uh log of any this is nothing but sorting takes n log and sorting takes n log n and login so that's why for query sorting and for Edge sorting this will be time complexity and space complexity would be uh so first thing we are storing the queries here additionally we are storing the query so let me take this as NQ although this is the 2D Vector but this is a fixed length of a length four so we can we won't count then also it's okay and uh Additionally the weird the additional space would be for bigger fan as we are taking this rank at parent Vector inside this DSU and apart from that uh yeah we are not showing anything so this is for the time and space compensation so yeah guys that's all for this video if you guys have any doubts then do let me know in the comment section make sure to like this video And subscribe to our Channel thank you | Checking Existence of Edge Length Limited Paths | strings-differ-by-one-character | An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.
Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for each `queries[j]` whether there is a path between `pj` and `qj` such that each edge on the path has a distance **strictly less than** `limitj` .
Return _a **boolean array**_ `answer`_, where_ `answer.length == queries.length` _and the_ `jth` _value of_ `answer` _is_ `true` _if there is a path for_ `queries[j]` _is_ `true`_, and_ `false` _otherwise_.
**Example 1:**
**Input:** n = 3, edgeList = \[\[0,1,2\],\[1,2,4\],\[2,0,8\],\[1,0,16\]\], queries = \[\[0,1,2\],\[0,2,5\]\]
**Output:** \[false,true\]
**Explanation:** The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.
For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.
For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.
**Example 2:**
**Input:** n = 5, edgeList = \[\[0,1,10\],\[1,2,5\],\[2,3,9\],\[3,4,13\]\], queries = \[\[0,4,14\],\[1,4,13\]\]
**Output:** \[true,false\]
**Exaplanation:** The above figure shows the given graph.
**Constraints:**
* `2 <= n <= 105`
* `1 <= edgeList.length, queries.length <= 105`
* `edgeList[i].length == 3`
* `queries[j].length == 3`
* `0 <= ui, vi, pj, qj <= n - 1`
* `ui != vi`
* `pj != qj`
* `1 <= disi, limitj <= 109`
* There may be **multiple** edges between two nodes. | BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*"). | Hash Table,String,Rolling Hash,Hash Function | Medium | 2256 |
1,732 | hey guys welcome to the channel in today's video we're going to look at a lead code problem and the problem's name is find the highest altitude in this question we given a gain array which represents the net gain in altitude because there is a biker starts from a point0 with altitude equal to 0 so there are n + 1 points and there are n + 1 points and there are n + 1 points and there are n elements inside the array because we start from altitude zero so that is not part of the gain array and our task is to return the highest altitude of a point so let's take a look at this example and see how this question can be solved so I've taken the same example given to us and currently we're at altitude 0 so I declare a variable current and initialize it to zero simultaneously I also have to create another variable called Max which will give us the maximum altitude we have reached so since current altitude is zero Max is also zero now we iterate through the input array from left to right and we keep adding that element to the current value and compare the current value with the max value So currently uh 0 - 5 is - 5 and Max of 5 currently uh 0 - 5 is - 5 and Max of 5 currently uh 0 - 5 is - 5 and Max of 5 and - 5 is 0 so max of 0 - 5 0 now we go and - 5 is 0 so max of 0 - 5 0 now we go and - 5 is 0 so max of 0 - 5 0 now we go for the next element is 1 so add it into the current variable we get -4 check if 0 or -4 is Max 0 is get -4 check if 0 or -4 is Max 0 is get -4 check if 0 or -4 is Max 0 is still the math now go for the next element is five so add it to the current uh value you get one so check current Max with current we update Max with one go for the next element is zero add 0er to the current value you get one and current Max is one and current is also one so max will remain as one now in the next iteration you get min - 7 so iteration you get min - 7 so iteration you get min - 7 so added current value you get - added current value you get - added current value you get - 6 check it with the current Max will remain as one and finally we reach the end of the for Loop and we return whatever is present inside the max variable in the end so max is equal to 1 so one is our output now let's Implement these steps in a Java program coming to the function this is the function name and this is the input gain array of length n and representing the number of elements inside the array but there are n+1 points because we're there are n+1 points because we're there are n+1 points because we're starting at a altitude zero and the return type is an N because we have to return the maximum altitude throughout the entire road trip so we start with the max element which will be returned as the output which is initially zero and now we start at a current altitude of zero which is not part of the gains array Now using a for Loop let's iterate through the gains array so in each iteration we're going to calculate the next altitude the biker will go from that point so we add the current gain into the current altitude and now we get a altitude right so we are going to check it with the max altitude variable so until now if the current altitude is the maximum assign that back to maximum else if maximum is greater than current so maximum will remain the same so in each itation we immediately checking if the current altitude is the maximum altitude you reached until now so outside this for Loop we'll have our answer inside Max and we'll return Max as the output now let's try to run the code the test cases are running let's submit the code and the solution has been accepted so the time complexity of this approach is of n where n is the length of the gain array and the space complexity is constant o of one because we're not using any extra space to solve this question that's it guys thank you for watching and I'll see you in the next video | Find the Highest Altitude | minimum-one-bit-operations-to-make-integers-zero | There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i` and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100` | The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n. | Dynamic Programming,Bit Manipulation,Memoization | Hard | 2119 |
395 | good evening millennials today we look at another lead code medium problem asked in the final rounds of some big interviews such as by dance and amazon so let's read the problem discuss various approaches and try to call the shortest code possible so it's the 3395th problem in the lead code website called longer substring with at least k repeating characters so given a string s and an integer k return the length of the longest substring of this substring such that the frequency of each character in the substring is greater than or equal to k so let's look at the examples to understand better so if the string is a b and k is three the longest sub string with each character greater than or equal to k is three because of a and when s is equal to a b c and k is equal to two the output is five because of a b because a is repeated two times and b is repeated three times when three is greater than or equal to two that's okay but it should be at least two so the constraints the string length is between one two and part four and s consists of only lower case letters and k is between 1 to 10 power 5. so remember that you can only iterate two s dot length once or k ones that is you cannot run an n square algorithm because of the constraints but let's look at the naive approach so for naive approach for each uh substring you can get the each substring in order of n square so from i to n and j to y you can get each substring and you can find the count of each substring in order of 1 which is because there are only 26 characters and for each substring you can check this condition but that'll be order of n square so we need a better approach because it won't pass the constraints so the another approach is to use a sliding window technique within order of n so the basic intuition behind the sliding window is that there are only 26 characters and for each of these unique characters if we can find the longest substring for that much unique our answer would be the maximum of all the unique number of characters so for we iterate through the number of unique characters and for each of them we iterate the string order of n times so the total crime complexity would be order of 26 into n which would be order of n so basically for each of the unique characters we find the longest substring satisfying this condition where each character is repeated at least k times so let's try to write the code so we have to return an int so let our return be answer so let us initialize answer to 0 because the initial substring length is 0 or the base case and let n be s dot size and let total unique be the number of unique characters in yes so for modularity i would write it in a separate function get total unique of s okay now let me define the function int so let me just copy paste the function definition so in get total unique of string s so it's given that it only consists of lowercase english characters so we can just have a boolean array of 26 letters and initialize to false so for and i equal to 0 i less than 26 plus i'm just counting the number of unique letters in the string so if not so i need a in total unique equal to zero now if not of array of s sorry i just i trade through the string so for auto ch colon s if r a of c h minus a if not of r a f c h minus a r a of c h minus a equal to true and total unique plus so i'm just calculating the total unique number of characters and at the end i return the total unique okay so this will get me the number of total unique characters so now i have to create a window based on the total unique so for i equal to one so i'm considering minimum length as one i less than or equal to total unique plus i so for each total unique i will declare four variables in windows start which will be zero because i migrating the string again and again same window end which will be zero and current unique characters which will be zero and current total k which will be zero so what this current total k signifies is that for the current number of unique characters there are how many characters with its frequency at least k so now while window and less than n so i just i trade through the string if the current so i trade through the string if the current unique is lesser than or equal to uh once again so now i need to i trade till n and for each window i need to check uh whether the number of characters exists or not if the number of characters don't exist we move the right window end so for that case we need to check whether the current unique is lesser than or equal to the top number of uniques in this window so here i do window and plus else i need to do windows start plus so let's write the conditions inside so if so i need a map right to calculate the frequency in each window so i'm declaring the frequency array of 26 initialized to 0 in each iteration of the loop so if so we have to check for that character so if frequency array of s of c sorry it should be frequency array of s of window and so window end is an iterator so minus a if this is equal to zero we just increase the unique because the number of unique characters has been increased and it was initially zero and then we increase this frequency array as well similarly if this equal to k so the current k total also we need to increase so then we increase our right window else what we do is if this is true we decrease our current total so instead of here window and we need to have windows start because we are increasing the start here and we have to increase the current total and similarly we have to decrease its count because we are moving the start pointer and similarly now if the frequency array of windows start minus a then we have to decrease the current unique and at last if our current unique is equal to the current iteration of unique which is i for each unique character we are checking right so for each unique character if the current unique is same and if the current unique equal to the current total k so that means we have found a substring which satisfies this condition so answer will be maximum of answer comma window and minus window stuck and after the loop we just return answer i think this should work but let's just run the code so there is some error so okay i haven't declared the variable okay let's try to debug it so let me just print the total unique to make sure whether it's correct or not okay so the total unique is right let me just remove this window start window and so while the window end is less than n if the current unique characters is less than total unique is it wow i decrease frequency is zero i just increase it and if it's okay i just increase this thing windows start window n minus windows start and here i check whether the current unique and current unique equal to current total k for each window if the current technique so i'm just trying to debug that in my mind so if the current total case less than or equal to k for each window we need to check whether i'm initializing it inside and this all right so this if condition should be inside the while loop because i'm checking for each window so let me just submit it oh sorry uh i think it should be current unique less than or equal to n sorry it should be current unique less than or equal to i think it was right the first time let me just submit it yeah as you can see it's accepted and it's better than 80 run time and 94 memory so if you liked our video please like comment and subscribe and please leave a comment if you have any constructive feedback and as usual i'm sorry for the small uh mistake in the between because uh of this single bracket because for each window we have to update the start and end so please subscribe thank you | Longest Substring with At Least K Repeating Characters | longest-substring-with-at-least-k-repeating-characters | Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`.
**Example 1:**
**Input:** s = "aaabb ", k = 3
**Output:** 3
**Explanation:** The longest substring is "aaa ", as 'a' is repeated 3 times.
**Example 2:**
**Input:** s = "ababbc ", k = 2
**Output:** 5
**Explanation:** The longest substring is "ababb ", as 'a' is repeated 2 times and 'b' is repeated 3 times.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of only lowercase English letters.
* `1 <= k <= 105` | null | Hash Table,String,Divide and Conquer,Sliding Window | Medium | 2140,2209 |
1,046 | so hey guys welcome back to my channel and after a long this I had started and uh I am trying to continue this series because I bought the new penate because there were many difficulties to write the programs and means uh to explain through the pp so I bought the pen tablet so I will uh try uh to continue this series per day so the question is last Stone weit it's an easy level question of a lead code so let's read it you have given an array of integers Stones where Stones I is the weight of I Stone we are playing a game with the stones on each turn we choose the heaviest two stones and smash them together means uh if there is an array then we have to choose the largest two elements from that array and the suppose to supposed uh the heaviest two stones have weight X and Y uh with X is smaller and equals to the Y the result of this MH is if uh X is equals to Y both stones are destroyed and X is not equals to Y then the stones of weight is destroyed and the stones of weight y has a new weight y - x so at weight y has a new weight y - x so at weight y has a new weight y - x so at the end of the game uh there is at most one stone left okay and return the weight of the last remaining Stone uh okay so guys here first we have to uh find out the uh the two elements that are the greatest in the array so here uh we are using the two means here we are using the priority cues through prior priority cues we are finding out the values of that means we are finding out those heaviest two stones uh that are uh heaviest two uh Stones so let's go on the tab open board okay so we know if we are taking the example okay by 2 7 this is the first case um 27 so if this is an example then we have to create here the tree uh not the tree is priority trees so first it here mean why we are using here priority cues the reason is because through the priority cues uh we can remove those two heaviest mean the two largest element from the array uh means in the priority element root so it is root node for that and the condition will be for this is uh here 4 here 7 1 uh and here uh so as we know K it uh first we are giving the conditions of a removal to the eight so we will popping out the eight outside and after that if uh the huh this is a first element or the first uh first element we are popping out from the binary not the priority trees or the priority cues and priority cues the priority is defined actually means defined from first only priority as compared to the smaller element will be greater so um so we will just popping out or removing the two elements that are the greatest one in the array or in the priority cues so first we the in the priority cues so first we will remove it and second we will remove seven after that um huh if we are removing here seven then first means if we are removing uh here eight then first will be eight then four down hi ification guys and first four then one have a seven as we know these are this doesn't satisfies the condition so as we know priority root greater than any other element of the left sub tree or the right sub tree in the priority trees so here we are converting seven and then four and then one we are taking your next page s p then four then one then two here will be one H and if we are talking about time complexity then we are KN we are removing the Two topest element we are removing we are REM removing the topest the two top element so uh through the Collision uh there will be the time and complexity that will be log and we are removing the two times so if we are removing the end time log again so there will be uh and login so this will be the complexity time and space Time and Time complexity so let's go on the question okay we are here on the question and this is a solution for this uh so what I had done here so just I'm going to tell you he first I had used here the priority cues and the starting and the beginning of the and I as I said there will be the three conditions the first the priority cues or we are determining it by pqs we are determined by pqs here that this pqs so these pqs will be greater than the size of a pqs or the pqs can be greater than one or not equals to zero or the zero if it is zero then uh I think then if it is zero then we have to return it zero and uh the first condition will be keep um the first condition will be the a p q means that is a priority cues should be greater than one then there will be the two conditions there will be the two condition that are uh as I said they will popping up the first topmost element that are this the first element and then popping up the second element that is P2 and the second last and here B we are using one algorithm that is we are finding out the absolute value and after that absolute value that is the first Maximum element finus the second maximum element and after that we are using the last condition here by if the priority cues or the size of PQ is not equals to zero then what we will return that we will return zero so uh this is the solution for this so thanks guys | Last Stone Weight | max-consecutive-ones-iii | You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000` | One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on. | Array,Binary Search,Sliding Window,Prefix Sum | Medium | 340,424,485,487,2134 |
421 | hi all welcome to learn code repeat so today we'll be looking at the day 16 problem of the september challenge so the problem is we have to find maximum xor of two numbers in an inter array so let's look into the problem statement so this is the problem statement which is given a non-empty array of numbers is given a non-empty array of numbers is given a non-empty array of numbers a 0 a 1 a 2 till a n minus 1 where a of i is greater than or equal to 0 and it is less than 2 raised to 31. find the maximum result of a of i x or a of g that means any two number in that array where i j is less than n and it is greater than equal to zero and could you do this in o f and run time so this is uh an important factor of and run time because to find the max of any two numbers in an array we can easily do it in n square time right so we can have two for loop and we can check what are the maximum xor between two numbers so in this case in the example if i xor 25 with 5 i'll get 28 which is a max in this list of numbers so let's look into this example so this is the example that we have in lead code so before going into the example let's quickly refresh the xor properties so in xor when you do one x or zero you get one zero x or one we get one again one and one is zero and zero x of zero is zero so that means any digit or any binary number if it is different than the other number then we always get one right so x are of two different digits in binary if both the digits are different then it will always be one if both the digits are same then it will be always zero this is what xr is right and also we have to note that xor is both associative and commutative what does that mean is if there are three numbers and we are xoring between those three numbers a b and c you can place the bracket anywhere for example addition is commutative and associative right so you can place the bracket anywhere and still the addition of the numbers will be same whereas if you have addition and multiplication then it is not commutative right because placing a bracket in multiplication at different places will yield different results right similarly here in xor like addition xor is commutative you can place the bracket anywhere so a xor bracket b x or c is similar to bracket a x or b bracket close x or c similarly its associative that means that if a x or b equal to c then a x or c is also equal to b and b x or c is also equal to a we will use this property in our problem also one more thing to note is if i want to set the bet at it index in a number i left shift 1 by i so i is the exact bet index where i need to set the bit so here right uh let's say i is 2 right so if i left shift 1 by 2 so i will get 1 0 as the number right and if i mask that with any other number since i am doing or operation so that means even if the bit index is having value 0 or 1 is 1 and even if it's having 1 or 1 is 1. so this will guarantee that particular bit is set so let's see how we can use these two operations in our algorithm right so let me first represent the binary representation of these numbers in our array so here if you see the numbers are 3 10 5 25 2 8 and the binary representation for that number is this and what we need to find is the two numbers when we xor that it will give me the maximum number right so any number right which is the largest number it will have its uh left most bit set right so between any two given number if the leftmost bit is set for a number then the other number then that number will be largest for example in case of 25 we know that 25 is greater than 5 right so the left most bit of 25 will be set compared to 5 right so 25 has the bit set at 1 2 3 fourth position right whereas pi has the left most bit set at sixth position right so four is left most than six so that's why 25 is more right so we can use this knowledge to check which is the largest number when we do the xor right so how can we do that right so what we'll do is for each number right we can go from left side so for this example sake i will take 8 bits instead of 31 bits right so let's say this is 8 bits right so from left side i will go one by one and check if any of the number has its bit set as one so from left side i'll go one by one and i'll check that right so for example in this case uh it starts from zero one two three four five six seven so i'll do two raised to seven right uh so two raise to seven will be the highest number that i have with which will give me one and followed by zero right so what i'll do is uh i left shift by seven digit right so this one is at first place i have to left shift by seven digit so that one comes here right so i can use this property mask and uh when i do a left shift by seven digit i'll have the number as one followed by seven zeros in this case right it left shifting this one by seven right so it will be one two three four five six seven so one will come here one followed by seven zeros right and then whatever is the outcome right i'll end with my number right so i'll do something like this where i am getting the prefix num so what will happen is if my mask is one followed by seven zeros and i am ending with my num right so and will only give true if both the values are one otherwise it will give false right so in this mask right uh currently only the first bit is one right on from the left hand side from left to right only the first bit is one so this will give me one only if my three is having one at the first bit so that way i can check whether that bit is set right and uh i can add that in a set and i can build the prefix num for the first bit and similarly in the next loop in the next iteration i can build the prefix sum for the next bit right where i can consider this two okay so at this point if i'm at a first bit right uh what is the best number or biggest number that i can have the biggest number that i can have is this number to be set right which is one followed by seven zero if i'm at this position after that right the biggest number that i can have is setting this bit as one and also this bit as one right so what i can do is in my next iteration i'll again left shift one by six digit because now the counter is decreased so i'll left shift by six digit and then order it with my current mask so my current mask was one followed by seven zeros and then i am ordering it with one followed by six zero so it will give me one and then followed by six zeros right and when i use that mass to and with my num i'll only get this two digit right and i'll get only those two digit uh for the num and that way i'll come to know whether this is 1 or 0 right and since i am adding that in a hash set it will only store unique values right so once i have the number stored in has set right now will come to this property right what we are doing here is similar to let's say that my target is 15 right and i want to check what numbers adds up to 15 right and let's say i now have 5 as a number right so to check whether the other number which is 15 minus 5 is there in my set which is let's say the set contains is 3 10 5 25 2 8 right provided that i have only one number and i know the target i can directly check whether 15 minus 5 is present in my set so in this case 15 minus 5 is 10 is present in my set so that's a valid combination that i can have i can say that okay 5 and 10 gives me 15 so that's a valid combination right so similar to that right once we have the set built with the prefix num right now we have to find the target which would give us the best number right so here we will take the greedy approach right so what is the largest number if i am at bit position 1 what is the largest number that i can have is one right similarly if i'm at bit position two the largest number will be one basically if all the bits are set as one that is the best number that i can have right but i cannot set all the bits as one and then check in my array right so i have to check within the limitation of my array right what is the best possible combination where all the bits are one in my array i can have right okay so what i am doing is this is a target that i am assuming that this is the best i can have now if this is the best i can have then there should be two numbers a or b or a and b which when i xor i will get the target right so at this point i have the prefix nums right for each bit from the array i know the prefix num right so i can so one of the a variable is this right so what i can do is i can do prefix num xor t okay and if that value whatever is the value of prefix num x or t is present in my set right the set of prefix nums right that means that is the best possible largest number that i can have which is t right till now that is the best possible largest number then we will go to the next bit and again do the same operation there right so the way we did uh the sum approach right where pi plus 10 equal to 15. so we subtracted 15 minus 5 and check whether that number is present in my array similar to that we are doing prefix num x or t right let's look into the code and understand how we can implement the algorithm right so we will be using only these three properties that is a x or b equal to c that means a x or c equal to b and this masking part and this part okay so first i'll go over the numbers from left to right and here it's mentioned that the number of digit is 31 right so i'll have to go through 31 bits right so i'll use a for loop and i'll declare the max variable and the mask as zero so max variable will show the maximum number that i can get from xor operation and the mask will have the masking operation right that value it will store so at the 31st point it will be having 1 followed by 30 0 and then at 30th position it will be 1 followed by 29 0 that way so let me mask the number i am shipping one by i once i have the mask then i need to apply the mask to my nums right i will apply the mask to the num and i'll add that in a set so by doing the ending operation i'll make sure that only that particular bit which is set in my mask only that bit is also set in the nums right if it is not set then it will obviously be zero right so once this is done and i'm having the set populated now as a greedy approach right i'll check what is the best maximum value that i can have right at this point right so that will be in max right that i can have is whatever is my current max so okay so i'm at 31st bit so it will be that bit i'm setting and i'm xoring it with my current max right in the next iteration when i'm at 30th bit right so whatever was my previous max value i'll add to the next bit i'll add one that means i'm enabling the bit after that right so for example if it is 128 right 128 will be one followed by seven zeros right one two three four five six seven right so this is the best at this position right which is two raised to seven right so for two raised to 6 the next best i can have it or when i equal to 7 is this is the best i can have right so when i equal to 6 the best i can have is i will set this also to 1 right so that is what i am doing here when in the next iteration i will set that bit to 1 and i am xoring it with my previous max okay so my previous max here was 1 0 so i am extruding it with my current max that i can have so it will give me this right so that's what i'm doing here so i'm assuming that okay this can be the best that i can have how can i validate that this is the best i can have right so this will be the best if the num in my prefix there are two nums in my prefix when i xor it i will get this right which also means that if i go through or loop over my prefix set and if i xor each number with my temp max then whatever is the output should be present also in my set if that is the case then this is a valid max value right so i will do that here if my set dot contains my temp max xor prefix value the current prefix right if this is the case then this temp max is my current max my i can assign my max equal to temp max and i can come out of this right because we have now validated that this temp max is the max element right we can assign this max equal to this and we can come out of this now here right we do not have to do the check max is greater than max only then assigned because we are going from left to right and at each point we are enabling the bit and checking whether that is the max value so since i am going from left to right so earlier my max would have been something like this and then i enabled the next bit while going from left to right so the next bit if i enabled my max would have been this right so this for sure will be greater than my previous max right so that's why i can directly assign my max as temp max okay so once i am out of this loop i can be rest assured that whatever is the final value of max that will be the maximum of xr of two different numbers within that num sorry right because we are going from 31st bit up to zeroth bit in the for loop right so at the end i can return my max value and let's submit this so the test case works fine let's submit and the result is also accepted now here the complexity will be of n y o of n so even though we are doing a for loop and inside that we are doing another two for loops so this in this for loop we are going over nums so this is having complexity of o of n where n is the number of elements in my nums array and in this for loop we are going over the set which is a prefix array right or prefix set right now that since it will hold unique values it will be always less than or equal to the nums array so in worst case it will be n right so here what will happen is it will be the total complexity will be 31 times n right since 31 is constant we can say that the complexity of this algorithm is o of n okay and in the worst case the space complexity will be o of n as well okay so if you have any questions or any doubt regarding this algorithm you can always comment down in the comment section below if you like the approach please hit the like button and do subscribe to the channel thank you | Maximum XOR of Two Numbers in an Array | maximum-xor-of-two-numbers-in-an-array | Given an integer array `nums`, return _the maximum result of_ `nums[i] XOR nums[j]`, where `0 <= i <= j < n`.
**Example 1:**
**Input:** nums = \[3,10,5,25,2,8\]
**Output:** 28
**Explanation:** The maximum result is 5 XOR 25 = 28.
**Example 2:**
**Input:** nums = \[14,70,53,83,49,91,36,80,92,51,66,70\]
**Output:** 127
**Constraints:**
* `1 <= nums.length <= 2 * 105`
* `0 <= nums[i] <= 231 - 1` | null | Array,Hash Table,Bit Manipulation,Trie | Medium | 1826 |
1,944 | hey everybody this is larry this will be going with q4 of the buy weekly contest 57 number of ruins for people in the queue so this one is a little bit tricky so um yeah so hit the like button hit the subscribe and join me on discord especially if you come here right after the contest uh don't the discord people are very good at discussing these forms right after the contest so come hang out anyway um so for this problem um yeah the first observation is that you know i would think about how to read what we think about the farm in different lengths it will raise or different ways of kind of going about it in this case um you know it feels natural that they give it to you in left to right order and you kind of go left to right but with experience you'll see that actually you want to go from right to left because there's some kind of um ordering or structure that you can build on top of it by adding it one right per um adding from the right one person at a time so yeah so the other thing that i did during the contest to be honest i messed this up is that i thought it was the longest decreasing subsequence i'm not going to really talk about it that much because i don't think it makes any sense and i don't know i try to make sure that it makes sense but it didn't really um so then the thing is just really passing this um up right so the two things you need to do one is kind of keep track of uh how many people you so how many people between you and the first the next person who's taller than you or the end of the list um is there right and and you can actually do this as a model queue i didn't have sorted list it doesn't matter because there is a login over there and we'll discuss this on this in a minute but yeah so for example if we look at this let me make this virtualization slightly easier by putting it here but yeah if we're at the six for example we cannot see the anything beyond the next highest number which is eight the other thing that makes this easier is that all the heights are unique so you don't have to worry about equal elements which i was playing around for a little bit as well let's say grab the eight then we can see all the um almost like a monotonically increasing sequence um of the next value that is you know for for example this eight you know you have five and eleven and even this for example there's a two here eight doesn't actually see the two because the five blocks it right so um we're just basically looking at okay five and then every time you get a number you ask the next thing of okay what is the next number after the level that we oh sorry after five that we can see and it's 11 right so basically what we do here now is that we just keep track of that increasing list that you'll see for example here we start with nine and then when we see the eleven we know that we'll never favor c to nine again right and this is the principle behind the mono queue this time okay well nine can never be seen again so that's c11 because for monocube type problems you're trying to think about a way to give you all possible answers right um and because the nine will never be in the answer set we can remove it and then the next one is in this case two then we know that two can be a passive answer so now the number has two and eleven um and then the next one is five and we know that in this case two can no longer be an answer ever again so we put in five right um given same thing for eight um because we know that five can never be an answer again here there's six so because six is a possible answer you put it in front and then lastly this is a 10 so we know that 6 can never be an answer and neither can eight so then we replace it by 10. um of course this is the last element so we don't really use it but that's basically the idea behind the queue is that you give yourself a candidate list of answers at every step of the way that are all the possible answers that you can use and the other part is of course looking at the next um how many numbers can you actually see from here right so let's say you have this and you have oops six eight and eleven well if your number is seven you can you cannot see past the eight because of the definition of the problem that's actually something that i actually struggled with when i was implementing this but between seven to eight um so then the short answer here is that you just binary search for the number of people for a number of numbers that are smaller than seven which of course is just a standard binary search to the left of the number that you know your binary searching off so that's basically what i did here um it's a very freeze these 16 lines of code i keep a sorted list so you can actually use like i said an array and a model queue um or you use a queue and it just pops up off the front to maintain that invariant we have a list of possible answers again we reverse the list first so that if we're going from right to left just a little bit easier on the writing and then for each height we do a binary search to kind of see from the other possible candidate set and we add one unless um it goes beyond the length of the list because that means that where we can see everybody and you're not yeah and that's just to handle the edge cases you can kind of walk that through here this is what we do to maintain the variant of the model cue by keep on removing smaller elements because smaller elements than the current h are always going to be in the front because this is assorted less um i mean actually just i mean yes i use a sword in this but this is a mono key right i don't know why i did it this way now that i think about it um but i think during the contest i just didn't want to think about it um in case i needed to sort by another index um and this is actually very confusing now do i think about it but um but anyway so this is always gonna be in the beginning of the list and then you can remove it um if it gets if it's smaller because as we said you can't see over because in future elements going from right to left you can no longer see over this person right which is the current age so it's always going to you know so we move it from the candidate set and then at the end we add h to the candidate set again this is already sorted um so this is actually really confusing probably so you can actually if i'm doing it right now again the reason why you know i did it this way was because during the contest i just needed a data structure and i wanted to get as quickly as possible so some code is going to be a little bit weird a little bit yucky but yeah so you can imagine you do something like this instead and then here we just so something like that should be the answer and anyway because we're going from right to left the answer is going to be in reverse order so we just reverse it back uh that's what it will crack just to make sure my changes are okay before i showcase them so i think it seems like i'm getting some kind of lag or whatever or whoops this is now cubes okay well we went into some technical difficulties but this should be good uh aside okay well done technical difficulties oh there we go sorry friends uh i you know feel free to fast forward or watching 2x but this pending is so slow okay but in any case that's basically the idea um even though we do use a cue from sorted list we don't actually gain any performance which is why it doesn't really matter as much um watch me regret that if the tre is after the contest but this binary search is the one that has all the you know like for each element we do one binary search so it's going to be log n in the worst case and yeah and this is basically log n so this entire thing is going to be n log n um we do use of and space linear space because we use the dag we reverse the heights which is maybe dubious when we also need it for the answer so that's gonna be the lower power output sensitive um but yeah this is the format i feel like this is a different format but in any case yeah so that should be good and yeah um that's why i have with this one you can watch myself and live during the contest next silly mystic okay to the white one two four okay and there's something big guys soon like i've seen this one but i don't remember off my head do it backwards five some kind of cube he could see two where's the longest decreasing sequence right so ending in whatever start done oh the heights are unique that's what i'm looking at it's the longest no that's not right this is not right okay think about it's so slow come on that's good c there's like a mono queue actually i think okay um it's like an inch oh that's not good wait why is this other this is four what is this two oh yeah i might have misunderstood the problem why can't this person see three and ten if everyone in between bothered which one more formally misunderstood some small parts of it okay so here you see one instead of two okay actually misunderstood this one until this one i think i'm an if statement alright but i have to be trying to be careful let's that's today want to binary search to the okay maybe plus one is this right i mean that's the right hands with it let's give it a go okay cool uh yeah thanks for watching uh hit the like button to subscribe and join me on discord let me know what you think about this problem uh yeah i hope you do well and stay good stay cool i will see you later bye | Number of Visible People in a Queue | truncate-sentence | There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person.
A person can **see** another person to their right in the queue if everybody in between is **shorter** than both of them. More formally, the `ith` person can see the `jth` person if `i < j` and `min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1])`.
Return _an array_ `answer` _of length_ `n` _where_ `answer[i]` _is the **number of people** the_ `ith` _person can **see** to their right in the queue_.
**Example 1:**
**Input:** heights = \[10,6,8,5,11,9\]
**Output:** \[3,1,2,1,1,0\]
**Explanation:**
Person 0 can see person 1, 2, and 4.
Person 1 can see person 2.
Person 2 can see person 3 and 4.
Person 3 can see person 4.
Person 4 can see person 5.
Person 5 can see no one since nobody is to the right of them.
**Example 2:**
**Input:** heights = \[5,1,2,3,10\]
**Output:** \[4,1,1,1,0\]
**Constraints:**
* `n == heights.length`
* `1 <= n <= 105`
* `1 <= heights[i] <= 105`
* All the values of `heights` are **unique**. | It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence | Array,String | Easy | null |
52 | Hello Friends Today I Will Discuss The Problem Latest Thing She Has Been Walking Officer Important Problem Skin Allotment Reviews And Its Very Standard Tractor Key Problem Subject And College Sandwich This Problem List Ko Play List Ko *Wed And Subscribe Problem Placid For *Wed And Subscribe Problem Placid For *Wed And Subscribe Problem Placid For Below Subscribe to Channel Pim Schm ID Enter Tags and Author Any Rate Part of Another Any Vacancy Oye Give Winners Name Qualification for and Transparent Subscribe to Like Subscribe and Subscribe Subscription Daily Salary and Second Problem It's Just Save It's But Only Numbers subscribe The Video then subscribe to the Page if you liked The Video then subscribe to subscribe this Video Subscribe Bluetooth ko subscribe hai aur ke adhishwar total number of aur ke adhishwar total no. Possibilities Till Total Possible Configurations Motherboard Classes Only One Cute And Rest Of The Malefic Planet User Name Tips Object Total Amount Configurations It's So What We Can Do In Very Nice Day All Possible Efforts And Not Weather For Every Possible Way Subscribe to the Page if you liked The Video then subscribe to The Amazing The The The Police Was Not Sleep In c4d Possible Combination Can We Torch Light Band Gurjar One Fool Affair Ok One In Hai And 120 Dars Can See Naukri Minute Aap Idhar And Naukri Naseem Line For The Same Like This Is The Fish That Me Scientist Someone Near Jaipur Heritage St Missile A Rich Vikram Nehra Fit Less Whose Mayor Is A Message Less Now Displayed In About This Point In Stadium And 713 So This Thank You Tube Light Pass Na And Ex-Husband Blake Tube Light Pass Na And Ex-Husband Blake Tube Light Pass Na And Ex-Husband Blake Influential Side Meeting NOTE REQUIRED ELECTION THREE YEARS HOW TO CHECK THAT COD Possibilities for all the conditions in which lack of protective hui are few were not with lots of chatting laptop take a pen don't forget to subscribe convention fans and subscribe to invest vacancy every rule Has only one key officer every one can do apk file ok and every place in every to the giver is i office for this construction welcome to k this is one left android select1 kyun hai langot dekho a tripod accused arrested at intersect with a use you List So Lets You Were Born From Top To Bottom And You Have No Clue Of This Placement Can They Not Assume Please Share If You Dare Video Please subscribe and subscirbe Ghrano 202 Data Printed Why Is This Cycle Pressure Absolutely Citizenship Secure To Connect With Secretary Advocate Operation Because it is difficult to say that this show Naagin Ek St Another In The Reason Why Have Discovered The World Order Shall Give And Last Mein Joint Subscribe Notification Aa Ek Takes Delight And Wood Us Point To That Point Dashe 29 This Is It Ko Notice People Sudda Decorating Means Years For Every Possible Combinations Of Pleasure Cute Hair Day This Is My Current Status Of Different States In Which Aim Of Places Have Two Options Where To Receive New Updates Points Notification Festival Function And Tagged With Fresh Water Of Ganges Next You Will Not Take Of modern explanation places in the voice of water in this pot another point of wood craft flower pot with respect is but if you find out the noble possibilities affidavit that Bigg Boss Sanjeev verification sum tractor-trolley to fluid verification sum tractor-trolley to fluid verification sum tractor-trolley to fluid Vikram's code name Delhi to So of computers for solving the problem was doing for M.Com subscribe The Channel [ doing for M.Com subscribe The Channel [ doing for M.Com subscribe The Channel subscribe Video to that surgical G to that digestive calls its function with astro turf helper function so activities like decorating for 100 greatest function specific health me all equal one He Seen All The Videos Indian Places In All The Function More Down Verbs Condition And Condition With Facebook And Twitter Function Which Gives Away And They Will Only To This Particular State When That I Have One My Control Of Taking Place Roll Number 21 Roll Number Gautam And Styles of this is the president of 20123 but the president school that is my rule number 6 youthful-smeared in these that is my rule number 6 youthful-smeared in these that is my rule number 6 youthful-smeared in these types of the board and starting roll number strong so roll number twenty one to can replicate I don't my post workout state witch reduced in the Answer Letter Shanti Jab Answers To Record Operation Inside Content Functions Are Visitors Know What Is This Is Not The Final Ronit Roy Doob Electronic To Play The Giver Jis Pot Drop Back To Back subscribe The Amazing Possibilities Of Places Of Tourist Places Point Mera Tab Jet Itna Pressure Why At This Point Weather Please Give A Bird Conservation Below Suhaag I Am Megha This Platform Should Know Her Place Tube Egg Roll Number Make This Dress Long And Make This Mark Long I Android Phone Number Christian Place Acute Stupid Roll Number Of A Point Where Did Not Dare Devil Please Why Am I A Position In This Champion That Pimple Board Updater School In The Gautam Liye Qualification Ahead With Increment Of The Roll Number Acid Sodium Explain The Clue Of This Point At Which Involves Valid Point And Developed And International And Over Deposit And Withdrawal from the diverse remove this point hundred yards from the ground arrest developing that in all the best wedding function I have two options weather of candidates for details have suicide dates have one standard rise other state fennel can't keep track of beasts the water of leaders I just Very This Point Se Below Update 18 In The Global Board After Reading This And Research Scholars And Subscribe Our Distinct On Hai But Is Adol What This Point Is Point Dual Remove Difficult Points Will Be Decided Not To Forward Bases Of Can Make To Functions In Wave Function IN WITCH IS UPDATED व्याजन अन्धो के पास UPDATED व्याजन अन्धो के पास UPDATED व्याजन अन्धो के पास निफिटाशन डिस्टन for the best status निफिटाशन डिस्टन for the best status निफिटाशन डिस्टन for the best status जरा कैन मेक टू फ़क्टिन्स इन टे ब्रिटिश रूल जरा कैन मेक टू फ़क्टिन्स इन टे ब्रिटिश रूल जरा कैन मेक टू फ़क्टिन्स इन टे ब्रिटिश रूल एंड सुसक्रिबे करें और subscribe to the एंड सुसक्रिबे करें और subscribe to the एंड सुसक्रिबे करें और subscribe to the Page if you liked The Video then subscribe to subscribe our Channel and subscribe the Channel Please subscribe and subscribe A unique reserved for improving election function is the main function for this program which is added with the giver point placid in the middle on the giver day and subscribe The Video then subscribe to the Page if you liked The Video then subscribe to Aam Aadmi Party Or Weather Effect Play Circular In This Particular Point But It Will Not Help But Still Know If You Don't Allow Any Place Know What Were Displaced 900 To 1000 subscribe to the Page if you liked The Video then subscribe to The Amazing That Know How To Do The Time So Let's Get Angry With This Point Solid Consider The Boy Thought For A Disagreement This Point To Three Four 2012 Withdraw From Giving Any Point Distic And Contacts From This Point Se [ __ ] Contacts From This Point Se [ __ ] Contacts From This Point Se [ __ ] Romantic He Bigg Boss Interested Late Induction Intermediate Students And Tourists For Interactions Key Problem top-left bottom right What do I can increment from Problem top-left bottom right What do I can increment from Problem top-left bottom right What do I can increment from middle and houses in the valley and only increment decoration mru classes meeting me row and column and I soft positive row plus one officer revenue video number 151 number roll number of verses in the mother Subscribe Gautam M.Com Diner Dash in the mother Subscribe Gautam M.Com Diner Dash in the mother Subscribe Gautam M.Com Diner Dash 11058 Doing For It's Going Downhill Hai Nehru Inter School Quiz That 1004 Points In The Tags Us Dashrath And Leadership Incident Road Side Romance Equal Amounts To A Girl For Details About Upcoming Events In The World That No Hawaii Issue of human in these directions state agricultural development judge justice ganguly this in preventing mothers romantic this lineage agreement in alwar distic in this way same thing in life and death and same thing for electronic producers setting of this country wide and creating apps and widening and Avoid any time subscribe and subscribe the Channel according to this platform ignore chocolate syrup code in description android by old marathi 1955 use the best for a small industry and the economies from amazon love scene code once indore and joining and this is the answer is Active and storing and force it indore holkar stadium meanwhile condition when everyone sequence has roll number option l pushparaj patel function in this toys and returned to give the volume to do subscribe videos om shree nandishwar your funds collected and key good bye | N-Queens II | n-queens-ii | The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_.
**Example 1:**
**Input:** n = 4
**Output:** 2
**Explanation:** There are two distinct solutions to the 4-queens puzzle as shown.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 9` | null | Backtracking | Hard | 51 |
129 | hello guys um I want to solve with you lead code problem number 129 some route to leave numbers now I think this problem is a very good problem for someone who is maybe starting out with the binary trees or trees in general because it's very straightforward it's basically all about um tree traversal how do we Traverse a tree there are plenty of ways and yeah let's dive straight into it right so maybe let's start off by talking about what the problem actually expects of us right what are we meant to do so you are given a binary tree and each of the nodes in the Bible new tree has a value that is between 0 and 9. so we know each of the nodes has a one-digit integer of the nodes has a one-digit integer of the nodes has a one-digit integer basically so now what we are meant to do is Traverse each branch of this tree right so in this case we would have three branches just like these and basically combine the numbers that we find in each note of each branch right so if we apply this to this example basically we start off with this Branch right here so we are given the numbers 4 from this node 9 from this node and 5 from this node now we know to stop on this node because this node is a leaf node right if we were to extend the tree here we see there are no other nodes it has no children basically therefore this is a leaf node okay and we know the branch is ending here now if we go over to the next Branch right we are again we can have a four we have another 9 right so this is this branch is identical so far and now we have a 1 at the end right our Leaf node of this branch is a one and you can see where this is going right so this was this branch and now if we do the final branch of this one right we are again given A4 and we then have a zero right it's this Branch so we have a 40. now um if we add this together right now let's let me do some quick math here okay so this is a six and then we have a two here and the Two Carries over so if my math is so let me just make this more clear if my math is correct which would be pretty embarrassing if it isn't we get 1026 from this example right this is the number we are meant to return so we Traverse every Branch we add the numbers together now we don't add them in a mathematical sense but we rather we append the numbers right and then we add all of the numbers that we get from every single Branch together and the result we return okay now let me clear this up how do we go about this problem okay now the easiest way in my opinion um there are several ways to do this the easiest way is probably a depth first search short it's um or for short it's DFS so how does DFS work it is basically the exact same principle that I just threw out so DFS is a algorithm that is used for tree traversal or graph traversal and it's basically exploring each branch at a time until you hit a leaf node so we start out on the Roots just like um just like I've shown you before so we start off here on four and then we go down a level right now we're on the nine and we keep going down right we keep going down we keep exploring this Branch right here until we hit a leaf node again a leaf node is a node with no children right both of the left and right property of this node 0.2 null right therefore this is a leaf 0.2 null right therefore this is a leaf 0.2 null right therefore this is a leaf node and now our algorithm our DFS is done with this iteration basically this branches is explored and now we backtrack up to this one right because this still has some work left to do and we keep exploring the next Branch right which would be this one now this is our base case right here right because we have again a leaf node that has no children right so this is what we call a base case that I just mentioned and we keep going back up we backtrack all the way to our root node and we go down here and we have our final base case here okay the zero so this is how the DFS the depth first search algorithm basically works and you can implement it recursively you can implement it iteratively and I'm going to go for a recursive solution in this video maybe another thing worth mentioning here is how do we combine the numbers right because like I said we are not adding these together right because if we just edit each value together of each branch for this Branch right here we would get the value 9 plus 4 is 13 plus 5 is 18 and this is obviously not what we want right we want 495 and not 18. there are two different ways to do this um one is a little more intuitive in my opinion and I think both are perfectly fine to do because they are equally performant I think um so one way is to basically turn each number into a string right so every value we turn into a string then we append the string right with the other numbers and then when we hit the base case we turn it back into an integer and we add it to our result right so we will turn this into a string then we would append nine then we would append five and here when we're on our base case we turn it back into an INT right this is one way to do it another well more mathematical way to do it I guess is to multiply the value 2 by multiply the number by 10 on every level we would have four times ten is 40. then here we have 40 plus we add the value of our node right so if 49 we take this times 10 again we have 490 right 490 goes down here and we add 5 to this right so we have 495 so on every level we take the number that we're building up we take it times 10 before we add the value of the corresponding node to it now you know feel free to do it either way I'm going to do it the string based way because I think it's a little more intuitive to do and yeah I think this is basically the conclusion for this concludes the blackboards part of the video and yeah we can get to the coding part okay so now let's actually work on implementing the solution um I'm going to use JavaScript for this and yeah let's just write the code what I'm going to do first is I'm going to check for an edge case right now maybe as a little disclaimer this is not going to be the most concise solution this is going to be a little bit verbose because I think it's easier to understand but again it's going to be the most optimal or like shortest solution out there okay so I'm gonna look out for an edge case because if we look here to the constraints and we can see the number of nodes in the tree that we are given is going to be between 1 and 1000 okay so it is a possibility that we only get a tree with a single node okay and if it's only one node right then we can just straight up return the value of that node okay we don't need to do any DFS we don't need to add anything together because there is nothing to add right we have no branches to explore we have nothing to add so let's just um code this out so essentially we can just check is the left child of the root going to be null and is the right side of the root gonna be null and if so just return the value of the root right and this is going to be our little Edge case here and then we can just initialize the result variable okay this is where we are going to start the result that we will end up returning and now let's actually get to the DFS part okay so our DFS function um we're going to implement recursively like I said and it's going to take to um or it has two parameters okay so it has node and let's call it number okay so node some people call this curve or current okay this is just going to be the note that we pass in right the node we're currently looking at and number is going to be the number that we are building up on each branch okay and again this is going to be a string for us right we are only going to turn this back into an integer when we hit the base case so let's first do this right I basically want to add to the number this is basically building up the number right so we want to look at the node and return a string of the value of that node right so we're turning the digit into a string and we're appending it onto the number okay and now let's actually check for our base case here oops okay so this is our base case right this is essentially what I showed you on the Blackboard and we are checking if we are currently looking at a leaf node right a leaf node is any node that doesn't have any children right so we are checking is the dot left property of our current null so it doesn't have a left child and is the dot write property of our node that we're currently looking at null okay and if that is the case what we want to do is we want to at the number that we have computed right this number that is currently a string we want to add it to our result okay so we are just going to call pass ins right converting it back into a number into an integer on our num okay and then we can just return out of our DFS right here because we are done exploring this branch okay and now we are going to do our recursive calls so we're going to check is the left child not node so does our node have a left child okay then we are going to call DFS on that left child okay call um colored with a note dot left so for the left child and pass it in the number we're currently building up remember this is the number that we are building along exploring the branch basically and we're just going to do the same for the right child right so just like this so these are our two recursive chords okay and now all that's really left to do is we just have to start our recursion right so we have to initially call it and we need to do a little check here again this is not the most concise solution but it is pretty efficient nonetheless so we are going to check does our route have a left child so is root dot left not equals to null then we are going to call um DFS on the left chart of the root and we have to um because we are building up a string we have to take the root value and turn it into a string and now we will do the same for the right child here we place this with the right and then at the very end after we're done exploring the whole binary tree we just need to return result okay and let's submit see if it works fingers crossed and it does work | Sum Root to Leaf Numbers | sum-root-to-leaf-numbers | You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`. | null | Tree,Depth-First Search,Binary Tree | Medium | 112,124,1030 |
449 | hey everybody this is larry this is day 9 of the october eco dairy challenge i hit the like button to subscribe and join me on discord uh my setup is a little bit different today let me know how that comes out uh we'll see okay let's go serialize and de-civilize bst for serialize and de-civilize bst for serialize and de-civilize bst for today's farm uh so we're trying to serialize it uh a binary search tree okay uh it has to be described as the original tree structure okay let me think about this for a second i am solving this live so you know this is not just an explanation video it's about um you know me going for my thought process and i haven't i don't have an immediate idea on this so maybe uh it could go in a couple directions so i would say uh my first impression would be to do um a sort of uh i mean i don't i'm trying to think about whether i can take advantage of the fact that it's a search tree uh because i think just the fact that it's binary tree we could do a thing where you know you just keep on uh where to pre-order uh where to pre-order uh where to pre-order uh pre-order traversal and then you just pre-order traversal and then you just pre-order traversal and then you just you know maybe use the o of n space will be two times n where uh yeah where you know uh two times and space which is off and space uh in linear time probably um but can we do better knowing that is search or like that is a binary search tree can we take advantage of the fact that uh i mean i think maybe let's uh i think for in general a lot of things i would like to do is get the right answer first and from that we could kind of make incremental uh price you know improvements to see if they work right uh so i'm going to do that and i think that works also in theory i mean i know that a lot of people nowadays are used to lead code and other online judges where you know they submit it and they already have a lot of test cases for you right but let's say like you know let's say for whatever reason you're you don't have internet and there's no test cases and you're just doing it for yourself well if you write a maybe like a sub optimal solution then you that you know is correct that you can prove is correct maybe uh that you could show that is correct then you know you could optimize off that by comparing the uh the answers or just um yeah compare the answers between the two solutions right so those are things that uh i think probably gets lost a little bit but does come in play a little bit on interviews because these are things that you could chat about with respect to code quality and stuff like that but okay so uh yeah so i think we return the string is okay so i'm gonna hmm yeah i'm just gonna i think i'm gonna do a pre-order traversal like i said a pre-order traversal like i said a pre-order traversal like i said and then i'm gonna basically have a common limited a delimited list of the elements based on that pre-order traversal pre-order traversal pre-order traversal so okay so let's just say um array is you could uh maybe a little better name uh traversal maybe is to go to the arraylist and then we have you know a classic that first search uh but let's just call it pre-order uh but let's just call it pre-order uh but let's just call it pre-order uh with the node if node is none we return but we want to let's just uh traversal dot append uh since no values are from 0 to 10 to the negative 4 we could use a negative 1 as a center value i was going to put a string or something but otherwise um yeah it should be okay um i actually was also thinking about maybe doing it in um in another way which is uh which is level ordered which yeah it's okay i mean i don't think it matters that much i think as long as you're consistent it should be okay uh but yeah let's do uh left pre-order no doubt right uh left pre-order no doubt right uh left pre-order no doubt right i think that should be good enough so now we uh yeah and then now we just could convert this to a string by return to do a comma uh dot join traversal right uh and i don't know of how this testing works so maybe this does something maybe it doesn't uh because okay i was hoping that would at least print this out but maybe we could okay just for debugging right so let's just print okay and then we turn k right well now we're not debugging in this case it'll be just visualization of uh we didn't actually do the pre-order okay pre-order okay pre-order okay i actually forget that sometimes but yeah now that we kick it off um oh in front yeah that's right i do okay i do use ants that is true uh yeah so now you get to see one two one and then you know negative one so you are going to use two times the number of space uh and most um because of the negative one values right or maybe three times the number of space uh because for each node it can have itself and at most two other uh empty nodes right uh so yeah so then this part looks good uh even if it's a little bit inefficient and then for these zero lights we just want to construct the node back from the pre-order from the pre-order from the pre-order and we can do that by let's call process pause maybe i don't know uh but let's first convert this from uh data that's split it by the comma and we map that back to an end so let's just say true let's go to this and then now we can pause uh hmm what do you want to pause um yeah maybe this price is okay i mean there are a couple ways to do this uh you could keep track of an index uh or you could i think the more pythonic thing is to convert use a key use a deck or a cue so i'm gonna do it that way uh but note that i think it technically is faster and more efficient you just keep an index and then you know you move as you go further away but i think this is more pythonic and that is more uh collections um more basically more uh how i want to express it right so then let's just return pause and what does pause to right pause just takes the first uh element um so kern is to go to traversal dot uh pop left and then yeah and then let's see tree node right uh so then we do tree node this is current value of current value right uh so then node or current node as you go to tree value uh current node dot left is equal to pause and current node.right that's pause and current node.right that's pause and current node.right that's gonna pause and then just return current node this is mostly done but not really i have to take care of the minus one case uh if current route is equal to negative one return none okay maybe that's it though let's see fingers crossed looks maybe good it doesn't really tell me let's do a few more though it's a little bit hard to write the input just because now we have to um now we have to make sure that it is a binary search tree right so you can just do this i don't think but i'm just going to see if it complains i'm just going to submit it yeah okay i'm just going to submit it because i'm a little bit lazy uh to do it at least in this interface right because we could have win tests in a different way and i think that would have been okay but um yeah let's do oh i think this one's more oops so this looks okay i mean i'm not at this point technically i would have more confident if i try one big test case but you know like i said i'm just a little bit lazier because uh of the given test code format i think if you were to write tests you would construct these things uh from the tree notes right now we are more obvious what are you trying to construct um but yeah that's all i have uh so it's linear time linear space uh as i said each one each node can lead to most you know two other leaf notes uh because they'll be if you have um i mean you know you could do some math on the leaf notes and stuff like that it's i think it's technically two to the two times n sorry but it's still going to be linear no matter it's 2 times 3 times n uh as the bow uh and in terms of time well this is a pre-order and this is well this is a pre-order and this is well this is a pre-order and this is just a construct you know recursion with uh getting one element at a time so it's going to be a linear time for both cases uh that's all i have let me know what you think uh sorry if this isn't my usual setup uh but you know hit the like button hit the subscribe button drop me a discord and i will see y'all tomorrow bye | Serialize and Deserialize BST | serialize-and-deserialize-bst | Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a **binary search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.
**The encoded string should be as compact as possible.**
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `0 <= Node.val <= 104`
* The input tree is **guaranteed** to be a binary search tree. | null | String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Search Tree,Binary Tree | Medium | 297,652,765 |
231 | hey everybody welcome back to another leak code problem 2 3 1 power of 2 this is an easy one given an integer n return true if it is a power of 2 otherwise it return false an integer n is a power of 2 if there exists an integer such that n is equal to 2 raised to power x n is equal to 2 raised to the power x yes so what is the power integer 1 becomes true because if 2 has the power 0 it will return 1 and 16 is a good example 2 power 4 is 16 and n power and n is 3 so 3 is not and in any case if we in any case we are not all numbers are out of list you can say because this is a table of two whenever we see a odd number we will say what is this is just makes no sense so what we will do is to solve this we can use bits bit of bit wise operators bit manipulation but that's pretty confusing and it is hard to work with bits so confusing to what i work with bets so we will be making a power variable and a counter will so whenever our power should be less than the number itself we know that you know that like just common sense our power will be for example if 2 has a power of 4 this is uh just for the sake of understanding then 4 is less than 16 4 should be less than 16 it is which it is and we have a counter and we will keep increasing our counter again and again by one until our power becomes equal to the um our you can say our power becomes equal to the number and hold it down like our power the product of power like this will be our power uh let's we will understand how things are working so like this if you have power 4 and 16 so if power becomes equal to n we will just stop okay and return true in another case if this is not possible then what we will do is just return out of the list and of our loop basically and say it is false so i think you guys understand how this works and now let's code it down so like i said we will be using a power uh variable which will assign one and uh power not power counters it will be our count one so while our power is less than nums itself or equal to if power is equal to n we are going to return true let me return true and in the else case what we will do is to raise to power our counter our count okay yeah this is good and our count we will keep increasing it by one again and again so this is it now if we make it out of the upper loop and we didn't return true then obviously we know we have something uh something odd going on here you can say and we will return false and this should work fine let's see if this works or not and if it works that will be good so yeah that's its work and the wi-fi is slow i think yes that's why the wi-fi is slow i think yes that's why the wi-fi is slow i think yes that's why it is taking so long so that's it yesterday | Power of Two | power-of-two | Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_.
An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`.
**Example 1:**
**Input:** n = 1
**Output:** true
**Explanation:** 20 = 1
**Example 2:**
**Input:** n = 16
**Output:** true
**Explanation:** 24 = 16
**Example 3:**
**Input:** n = 3
**Output:** false
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion? | null | Math,Bit Manipulation,Recursion | Easy | 191,326,342 |
238 | Hello friends, welcome to the channel, you are doing 90 days software engineering prep with me, this is lead code 75, question number seven, lead code 238, product of array, accept yourself, see what is the question, an array has been given to you, return a new array. What do you have to return at each spot? What do you have to return? For example, let me show you the question. So, if T is 3 4, 2 3 4, then the first spot address is what is returned. One. Product of everything else except 2 3 4 Product of everything else 1 3 4 in place of T If you don't understand then let me explain to you. Understand the question with me. Let's understand the question in terms of A B C D. Let us If you are given an array of a b cd then what you have to return is in place of a you know what to return is b the product of cd in place of b ad and the product of e in place of c ad and the product of e in place of d a c And the product of e instead of e is the product of a b c d. You have to return this. Is this a special thing said? You cannot use division, otherwise what would you have done? Product all, product all with that number. Division is not allowed, so how to do it. See what I will do. Look carefully. A B CD, I will make a. A prefix array means the product of the elements before that element. So there is one before A, otherwise the product. In one if only a is before b then if a and b are before c then their product is abc before d then their product is abcd before e then the product of all those before them in the prefix array Product I will create a suffix array in which the product of the subsequent ones is there is none after e. If there is none after e then one is after d then there is only e then e is after c then d and e then deed b is after cd then The product of CD is all the others after A, so see what is the product of CD. Now look carefully at what is lying below C. The product of a and b is lying in the prefix below C, meaning the product of the left ones and the suffix se is lying in The product of d and e is the product of the right ones. If I make a carry by doing the product of these two, then A and B will not come in it. The product of the left ones is the product of the right ones. You have missed it. Okay, did you understand the question? You must have understood the approach. I think O's approach is ok, now see how I will make it, how will I make it, see carefully, it is not difficult to make, it is easy, this question is, I have to make a prefix array for instance, I have to make a prefix array, you will see it being made, because before a, there is Now, at the zero spot, I will always put one. At the zero spot, I will always put one because there is no one before the zero. So these are their indices. 0 1 2 3 4 So at the zero spot, I will always put one here because there is no one before that. Now What will I put on one spot? Look, on one spot, I will pick the value of the array and I will pick the value of the prefix array and make the product of both a. Now what will I put on the 2nd spot. I will pick the value of the array. The value of the array is b. The value of the prefix array is a. I will do the product of these two. Now think and see why this is happening. Think and see why this is happening. What do I have to put here? So pick the value of the prefix array and pick the value of the array and do the product. Look at the prefix. The array contains the product of the ones before C and the array contains C, so if I product the first ones with C then it will be the product of the ones before D. So basically multiply AB with c and you will get A B. If you do n't understand this thing, then understand on e. See what the prefix array represents. When I am making the answer of e, I am saying, product this and this, you will get A B sequence, meaning the product of the first one. Will get why will get see picked up a c for e i what does it represent represents the ones before d it represents the ones before d picked up from the prefix array a b c represents the ones before d And picked up from the array d if I produce this place by this then the offcourse will become the prefix of e that is a b c d all right for the suffix we will do the same in the reverse direction if we make it reverse then we will put one on e and now the value of d will be like If you want to make a value of e then we will product it. E has become. If you want to make a value of c then produce d and e. If you want to make a value of b then produce c and d. If you want to make a value of a then product b and s. Okay, then there is nothing left. The final answer will be its product, make aa and give simple questions. If I code it with you, then make prefix aa, suffix aa. Let's start creating the prefix array. Prefix of zero will remain in one. Filling the array will start from aa eve. This is that in Names of Aave, there is N of Aa Mav but in the Price of Aave, the product before that is there, so if you convert it from zero to Aa Mav, then it will become the product of zero to Aa Mav. Which we have to put on prix aa, listen to the previous thing again carefully, now if we make the suffix, it will become upside down, then what is its last spot, the last spot is the length, it will take there and the loop will go upside down, so numbers dot length, oh re. Hey, the passing wind, tell me, will it do so much for me ? Go to my village, ? Go to my village, ? Go to my village, salute my friends, is that street in my village where my heart lives Ruba, so I feel that the code has worked and the performance is also good. Beats 100% So this was what performance is also good. Beats 100% So this was what performance is also good. Beats 100% So this was what question this was seventh from lead code 75 all right and 235 th 238 other wise so what will be my request to you there is a journal in the first link go to that journal and document your journey with me there But I do a lot of meditation etc. due to which the performance may or may not be good. Let's fight this day. Let's fight this dumb together. Let's try to win this together. Alright then see you in the next question. Thank you so much. Mach | Product of Array Except Self | product-of-array-except-self | Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`.
The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
You must write an algorithm that runs in `O(n)` time and without using the division operation.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[24,12,8,6\]
**Example 2:**
**Input:** nums = \[-1,1,0,-3,3\]
**Output:** \[0,0,9,0,0\]
**Constraints:**
* `2 <= nums.length <= 105`
* `-30 <= nums[i] <= 30`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
**Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.) | null | Array,Prefix Sum | Medium | 42,152,265,2267 |
473 | hi guys welcome to tech geek so today we are back with a really good challenge problem that's match62 square that's elite for medium 473 question and mostly asked and great companies like fang and not just this many product based companies go up with questions like this and basically this question that you will see it's repeating before beginning with the solution and the approach i'd like to request you all to please like share and follow the channel i even have an instagram page i have attached the link in the description box if case you have any queries you can reach out to me anywhere like even in telegram or on instagram i'll be there to help you out okay so let's see the question they are saying we have been given an array of math six okay that's an integer array and each matchstick i that's each element will depict the length of that particular math six okay you want to use all the math sticks to form one square so all of the given math sticks should be used such that they form a single square now you should not break any stick remember that you have to use it fully but you can link up such that like link up in the case you can see you have two match sticks so you have otherwise one so we can link up in this two okay return true if yeah each one of them should be used exactly once now no repetition is allowed you have to check return true if you can make the square and return false in the same way okay now let's see what solution or how we can approach to this problem okay let's see this we have been giving the very first example is one two and the very first thing is let's understand what the problem says so they are saying and now for this you know that yeah it would form a slope but if you talk about the square there's a basic condition you know that basic condition is that this sum if you talk about an integer r okay so if we have all the sides as integral values so the sum of these values should be a multiple of four so every array that is given to you the very first thing you have to do is find the sum that's very important and if some mod 4 that's if their remainder on division is not equal to 0 okay that means the answer is false why because if it's not an integral value if you sum up that means in no case you can come up with a solution now let's talk about this what is the sum here it's 8 and we know the sides length is equals to whatever is the sum divided by so that means each of the side is equals to two they are coming to each of the side is equal to two so what we could do is we could begin from this one okay now for this we need four ports let's see i'm taking these dots kind of for you can save both edges okay yeah no we have to join these uh join these vertices with an edge okay now very first is one and each of them is two so let's place it and let's begin from any one they forgot to vertically that's what again is one check one plus one is it equal to target or less than double if it's equal or less then place it here otherwise place it in another direction it's equal to the target so that means it will satisfy then comes 2 obviously this is finished let's take some other direction this is equals to target again are all the lines filled yes that means your square as possible right this was quite uh you can say easy format if you know like how to approach this topic but if you talk about some other approach in that case how things would go on this was quite easy one so you know so if you talk about any other problem the very first thing this and this these will follow right these are one of the most important things that you need to do so let's take some other example to it change these values a little and check whether they work or not okay that's what we need to check first okay let's take this as three four five okay so we have these values let's sum them very first six plus four ten fifteen twenty four so we have order 0 now coming to the length 24 divided by 4 okay the length is 24 sum 24 divided by 4 that will give us 6 so now each of the values should be we have to create it by 6 right now checking it in a solution like each of this side should be equal to 6 we have four sides so we will work accordingly we need to work for four sides so we need to check that the sum should come up in the same way right uh let's take the solution yeah that's right okay now you need to check for the solution like uh oh sorry that's one mistake i used four eight eleven forty that's fine yeah let's see how things could go on in the same way now this is how uh matchsticks are to be there okay let's continue up in some other way if you have the solution like this again these points are can three okay let's see this problem three four five so let's just take it we took three one here another three here okay this went down now you have four you placed four here again you have five you place five here you have four you place four here we still have two and one that means one five is still unusual but can we break it like this no we cannot okay why because that's what the point is that if we have to do we cannot break this part even if this was satisfied there was a condition that says that this can not be broken that's what just to be done i hope this is clear now how we'll go we'll take up all possibilities that means initially how we can begin with it how we can change and that's how we have to check like adding on this if it's less or less 10 on the ad and if not then continue to the next side okay let's look at the solution now the very first condition is check whether they are none length or zero that absolutely falls stick for the sum if someone is not zero that means it's not true take it sort the array return dfs now dfss we are checking how possibility and what's the target is actually the side here that's sum minus okay we'll uh check recursively which particular element could be taken that's how we check if it's greater than target or if they are equal then we continue if not then we act okay that means for this we are not going to consider if it's less that means we have to consider considering 10 checking for the other one and then still goes on so this is how the solution will go on if in case of any queries regarding the solution or anything please let us know we will be there to help you out and uh do let me know regarding any particular queries regarding any upcoming interview placements of oa or anything i'll be here to help you thank you | Matchsticks to Square | matchsticks-to-square | You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**.
Return `true` if you can make this square and `false` otherwise.
**Example 1:**
**Input:** matchsticks = \[1,1,2,2,2\]
**Output:** true
**Explanation:** You can form a square with length 2, one side of the square came two sticks with length 1.
**Example 2:**
**Input:** matchsticks = \[3,3,3,3,4\]
**Output:** false
**Explanation:** You cannot find a way to form a square with all the matchsticks.
**Constraints:**
* `1 <= matchsticks.length <= 15`
* `1 <= matchsticks[i] <= 108` | Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this. We don't really need to keep track of which matchsticks belong to a particular side during recursion. We just need to keep track of the length of each of the 4 sides. When all matchsticks have been used we simply need to see the length of all 4 sides. If they're equal, we have a square on our hands! | Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask | Medium | null |