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
960
problem 962 the columns to make sorted3 okay so let's go through the problem description first we are given an array a of n lowercase letter strings all of the same length now we may choose any set of deletion indices and for each string we delete all the characters in those indices so for example if we have an array a which is made up of these two strings and the deletion indices are 0 1 & 4 then we basically delete the & 4 then we basically delete the & 4 then we basically delete the characters at these 3 indices in every single string in the array okay and the final array has every element in that graphic order so basically problem says that we want to delete characters so I if we visualize this array as a matrix so like there each string each individual string is a row of the matrix then we can actually visualize columns which can be deleted from this matrix so what the problem says is that you can actually select column indices that you are going to delete such that every row is gonna be sorted in the end after you're done deleting these indices so yeah so that's what the problem says so they also have so okay for clarity is you know isn't that so graphic order if this okay yeah so like the equals are also graphically it's possible so like you can have a string like a BB and this would be considered lexicographically sorted and if you returned minimum value of TR length or we have to return the minimum number of deletions for which this is possible okay so I think the problem statement is clear the problem immediately it's not very clear how to approach this but I insist on actually breaking the problem down so the best way of breaking this problem down is to think in terms of one string so like forget about this other one let's say that butan they had this one string so if we add sponsoring and we will allow to delete some characters and we had to make the strings such that the remaining characters are in that so graphic order how would you go out in that so like one approach that comes to my mind is that so you run a loop on this ring you go through every character so let's say that you approach this see in your loop I would then check all the characters before see considering each one to be the last character before see so for example let's say that I read at a so like I'm considered in my outer loop I'm considering see I go back I am now at a I would assume that all the characters between a and C have been do so you can easily come to indices of CNA you can easily compute the number of characters that have been deleted and then all you have to do is actually make this string sorted so like this immediately like rings dynamic programming in my mind so like even like okay so that's let's go to enemy programming once we have settled on our recursive solution so for every character all you have to do is go back each character that comes before it and consider it as the last character before it so like deleting all the essentially deleting all the characters between the character under consideration and the character that we got from going back so I think that should be easy enough to do but then now we have to scale the solution to multiple rows but that isn't a problem right because I think the constraint so you're looking you can look at the constraints they're not very strong so what we can do is that we can actually select this problem has two sort of logics right so when you go back and let's say that for this see if you or rather let's say for this a when you go back and find this B there is no possible scenario in which this would give a lexicographically sorted string right so the answer will be minus one now this check or rather like this check whether or not this configuration is possible right now we could just do it in one line because it was one string but now let's say we have n strings so we can write a separate check function which or what it will do is it will go row by row and it will compare the columns that you give it and it's going to make sure that you are actually able to use this configuration or every let's say like if I call the character at index A to B I and the character at index then index before it to be J and basically it will go through every row and check that the character IJ is less than character at I or equal because if it's greater then it's not possible so they give in any one of the strings it's greater we actually can't use this configuration so this won't be a part of subproblems that actually make up the solution for that particular I so I hope that makes the problem clear enough gain more clarity once I start coding so let's get to coding you first things first if a relent is zero we return zero fig is nothing to delete then we declare our DPA and after realizing that we'll need the length of the strings repeatedly we assign that to a variable n the length of the DP array and then just beyond under the loops you want to iterate over our elements left to right starting at index one in the RFP the interview goes from I minus 1 to 0 we also want to initialize the DPL do at index I with I because in the worst case we may end up deleting all the nicest before I so the DB value can be more than that now we check if it's possible to make a solution which chairs the preceding column 2 I we update our DB values if I minus J plus 1 plus T PJ is actually lower than the current value here I minus J plus 1 are the number of deletions between I and J while TP j is the minimum cost to make the string sorted from 0 to J now we can compute the answer by simply iterating over our DP array and considering I as our last element the total cost is then the DP value at I plus the length of the rest of the string which we would have to delete to make I the last column finally check function all we need to do is to go through every string and compare the characters at I and J we return false if the character at J is greater than the character at i for any of the strings you can return true otherwise and there you have it folks 96% and there you have it folks 96% and there you have it folks 96% optimality that's it for this one please trouble like if you like this dislike if you disliked this and as always subscribe for more thank you bye
Delete Columns to Make Sorted III
minimize-malware-spread
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`. Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`. **Example 1:** **Input:** strs = \[ "babca ", "bbazb "\] **Output:** 3 **Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\]. Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]). Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order. **Example 2:** **Input:** strs = \[ "edcba "\] **Output:** 4 **Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted. **Example 3:** **Input:** strs = \[ "ghi ", "def ", "abc "\] **Output:** 0 **Explanation:** All rows are already lexicographically sorted. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 100` * `strs[i]` consists of lowercase English letters.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Hard
null
1,621
well I leave code every day never take no Hiatus this is number of sets of K non-overlapping line segments non-overlapping line segments non-overlapping line segments okay let's go ahead and get right into this problem so given endpoints on a 1D plane where the ith point from 0 to n minus 1 is at k x equals I find the number of ways we can draw exactly K non-overlapping line segments such that non-overlapping line segments such that non-overlapping line segments such that each segment covers two or more points the endpoints of each segment must have integral coordinates okay so you have to place lines at integer points right you can't place a line at 2.5 and 3.5 right it has to be line at 2.5 and 3.5 right it has to be line at 2.5 and 3.5 right it has to be on two or three right it has to be the ends of the line have to be placed on integer points the K line segments do not have to cover all endpoints okay so there can be gaps in the space that you fill and they are allowed to share endpoints right so if you had one line that went from two to three you could have another line that went from three to four so they can share endpoints but they can't overlap right you can't have a line from two to four and three to five right because there would be overlap there but you could have two to three and three to four if they share an endpoint that doesn't mean they overlap yeah return the number of ways we can draw K non-overlapping line segments and draw K non-overlapping line segments and draw K non-overlapping line segments and since this number can be huge we're going to return it modulo 10 to the 9 plus 7. okay so a little confusing if we looked at this example here and then so we have four points I guess you could call it four points in the system uh what just happened okay we have four points in our system so I'm going to draw that system like this so you could draw a line to three and four so this is our one dimensional plane where we can put our strings or we call them strings here segments all right I might use the term strings interchangeably right but you have these line segments well if the dimension is four well I could put a line here that's one way I could do it right I have to put k equals two lines right because we have k equals two so I could put a line here and a line here that's one way I could do it I could put a line of this link here and then another line of this of length one here I could do the opposite right I could put a line oh no I couldn't do that what else could I do there's five ways of doing this okay I could put a line here and finally I could put a line here and here right so these are all five numerable ways right so this is two lines right so there's a line here segment and another line segment here two line segments on their own note that you know there can be a gap we don't have to cover the whole Space just for this size four space these are all you know this enumerates all possible placements okay so how do you approach this problem efficiently well I guess what led me to the solution first was thinking about in this line segment system right I can place if I have two lines I need to place right I can place the first line like this and then for the remainder of the system I have to put one line here I could place the line like this and then for the remainder of the system I could put one line here or I could place the line like this and then for the remainder of the system I'd have one line here so what I'm basically saying is like for any system right if this thing is length n so let's draw it out so we have this space right just in a general case what I'm basically saying is we have this space which is length n right and I have to place K lines so I have to place K lines in this n space well what are my options well I could put a line of length one here which means that I'm going to have to place K minus one lines here in this Dimension here there's something wrong with my iPad charge unfortunately right and I guess even more generally I have to do K minus one lines here using what using n minus one space why well because I create a line that's length one here so then I have K minus one lines remaining and I have to use n minus one space to do it okay I could also put a line of length two but that means now that I need to put K minus one lines using n minus 2 space or I could do something of length three but that would mean that I'd have to place K minus one lines using n minus three space and I can keep going down until I get to the very end using all end space and not have to place K minus one lines using n minus n space so I can for any point I can draw a line like for any close four here and I could draw a line that covers almost all the space you know I can draw a line that covers all the space I can call a draw line that covers this much and this much so and then I would just have to fulfill the remainder of the solutions for what's left over okay which makes sense right because I can place a line and then since I placed that line I now have K minus one lines I still have to consider and then for those K minus one lines I have n minus the size of the line that I've decided to use left to fill that space okay um now there's one more thing I can do right I don't actually have to fill up all the space so what I can also do is not fill up the space at all and fill up K lines using n minus one space right so either I use a line so I have K minus 1 lines left and since this line has length one I have n minus one space left to fill it up I could use a line that's length two so I have K minus one lines left that I have to place using n minus two space n minus three minus four all the way up to n or I can decide that I don't want to put a line here and I can just use K lines to fill up n minus one space and that will you know create the space you see in this example right like in the beginning I can do a line of length one and then these are the ways that I can do a lot where I use one line here in this system or I can decide to skip this space and not use it at all and distribute my K minus my K lines with n my in N minus one space right because here n equals four so I'm Distributing all my two lines in n equals four but I can decide I won't use this space so how many ways can I distribute a line in and minus one space how many ways can I distribute two lines k equals two lines and N minus one space hopefully that makes sense so that's the idea here so how do we generalize this idea well let's just say that I have this dynamic programming array n right and I say how many ways can I using K lines let's actually make this a different color make it red so how many ways using K lines can I distribute those lines into n space well I can distribute the line of length one right so I can use this line here right I can distribute this line here which basically means well I'm going to create a line of length one which will remove one spot one space from the total space right because when I use this one space I've allocated it so I have n minus one space available left and since I've used the line well I can use D of K minus one because I've used a line and that line uses space one so I have n minus 1 space left plus well I could use a line of length two and I get n minus 2 space left plus d of K minus three so I can use a line of length or sorry guys I messed up here no matter what I'm using only one line and that I could use a line that has length two I'm using one line and that line has length three all the way up to what well I can't use a line that exceeds the space that I have so the maximum line I could use in this example would be DK minus one n minus n right so these are the links of all the lines I can use so I'm basically saying if I have K lines well I could distribute one line and I can make that line length one I can distribute one line make that line link two I distribute a line make that line link three all the way up to n right because the line can't exceed the size of the space that I'm using and that will give me the total number of ways that I can distribute this system right because what's basically happening is I distribute a line of length one and then my question just becomes well if I distribute a line of length one how many ways can I distribute a line of a lines how many ways can that should be K minus one lines with n min n minus one space so that's basically the idea here so if I distribute a line of link two well I can do that and then I would just have to figure out how many ways can I distribute K minus one lines using n minus two space since I've just used two space here right now we just saw that recurrence relationship for this problem as well um this is more stated in our tabular recurrence relationship you could use mobilization for this as well right which might be a little bit simpler but as we go through this problem further we'll figure out that there's a optimization to make this even more efficient okay so that's all the ways that I could distribute a line right these are all the ways that I could distribute one line and these are all the links that I could use okay now the final way I can do it that's not articulated here is I can also decide that I don't want to use this space for anything so this is kind of like the outlier right this is basically saying okay I'll just distribute okay I'll use K lines and N minus one space I won't use the space for anything I'll leave this space empty so the number of ways that I can distribute K lines covering n space is the same as the number of ways that I can distribute K minus one lines to M minus one space if I decide to use a line of length one I can use the link line of link two link three all the way up to n or I can decide to not use this space so I can also add in the number of ways that I can distribute K lines to n minus one space okay now if you want to use a little bit of a mathematical notation to kind of simplify the way that this works a little bit we can call this the sum from I equals 1 to n of d k minus one n minus I right so that addresses this sum here because the sum has a very natural progression Plus so this is one term on its own D of K of n minus 1. so this basically saying is all the ways that I can distribute one line and its length plus not Distributing a line at all and just not using this space okay cool so where do we go from here well we can just do a for Loop right a nested for Loop if we've gone from for I in range n and for k for J in range Okay so we could populate this system I or I guess j i equals the sum of I prime equals one I guess we could call I prime that's fine I prime equals one all the way up to I d k minus DJ minus one d i minus I prime plus d j D of I minus 1. so we could run this whole thing right this formula here sorry if the notation is incorrect or sloppy the but the general idea is right we're gonna have to look at o of N Things here o of K thinks here and then here we have to do o of K well it's actually up to I so o of n operations right so for each o of n so for each n we have to do K things and for each K things we have to do n things so that means we have to do Big O of n times K times n or Big O of N squared k now this might be good enough but n is less than or equal to a thousand so a thousand is 10 cubed so that'd be 10 cubed times 10 cubed 10 to the nine so that's going to give us a time limit exceeded um issue so this is still to um this is still too slow right barely but it is still the case that this is too slow of a process for our purposes so I guess the one thing we can do to fix this problem to make it just a little bit more efficient so that we don't need to do o of n times K times n operations right is let's work with the math directly and think about how we can make uh this just a little bit more efficient okay well foreign right meaning you know when we calculate this is constant time right but this right now is taking o of n time to operate so since it's taking all of that time it's causing that additional n factor in making our solution 10 to the 9th if we made this constant then it would be o of one so if we just kept track of this sum somehow then we wouldn't need to continue to um recompute this over and over again what if we had like a prefix some idea what if we had this information catched or saved somehow that way when we calculate this information is constant well let's just call let's call D of call it Big D of k n equals 1 to n d of K the sum up decay n minus I so that would mean if we substituted that in here D of k n so I'm just trying to do some direct substitution here would be D of K minus one all the way up to n this is Plus D of K n minus 1. so then you might be just saying right now okay well that's just a foolish substitution who cares right um I guess the idea here is then we could update this system we could update d k of n by saying DK of n equals D of K minus one of n because what is DK of n in terms of DK of n minus one it should be small B here all the way up to n so if it's all the way up to n then the recurrence relationship here would be sorry this is a very confusing problem and I'm not articulating what's going on here very well and I apologize okay because I guess the idea is here because what is DK of n minus one well d k of n minus one is this what's this here just to prove it to you why I wrote this recurrence relationship like this right it equals that let's make it blue and we're adding in DK well it's DK n minus I d k of N and since it's n minus one this would be n minus 1 here so then we're just adding in this final term right this is just the last term of this sum this equals I equals 1 to n d k of n or because this will be the final term of the sum if you just went one past what it was before right so that's DK again very mathematically intensive problem here so with all that said in order to solve this problem if we just keep track of this sum using this system then we only actually need to solve these two problems and this can be solved in constant time and at the end you just return uh the final value of this system hopefully that makes a little bit of sense I this is my own unique solution and I didn't see anyone else do this so it's a little weird but that would basically make you know now solving for any of these is constant right this is constant this is a constant thing we catch is the constant thing we catch constantly cash so for k n values so in Big O of NK time we do constant things so it's MK time um now what are our initial values well in any space right d of I guess D of 0 for any n value equals one because for any K value if you have how many ways can you distribute nothing to any space one way doing nothing right so that's basically what this is saying here for any n value is one okay so let's go ahead and just walk through this recurrence relationship and see if you can get us to the solution okay so we have Big D and we have Little D now we're doing kn so we'll do one times n Plus zero for zero times n for blank in range okay and then now let's just run through this recurrence relationship so we'll go through n through k so for NN in range we don't need to look at n equals zero for k and range okay we'll just update using this recurrence relationship and not think about it too much so D of k n equals DK minus one n plus d k n minus one okay so little d k n equals D of K minus 1 and plus d of K n minus 1. let's um okay so this is DKK and the KK and then E K and N and then Big D of KK and it updated is just taking the previous operations value adding in current one and then at the end you just return D of negative one because this will give you right negative one would be dkn which would give you the number of ways that you can sum up using K things right man uh what am I doing wrong here that'll be K because it's K plus one all right this is link K plus one because that time let's see if this broke my recurrence relationship had a KK minus 1 and n you know and that's the wrong it's minus one why is it minus one okay so this is mod 10. you know this game the game we always fail Okay so notice the max that this system can go to is n minus one right it goes from n minus n K minus 1 n minus n you can't make a string that's n minus n here because there would be no space for the remaining string so the highest they could this can go is n minus one so this would be then n minus 1 here so this would be n minus 1 here and I'll get you the solution all right guys this may be my very worst video nobody watches this like most of my videos that's fine but it's good for me for practice this is uh it's difficult okay what's the runtime what's the space okay so for space and run it's the same now we have to look at N Things K things so for all NK things we do constant operation it's NK time we have to also populate NK things here and populate NK things here so it's NK space as well so NK time and K space okay KKK see ya
Number of Sets of K Non-Overlapping Line Segments
number-of-subsequences-that-satisfy-the-given-sum-condition
Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints. Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 4, k = 2 **Output:** 5 **Explanation:** The two line segments are shown in red and blue. The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}. **Example 2:** **Input:** n = 3, k = 1 **Output:** 3 **Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}. **Example 3:** **Input:** n = 30, k = 7 **Output:** 796297179 **Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179. **Constraints:** * `2 <= n <= 1000` * `1 <= k <= n-1`
Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences.
Array,Two Pointers,Binary Search,Sorting
Medium
null
1,915
There are hello guys also in this video they go into se 10 problem numbers and wonderful subjects so what is a wonderful subscribe interesting where at most one later affairs and number of times she can see the example portion this scene which is six example water crisis in the number Of Times Series Repeated History Advantages Defeated Is Two Shoulder Should Be The Most Helped Emphasis Of Days 100 Most One Letter Application And Number-10 President SPS And Application And Number-10 President SPS And Application And Number-10 President SPS And Number Address To Love The Ne Pac And Number Times S You Can See The Example E 20 Directly Executives and Senior Students will Sleep MP Isko Times and Acid Test More Than New Episode Number 500 Backem Chief Bustling with the Number of and 1200 A Specific Years Will Hear No Later is the Video then subscribe to the Page if you liked The Video then this all Screen that your also what we have to bank savings so let's get up and intuition you from here this problem and will directly 100 glue subscribe to angry birds for going to be something Lakshmi explain you this act and operator and cancer se by product sweater se 0.2 subscribe to your after eggs with 0.2 subscribe to your after eggs with 0.2 subscribe to your after eggs with subscribe 250 divine subscribe right subscribe this piece 10101 A little boy's bodh and once in this way you will again be too difficult for lips this thank you have to keep in the Distic and one more thing Supports must be * This is exclusive lu dis page let's see subscribe like you can do something like this a in this and disposed and it's ok to give it a go back to this actually zero exams page so what's this after what you want to subscribe and decided to support The That And Spiritual Mask 120 Sports C What This Will Result In April 2012 161 Straight B C And E Will Be Deleted And Will Be Like This Subscribe Tab Off All The States With Water All Subscribe Button Letter With U That Suvatiya is going to perceive what we will give you now Maruti 800 1320 Bhavya Bhavan to the Video then subscribe to the Page if the hour ago to represent district the one for being represented with and 10 minutes after representatives of this letter will be Cent and it's ok 12345 680 I will present 500 and 1000 smart converter05.htm that word MP's mass as zero examples notification is such only source of will suffice for a 0001 for 20 2010 ch-51 09 speed meat and exhausted 2010 ch-51 09 speed meat and exhausted 2010 ch-51 09 speed meat and exhausted with quote will Be Difficult To 10 Of 10 Things You Must See This Value Is Well In Waqt Camp What Is The Value Of 200 Maa Skirt With 20018 A Similar D Is Drafting Pocketmar Chalega Teen Do Ek Baar Off Birth Mass Karne Quote Exams Page Issi Against AIDS Patient Will be removed and will take place to the Tags Arvind Chief Disawar You Must Agri Milk 0 Sila Duma Stands For Storage Vacancy Shodh Elizabeth 110 Will Again Witnesses And After The Printed 1200 More Importance Okay This Video Exothermic C Value 800 Wickets 105 Words This Adham To this is such a 342 experts have the holy cave of window to Sadar Asraf so Anand Sheela me civil again and again of birth 2010 point subscribe is this mask to 21814 operation of elements of this Bluetooth once operation Shabdish are in Features What Is Means 2012 1,000 Aur Sabse Features What Is Means 2012 1,000 Aur Sabse Features What Is Means 2012 1,000 Aur Sabse Zor Peerche Aksar Seervi Collectively 1025 E O N 0 The Video then subscribe to the Video then subscribe to The Amazing Number of the Day A S T Spoon Ali reached the fighter end gate and took the sim that -Between point and took the sim that -Between point and took the sim that -Between point vacancy se zinc burst MP4 se zinc from a point start cesc pair bp.ed ya na point start cesc pair bp.ed ya na point start cesc pair bp.ed ya na dhoop wa subscribe between two points on this thing is the meaning of the number 999 apni badi easy players will always be in will not understand the giver And Circular They Have Everything From This Point 0.5 Special Everything From This Point 0.5 Special Everything From This Point 0.5 Special Guest Sage In 1803 E Mein Aa Adityanath Seervi Akunth Specific Market Value Is 409 Plus Understand How Will Get The Number Of And Value Member This See Its Fans Free Mode On And Drags And With All The Values Pair Co * Supports Then Eye Can They And With All The Values Pair Co * Supports Then Eye Can They And With All The Values Pair Co * Supports Then Eye Can They Reduce Orange Letter Of Big Roll Number Of Times Plain Letter Confirmation In Which CBSE Is This Is Not Carefully Sweat Through This Hair Care Numbers Page Number 2 Ask Exam Form This Page Directly Middle School With Water All The Chief Sea Fennel 2 Exorbise Sapoch Sep 2012 Exorbise Sapoch Sep 2012 Exorbise Sapoch Sep 2012 I One 0821 Services 12101 33500 Term End 109 Busy Schedule Graeme Smith And Sapoch 300 B C D 120 Dip So Many 0 End Values ​​End WhatsApp To See The Values ​​Off Values ​​End WhatsApp To See The Values ​​Off I am your show interview has welcome zero to 1000 wide variety debate stage so set time particular point now screams rent act will be r ashwin dance simple a letter with and recitation only be but give me example player leuvin undercurrent suicide 10th over smart They are daily this one must follow this rear it is active on Thursday subscribe surya market value got but market value easy 2015 on amazon to z sirsa construction and worries of this character recipe subscribe button video 000 subscribe already being that all that screen from This particular point to the end were amazed with subscribe will be repeated subscribe to the Page if you liked The Video then subscribe to the serial number subscribe to hai bbc ne 181 number agree with is vansh everything is related to that you thanks for this is And subscribe yes bhaiya sab singh aadat hai notification for this is the concept or any user name is the different are subscribe to the Video then subscribe to subscribe our ki naav par neech character in the world everything is going to see what is that characters of Electrification of CMS - characters of Electrification of CMS - characters of Electrification of CMS - Chief Syed Ashraf Member Ward 08 - 1800 334 subscribe and subscribe the Channel and subscribe this for the number one and number two A View of Movie Pt. Total Because Vivek Poochhega Qualities of Yours Veer Verification of Yourself Thank You Are Masking Disha And head and subscribe the world at that this vitamin C important direct commission committee seriously so let's committee will see this rumor giving them without any fear in 2030 password has arrived like this thank you
Number of Wonderful Substrings
check-if-one-string-swap-can-make-strings-equal
A **wonderful** string is a string where **at most one** letter appears an **odd** number of times. * For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not. Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-empty substrings** in_ `word`_. If the same substring appears multiple times in_ `word`_, then count **each occurrence** separately._ A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** word = "aba " **Output:** 4 **Explanation:** The four wonderful substrings are underlined below: - "**a**ba " -> "a " - "a**b**a " -> "b " - "ab**a** " -> "a " - "**aba** " -> "aba " **Example 2:** **Input:** word = "aabb " **Output:** 9 **Explanation:** The nine wonderful substrings are underlined below: - "**a**abb " -> "a " - "**aa**bb " -> "aa " - "**aab**b " -> "aab " - "**aabb** " -> "aabb " - "a**a**bb " -> "a " - "a**abb** " -> "abb " - "aa**b**b " -> "b " - "aa**bb** " -> "bb " - "aab**b** " -> "b " **Example 3:** **Input:** word = "he " **Output:** 2 **Explanation:** The two wonderful substrings are underlined below: - "**h**e " -> "h " - "h**e** " -> "e " **Constraints:** * `1 <= word.length <= 105` * `word` consists of lowercase English letters from `'a'` to `'j'`.
The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters.
Hash Table,String,Counting
Easy
889
61
hey what's up guys think white here I do token counting stuff on twitch in YouTube I do the Premium Lee codes on patreon everything's in the description and you should join my discord thank you this problem is called rotate array a lot of likes some dislikes I saw people complaining it was too hard given an array rotate the array I'm sure you guys have heard of this rotating an array given an array rotate the array to the right by K steps where K is non-negative right by K steps where K is non-negative right by K steps where K is non-negative okay so we're given an array like this 1 2 3 4 5 6 7 and we rotate it to the right three times so the 7 goes to the front the 6 goes to the front and the 5 goes to the front and then it's 5 6 7 1 2 3 4 so rotate a rotation is just popping something off one rotation is popping one number off the end of the array putting it to the front and pushing everything else to the right so I mean yeah ok k equals 2 so you rotate the 99 to the front and then the 3 to the front I mean it's pretty straightforward people complain this is too hard this should be medium this should be a hard problem is so hard guess what it's not hard dude let me tell you why you guys think that when you this is what I have a problem with this people think especially people that try to understand algorithms and they give up they sit and they I they'll sit and look at this problem and be like they'll have a double for loop solution and be like how do I do this I don't know how to do this I can only get N squared solution I don't know how to do this guess what look at the solution just look at the solution sometimes and in this case there is a trick that you can either sit here and spend all day trying to figure out and eventually figure it out or you can just look and think oh this is how it is you do these steps and this is how you do it in a linear run time you know it's just the way that it is you don't have to you know there's no crazy explanation for it's just the way it is sometimes and I'll explain you know I'll show you it the trick here is you know the array you know you have this array so like 1 2 3 5 6:7 if you want to rotate it three times 6:7 if you want to rotate it three times 6:7 if you want to rotate it three times the trick is you reverse all the numbers so you reverse one two three four five six seven so it becomes seven six five four three two one then you reverse the first K numbers five six oh seven six five the first three numbers becomes five six seven then you reverse the last numbers after K four three two one becomes one two three four and look if we were to have pulled this seven six and five off the front you put five six seven one two three four it's exactly what it is so you reverse the whole list you reverse the first K numbers then you reverse the leftover numbers that's it's just how it is you don't have to you know it's not like the person who thought of this probably had to sit there and think for a while we don't have to because he did we just learned things it's like just learning a thing in math class you learned what it is you remember this next time and that's just how it is you don't have to sit here like if you didn't know how to do it in an interview like yeah you'd have to sit there and look at it but you that's why you study for the interviews you study so you see stuff like this you do these easy problems and then you know how to do them so you know that's my rant so first thing we're gonna do is we're gonna take K and we're gonna do K mod nums dot length just because apparently the problem let's there be none nums array where the length of the array is less than K or equal to K and in that case you know it's gonna be we have to do this to be able to know how many numbers to reverse and then like we're gonna do the steps right so we reverse nums from zero to nums dot length so we reverse the whole array minus one we reverse and once we reverse the whole erase we reverse the whole rec it looks like this then we reverse the first K letters so we pass in nums we're gonna do from zero to K minus one these are indices that's what were you adding the minus ones here and then we're gonna reverse the leftover numbers that's it guys don't think on it too hard if you don't have to think about it so much then don't you know so many people get stressed out and it's like you don't need to be so stressed out and then you make your reverse method that's a it's real that's why it's easy because it's easy you know just look learn it and then you don't forget it you know just remember some of them you do have to figure out solutions to but you have to learn your tools before you actually you know this is a tool learning one so and then you use this to figure out harder versions of this problem but this is something you just got to know so whilst art is less than and we're gonna do you get your tenth will set it to numbs of start we're basically just doing swaps so you do a number that's equal the number and this is just our basic reversal so you just go through the array and you swap the it's like two pointers almost one at the beginning one at the end and you're just swapping them as you go through that's just a basic reversal and then nums and then you always have to make a temp because you lose the reference to start right here we're resetting it so we want to set numbs abend equal temp and then you just decrement start so you do plus and minus and yeah that's it's the whole problem that's why it's easy you know it's easy there you go let me know what you guys think let me know if I'm wrong here but I'm I mean I see a lot of people that like complain about you know this should be under medium category it's like I don't know it's I think it's just people overthinking things and it's like sometimes you know I don't here's a one more thing before I get off I know this isn't like a advice video but if you're struggling with a problem for more than twenty or thirty minutes you're wasting time dude look at the solutions learn from them there's thousands of these problems you can learn the basics just look at the solutions and learn from them and then when you're ready you can start using your knowledge to actually knock out problems on your own you know that's what I that's my strategy let me know what you guys think in the comments but appreciate you guys for watching sorry for being a little bit negative I just want you know you guys not to waste your time don't waste hours on these and then stress yourself out and give up just fit learn from things this like I got it down in my mind now I don't know I don't have to look you're the whole list you reversed the first K you reversed the rest of them that's it thank you guys for watching and I'll see you guys in the next one
Rotate List
rotate-list
Given the `head` of a linked list, rotate the list to the right by `k` places. **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[4,5,1,2,3\] **Example 2:** **Input:** head = \[0,1,2\], k = 4 **Output:** \[2,0,1\] **Constraints:** * The number of nodes in the list is in the range `[0, 500]`. * `-100 <= Node.val <= 100` * `0 <= k <= 2 * 109`
null
Linked List,Two Pointers
Medium
189,725
365
hi everyone this is Emma let's look at some little problems today we are going to look at 365 water and Jack problem so first let's read the problem you are given two Jacks with capacity The Jug 1 capacity and the drag 2 capacity leaders and there is infinite amount of the water supply available you need to determine if it is possible to measure exactly the target capacity leader using these two jacks so finally the target capacity leader of the water need to be contained within one or both buckets here are the options you are allowed to do you can fill any of the tracks with water so initially that's empty you can feel it okay fill with water or you can empty any of the Jets so it has some water inside you can empty that or you can pour water from one Jack to another one so you have the smaller one it has the one liter of the water and you decide to pour water from the smaller to bigger one so finally smaller one is just empty their liter inside and the larger one has a one liter of the water and here's one example we have the Jaguar capacity three and the Jack 2 is a larger it is a larger capacity is five and our Target is full the output is true so let's see how to solve this problem so we have two Jack one is smaller it has capacity and the other is bigger is five we have our Target capacity that is four so what we can do right now since these two Jacks are empty right now we can choose either fill the smaller or the bigger jug with water so let's try to fill the bigger one with water while you can also choose a smaller one but here I just use a bigger one as a demonstration we fill the drug with water larger one with water so right now it has five inside it's still empty and we decide to um pour the water from the larger one to smaller one right so final one we can get a smaller one it has a on the water from the larger one so finally it has a three right three over here and the larger one only has 5 minus three two left and next what we can do we can empty This Modern one right and we can transfer we can pull the water so finally what we can get so initially that will empty the smaller jog is zero and we'll get two water from the larger one and the larger one would be just empty next we can add water to the larger on junk and we can transfer the water to a smaller one so if I know what we can get so for the smaller one it will be full with three and the larger one initially that is five it says one liter of the water get to a smaller one so finally you know when it has four left okay and this one the smaller one is three and finally we just need to remove the water from the smaller jug and finally we can get smaller one is empty and a larger one it has a four liter inside and this is our Target if we look at the entire process we track the total amount of the water of both jugs okay you will notice initially this is zero right and we add five here is transfer body will not affect the total amount and then we will remove from the smaller jug is minus three and here is we add another five we'll remove another three so that's a zero plus five minus three finally we'll get a four here as we can see for each step we have four options you can plus five or minus five or plus three or minus three so finally we will get our Target floor or not let's recall how we solve the problem so let's track the total order of Two Jacks so initially two of the drugs they're empty so the total should be zero and we have four options we can do plus five minus three plus three so let's just add these four over here and we can calculate total so the total here is five negative three and three so for the first one the five is okay well it's negative five it's not possible the total of the two jar should be at least zero that means at this moment they are empty if the total is smaller zero and also if the total is um larger than eight the eight is the largest possible amount of the water when Two Jacks fill with water we need to return we couldn't find a solution from these steps here we can just return false get a false this way as possible and we can keep searching and we can calculate the total so for this one is larger than the upper boundary we can just return force and this one zero we've already seen zero before so we don't want to repeat over here we need to um create a set we call that scene to track the total of Two Jacks we've seen before so we already seen zero over here and a five right we add a five and we also add three inside so if the total or it is out of the boundary we all need to return false so we can continue this is false because we've already seen that zero before and this is two we didn't see that so it is okay and eight is also okay so let's just add the two in it to the sink over here and we can continue from here we have four potential options five minus three and three so we can do a calculation of the total here should be seven negative three negative one and also five so we can check the seven we didn't see that before so we can add a 7 to the same and negative three since that is smaller than zero we just need to return false and also here's negative value return force and the five we've already seen five in the same set so we just written fours so we can continue over here plus five minus three plus three we can do a calculation of the total it should be 12 2 4 10. so for the 12th it's out of boundary larger than 8 return Force the two we've already seen two before return force and here the 4 equals to our Target total equals to the Target okay just return true so we can find the final Target is four we can just return true so it's from zero five minus three then plus five final again get our Target so we will look at our criteria over here if we didn't see that before and that increasing the boundary and it's not the target so for the total we have four options we can plus 5 minus five or minus three or plus three if any of them return true we can just return true else we return false so right now let's consider about the time and space complexity so for the space as we can see we only have this thing set and for the things that we have potential value from 0 to the sum of two capacity the capacity one plus a capacity to a space complexity it should be o the capacity of one plus capacity two while for the time we have jaguan and jag2 so for the Jaguar just zero liter of the water to the capacitive one well for the juncture it has zero to capacity two so how many combinations over here you should be capacity one plus one then times capacity 2 times 1. so finally for the time complexity it should be o capacity 1 times capacity 2. here we will introduce both DFS and BFS to implement idea we share before let's try start with DFS so first we need to create a set we'll keep the totals we see before and then we will create a function for DFS then we will have the total as our input so if the total that equals to the Target we can just return true Y is a total we've seen the total before or the total is out of boundary larger than the sum of jug 1 and jugular capacity so we just return both if the total is not equal to Target we didn't see that before it's also within the boundary then we can add the total to C for Next Movement we can either add or minus junk capacity over M minus junk to capacity so you can do that quickly so for different for potential operations if any of them return true we will return true right all of the Rhythm force it will return Force so we can just return it and now we need to call this DFS function initially the total should be zero so both of them are empty you can just return this value and we can try to run and that is right and we can submit it so finally we can pass on the test and now we can try the second solution be at best and we are going to use Q to implement this idea so we will create a queue and we have the first value the total is zero inside and we will create a set keep tracking the thing total and we have four different potential options so we can plus or minus the Jack capacitor one or plus minus drug capacity two while we have something in the queue and we will pop the first one this is the top left and we will iterate all the potential operations will calculate the total will be current plus that and if the total equals to our Target we will just return true if the total we didn't see that before and the total is releasing the limit that means nicer than zero and also smaller than the sum of two capacity now we can add the total you see we will append this tunnel to the current queue if there is no solution return true your return false and we can try to run it and also submit it and it works
Water and Jug Problem
water-and-jug-problem
You are given two jugs with capacities `jug1Capacity` and `jug2Capacity` liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly `targetCapacity` liters using these two jugs. If `targetCapacity` liters of water are measurable, you must have `targetCapacity` liters of water contained **within one or both buckets** by the end. Operations allowed: * Fill any of the jugs with water. * Empty any of the jugs. * Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty. **Example 1:** **Input:** jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4 **Output:** true **Explanation:** The famous [Die Hard](https://www.youtube.com/watch?v=BVtQNK_ZUJg&ab_channel=notnek01) example **Example 2:** **Input:** jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5 **Output:** false **Example 3:** **Input:** jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3 **Output:** true **Constraints:** * `1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106`
null
Math,Depth-First Search,Breadth-First Search
Medium
null
55
hello everyone let's look at jump game the problem statement is we are giving an array of positive integers we are initially positioned at the first index of the ray each element in array represents the maximum jump we can take at that position we need to determine if we are able to reach the last index let's look at the example this is input 23114 initially we are here at two and then we can jump either one step or two steps so if we jump one step we reach three and three we can jump three steps to four or we can jump one or two so if we jump three steps to four then we reach the end that's the explanation jump one start from index zero to one and then three steps to the last index i guess a really straightforward solution is to try every single jump pattern starting from the zero index and then we only need to check if any path will lead us to the last index this is like travels a tree and we need to use recursive back tracing but if we think about recursion it might not be the optimal solution this is like if we want to solve a fibonacci sequence we rather use a recursion rather than using a single loop however for this question i will still explain the recursive solution but in general it should be categorized into dynamic programming it's a top-down dynamic programming it's a top-down dynamic programming it's a top-down dynamic programming solution let's use an example here think about our input arrays 3 1 0 two four so initially we're at position zero that's three that means we can jump one step two steps three steps if we jump one step it's one the value is one we can only jump once then we jump to zero we won't go anywhere so this path three one zero doesn't work let's back to three if we jump twice then we jump to zero we jump to here and then we still don't go anywhere so three zero this path doesn't work if we jump three steps then we jump to two and two the value two we can jump either once or twice if we jump once and then reach four that's the last index so we have this one path 3 2 4 reach the last index 4. as a result we can return true so we can easily build this tree structure and then determine if we can reach the last index let's look at this tree again well please think of this as a tree when we jump we can mark a certain index as good or bad for example this one index is two is certainly a bad index because the value is zero it won't lead us to anywhere we end up stuck stacking here also for index one the value is 0 sorry the value is 1 and the next one is also 0 so this index is also bad to sum up we want to mark every index either good or bad from top to down let's go through an example so initially the values are unknown this is unknown okay from top to bottom for three we don't know for one we don't know for zero index is 2 this one becomes bad because index 2 is bad index 1 is also bad so this becomes from unknown to bad and then 2 two we don't know but next one that's four is good so that's two is also good and three is also good because they're on the same path and all these good and back can be saved into a memorization array let's call it memo so initial value will be all unknown and then from top to bottom we update the value in the end as long as the first element for this array is good then we know we can jump until the end based on the rule we just described here i know you are thinking about why now we check the index in a reverse order first from 4 then to 2 then to 0. i'm telling you this is a really good thought this will be the second solution we call it a bottom-up it a bottom-up it a bottom-up dynamic programming let's first look at the implementation for the recursive top-down approach so first we get the length of the input array and then we initiate our memorization array the initial value are all unknown and we want to update that last element the last element should be good and then this is our recursive method we pass index in as a parameter and then we only need to return jump 0 let's look at the implementation for this recursive method if the car inducts the value is good will return true if the value is bad we return false and then we have this number's i this is a value is how many steps we can jump for the loop we need to have a boundary check we need to have the mean value for the lens minus 1 and the steps we can jump this is because we need to have this boundary check and then let's start our for loop what should be the start index for this i think it should be index plus one if we think the starting index is index plus 1 then this max jump here we should also have idx plus nums i and then let's do the jump again we pass it in we check the jump result if it's true then we can update the index for this memo that's good and also return true otherwise after the for loop if we don't any good it should be marked as bad and return false and this is the recursive method and uh and here it should be idx not i so this is the how many steps we can jump and we add this um index that's why we have i equals index plus one let's sum it in past but it's um yeah takes really long time let's first look at the capacity here for space is all n this is the size of our mammal table and then for time it's open square because we have this recursive method obviously we all know this is definitely not the optimal solution let's look at the bottom-up solution let's look at the bottom-up solution let's look at the bottom-up solution for the bottom-up approach let's see for the bottom-up approach let's see for the bottom-up approach let's see this example again so this is our mammal the initial value will be bad initial value is all bad except the last digit the last one is good and then we from back to front if 4 is good and the next one second last two is too good i think it is good because it can jump either one step or two steps so we update this too good and then we keep moving back zero is this good or bad no it's bad we keep it like this and then one is one good or bad i guess it's bad and then three is three good or bad it's good by doing this we get this final mammal array and then we return the first element for this memo sorry not return the first element but to check if the first element is good let's look at the implementation first we can completely get rid of this recursive method in the end what we need to return we only need to return this as long as the first element for the memorization array is good then we should return true let's look at the loop inside we do the loop from back to front so the start index is the second last and then we keep minus one inside the loop we also have this boundary check and then inside this we have another for loop so for the j as long as the j is at the good position so if j is good then we can say i is also good we can break this inner loop and then we go to the outer loop we have this is typo we have this max jump and then we do the inner loop again after the for loop ends we return this if the first element for the memo array is good let's submit it passed and this time the performance is much better than the first approach let's look at the complexity here this time space is of n that's the size of our memorization array for time it's all n squared because we have this outer loop and inner loop i do understand for both top down and bottom up dynamic programming solutions are not optimal and even confusing if i have confused you feel free to move back and look at the video one more time finally let's look at grady which is supposed to be the best solution for this question to illustrate my idea let's look at this example again let me clean up this a bit so initially we have a value called maxjump and the initial value is 4 comes from length -1 then we can loop comes from length -1 then we can loop comes from length -1 then we can loop through the array from back to front we can skip the last index and then let's look at the second last index is 3 value is 2 and we need to compare the sum value 3 plus 2 if it's greater or equal than max jump if it's greater then we mark this index as good the reason is because at this index we can jump two steps that's greater than four so we mark this as good and then we update our max jump into three that's the index for this good index and then we keep loop we move to index two and index two the value is zero so we add them together we get 2 is less than max jump so we mark this as a bad index and we don't update our max jump is still 3 and then we move to index 1. value is also one we have one plus one that's two that's less than max jump still we mark this index as a bad index and we don't update our max jump and then we move to index zero adding them together zero plus three is three so we mark this as a good index and then we update our max jump to be zero after the loop if the maximum value is zero then we can return true if i have confused you let's look at the implementation i can confirm it will be clear when we look at the code logic this is our max jump initial value and then let's do the for loop same thing here we start from the second last if the sum value is greater or equal than max jump then we update max jump after the for loop will we return if max jump equals zero let's submit it looks good let's look at the complexity here first base is constant the time is o of n we have this loop here i'm sorry this video is a bit long i hope you find this explanation useful when you look at this question thank you for watching if you have any question please leave a comment below
Jump Game
jump-game
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position. Return `true` _if you can reach the last index, or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[2,3,1,1,4\] **Output:** true **Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index. **Example 2:** **Input:** nums = \[3,2,1,0,4\] **Output:** false **Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 105`
null
Array,Dynamic Programming,Greedy
Medium
45,1428,2001
159
now let's take a look at a legal problem called longest substring with at most two distinct characters so given a string s find the length of the longest substring t that contains at most two distinct characters so at most to the same character basically means that um not no more than two distinct characters so if we have only one distinct character in the string that still count as a uh that we can still calculate the longest substrate right only if it's like more than three uh distinct characters in the substring then we cannot be able to uh count that as a longest substring uh so in this case here you can see we have an example of e c e b a and the longest substrate in this case is gonna be three because we have ece which has a length of uh three right so in this case it has two distinct characters in the substring and uh we only we have a size of three right so is the max so and then here you can see we have another example of c a b and in this case t is a b which is has length is five right so we have a b which has a length five and uh it has two distinct characters in the substring now we could choose ccaa but in this case we have a line of four so it's not the largest so to solve this problem uh we're going to use sliding window technique uh basically we're just going to expand our window uh if it can satisfy our condition and we're going to contract our window when we don't satisfy our condition right when we start to uh don't satisfy our condition we want to make sure we can track our window and um and then from that we're going to continue to expand our window after we're done contracting right after we're contracting we want to make sure our windows satisfy the concurrent condition that we can be able to expand so let me show you a demonstration of that so let's say we have an example of e c e b a okay so far we have one element in the table in this case we have e and the max length that we have seen so far is one because we can have uh one character in this case our current window satisfy the condition because we have no more than two distinct characters in our window so now we expand our window now we have c so c has up here once okay so we're going to have max length that we have seen so far is two because we have two elements in our window so now we have e so now we're going to add e by one right so in this case we're going to out in this case our window has two e's and our wind our maximum length that we have seen so far is three so now we're going to expand our window again and we have b so now we're going to um check to see if we satisfy the condition but in this case we don't because we have at least three and now we have three distinct characters so we're gonna uh contract our window so now we're going to shrink our window now we have only one e and now we're going to still doesn't satisfy the condition then we're going to shrink our window again now we have e and b so now we're gonna update our maximum length in this case but the thing is that our maximum length is three is bigger than two so we don't we won't update the current uh the current maximum life so then we're gonna start to expand our window again because in this case we have satisfied the condition so now we have a we add a onto our window and then we're going to have three elements but in this case we have the same characters of three so we have to start contracting because in this case we don't satisfy our condition so now we're going to remove e out of our table and now we start to met the requirement metacondition and then we have to update our max length in this case the size is two but the max length right in this case the max length is three so three is bigger than two right so there are only two element two elements in the window so in this case we're not going to update that so now let's take a look at how we can do this in code so first we know we basically know that the constraints it doesn't really have any constraints so what we can say is this we can first define our base case so if the string is empty or string has only one element uh then we can just return the size of string right because there's only uh one element where there's no elements at all so we're going to return the size of the string size of string if the size of the in this case if the size of the string is less than three actually because if there's only two then we know that's going to be uh that's going to be a valid answer right then once we define our base case we're going to define our pointers right so define our pointers and we want to make sure we define the table right and we want to define a max length so once we define those variables we're going to basically trying to find the max length right so max length substring to the same characters okay so let's define those sections so first we're going to have n which is equal to s dot uh as the length or what we can do is we can convert this into a character array which is equal to s.2 character array which is equal to s.2 character array which is equal to s.2 character array and then we're just going to say array.length okay so once we've done that we're going to say if n is less than three we can just return it right if there's only one element in the array in the in yeah in the array then we can just return the size of the array if there's two elements then we can just return two right and then we're gonna define our pointers so our pointer is gonna be in this case we have our left which is equal to zero so the right also starts at zero once we define our pointers we're going to define our table so we have a map sorry it should be character should be the key right and the integer is going to be the value so we have hashmap is equal to hashmap okay so once we define our table we're going to define our max length so now we are going to have integer max length which starts at zero okay initially we have we haven't had any elements yet okay so we're going to say this we're going to say while the right point is less than n right we're going to start to expand our window because in this case we uh we satisfied our condition right so what we're going to do is we're going to first add the current character onto our hash map so we're going to say hashmap.put hashmap.put hashmap.put okay we're going to say array at right okay it's going to be hashmap.get or okay it's going to be hashmap.get or okay it's going to be hashmap.get or default because we don't know if we create that position we haven't created that element yet so in this case we're going to say array at r by default is zero we're going to plus one on that one so once we update our hash map we're also going to basically check to see if we satisfy our condition right so in this case what we're going to do is we say while right so while um the size of the hash map so the size in this case is if it's bigger than two then we know that we don't satisfy so we shrink so we contract our window if we don't met the condition right if we don't need the condition so in this case we're going to start to shrink our window right so what we're going to do is we're going to remove the element that the left pointer is pointing to so we're going to say hashmap.put so we're going to say hashmap.put so we're going to say hashmap.put array at left we're going to decrement that element by one so hashmap.get that element by one so hashmap.get that element by one so hashmap.get uh array left decrement by one and if you realize that hash map dot get right hash my bucket array left is equal to zero then we know that we can just delete that element right so remove array left and just delete the l delete that element and otherwise if we uh if we don't have to delete an element right so in this case what we're going to do then is we're going to move the left pointer one to the right because now we delete the element off our table and we can be able to shrink our window now so then at the end what we're going to do is we're going to continue to get to a state where we continue to shrink our window until we met the condition which is basically uh can track our window until we have at least uh you know less than or equal to two elements in the table right so then what we're gonna do then is we're gonna um update our max length right so in this case our max length is now equals to the maximum value between either max length or the size of table or sorry the size of the window in this case to calculate the size window is going to be the right point or minus the left pointer plus one to give to which give us how many elements do we have in our window so once we update our max length we're gonna we're going to move our right pointer one to the right so now we because now we know we met because after we've been through all this while loop thing we know that we met the condition that we can start to expand our window again so we're going to continue to do that until we get to a point where we um iterate or basically traverse all the elements in the array then we can just return the max length okay so now let's try to uh run our code let's see okay let's try to run a code okay so let's try with this example right here and let's try to submit so here you can see this is how we solve this uh liko long longest substring with at most two distinct characters
Longest Substring with At Most Two Distinct Characters
longest-substring-with-at-most-two-distinct-characters
Given a string `s`, return _the length of the longest_ _substring_ _that contains at most **two distinct characters**_. **Example 1:** **Input:** s = "eceba " **Output:** 3 **Explanation:** The substring is "ece " which its length is 3. **Example 2:** **Input:** s = "ccaabbb " **Output:** 5 **Explanation:** The substring is "aabbb " which its length is 5. **Constraints:** * `1 <= s.length <= 105` * `s` consists of English letters.
null
Hash Table,String,Sliding Window
Medium
3,239,340,1034
1,002
hello everyone today we are gonna solve find common characters problem so in this problem we have an array of strings and we have to find the common characters which are present in all string including the duplicate so in this example you can see that e double l is present in all of these three string so in this case we will written e l and double l and this can be in any order so how do we do that so our first intuition will be what we can do one thing we can use um map we can use the map where we will store how many times a character is present let's say this is present b is present one time is present he is here present one time l is present two times and e is present one time and here also we can map how many characters are present here so we can say that l is present here two times and a is present here one times b is present here one times and is present here one time and if i map this also so this will be r is present one time o is present one times l is present two times and this is present one times and this r is present um definitely it's present two times so i will remove this so now what i have to do i have to find b is present here so what i can say that here my b is present yes it is one here i can say that b is present zero times yes so what i have to do i have to choose the minimum one from this so my b is present zero time so if b is zero then i will not include into my answer not included my answer now see now let's see e is one time and here he is also one time so minimum will be one time so i can write e one time here now let's see here is to um this is l so l is two times here at l is two times and here also l is two times so what i will do i will make l two times in my answer now this a is here one time also one time here is no is i can say that a is zero times so minimum will be zero so i have done this so what uh how can i do this so this is my intuition how can i do this for this case how many number of alphabets we have in english so we have 26 alphabets so what we can use a simple array having size 26 and we will initialize with zero in the slide with zero why because initially we have no character in a string then we will iterate from i trade this first string and store all the character in this string or this array and now we will add this into our new vector and check compare which one is minimum and the minimum one will be stored in this vector and this let's say i will name it as a common vector so i will do that after all after that i will add all these characters of the string into my vector and i will do it for all the strings all the remaining string and once i will find the common and this common will be minimum of all this all character minimum so at if there are is to here is two time present but here is one time present then i will add only e one time if this is two everywhere or minimum two then i have to add two here so now let's see how we can solve this uh using the code so here what we are doing is first of all we are using this vector which is our common vector and which will store our result and we are initializing with into max because we have to store here the minimum occurrence and this is our result which will store a string okay so basically they are correct and not string but we are using it as a single character string so how we are doing is first of all uh in our arrays this arrays what we are doing is we find this string first string and what we are doing is we initialize it with zero so i have this vector and i am initializing it all with zero now after that what i will do i will count how many number of characters i have in this string and their occurrence so if i have a one time so i will mapping like this so once i done this then what i will check this is my common vector so i will check which is minimum and i will update my minimum to this common vector now after doing this what i have to do all known zero all non zero element from this common i will store it into my result and how do i store this is like a string i will convert here i am storing numbers and here i will again create make them string and storing it to my result so now let's understand the time and space complexity part so what will the time complexity so if you see here so the time complexity of our solution will be often because what we are doing is what we are doing here is uh we are running a loop for this and this will be run for we can say of l time l is the length l is the maximum length and here this will be of 26 which i can say of one and it is also i can say this is also awesome so now what i can say here is that my overall time complexity will be of n into l and what will be my uh this space complexity i can say my space complexity of 1 because i use here i use one vector which have the fixed size which is have the fixed size 26 so i can say it is my constant space so i hope you understand the time complexity and the intuition and source code if it helps you do not forget to hit the like and subscribe button thanks for watching
Find Common Characters
maximum-width-ramp
Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**. **Example 1:** **Input:** words = \["bella","label","roller"\] **Output:** \["e","l","l"\] **Example 2:** **Input:** words = \["cool","lock","cook"\] **Output:** \["c","o"\] **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of lowercase English letters.
null
Array,Stack,Monotonic Stack
Medium
null
1,603
In this video, we will discuss the problem of Design Parking System, its category is Easy. In this problem, you have to design a parking system in which you have to draw only two umpires, one is Ad and the other is Ad. These are the only two umpires which are there in your parking system. There are three types of parking in it: Big, Medium, Small. of parking in it: Big, Medium, Small. What will be given to you in the constructor tomorrow is that Big, Medium and Small. How many stalls do you have for this type of parking? Basically, how many vehicles of this type can you have in your parking system? Yes, then it will be added to you tomorrow in which we will give you what type of tax has come to us, it has come medium, what do you have to tell whether you can make it talk to your parking system or not, basically it Is the stall available for tax or not? If it is available then you have to make your stall one mine and if not available then what type of tax is there. Here we have big type tax here, medium type here and small type here. And here again due to big type, in this starting hole, what we will do is we will initialize all these stalls in our variables so that we can do them later and then they came to us, we had this stall available to us, so we have made provision that We can divide it and we made this stall zero, now we also have zero for work, we made it zero, now we did not have a lot, then there was no slot, now we saw how many stalls we made by doing it to you, then you This system has to be designed simply, which we have just discussed, these three will be big, medium and small. We have to store them. To store them, if we want, we can take three variables. We have taken a vector here and we have added our three variables in it. Medium and these three stalls have been stored, now we will add it whenever this AP comes and we will be given the car type. What will we have to check by typing it, whether we have the stall or not, if so then note it. Occupy it i.e. do one mine and return true. i.e. do one mine and return true. i.e. do one mine and return true. Can you advise me to attend the holes whether we have stall of this type i.e. if it is whether we have stall of this type i.e. if it is whether we have stall of this type i.e. if it is more than zero then do one stall on it and return if not. If it is 4 seater then what will be our time for it? We are doing three variables here and check a condition here too if off one will come then a will go. We are taking vector but how many types of loan do we have? What will be the size of the vector? If it is 3, then what will be the thank you gas?
Design Parking System
running-sum-of-1d-array
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor. * `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`. **Example 1:** **Input** \[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\] \[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\] **Output** \[null, true, true, false, false\] **Explanation** ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0); parkingSystem.addCar(1); // return true because there is 1 available slot for a big car parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car parkingSystem.addCar(3); // return false because there is no available slot for a small car parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied. **Constraints:** * `0 <= big, medium, small <= 1000` * `carType` is `1`, `2`, or `3` * At most `1000` calls will be made to `addCar`
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
Array,Prefix Sum
Easy
null
930
hi guys good morning welcome back to a new video again a bit Rand in the beginning I see a lot of people just in sake of telling the most optimal solution they forget to tell that it is not applicable to anything so in this we'll see very deep again we'll see two questions first is sabaris some less than equal to G has been asked by Facebook yendex Amazon okay Facebook 73 times is last in the last 6 months Google Apple Bloomberg like any company you can think of Goldman any company like it has been asked and you can see it's a lot and then that comes the question of today which is which has been okay sorry which has been asked by a few companies but still it's exactly same or if not I'll tell you what's the difference but it's more or less same than that of this question which is 560 okay you can do it by yourself Al exact same code you can copy paste I did the exact same thing cool so the problem simply says again we are doing right now 9:30 binary subar with some and we also 9:30 binary subar with some and we also 9:30 binary subar with some and we also do par 560 which isaris some equal to K so both simply says one thing that you are given again the only difference is that in the left side you are given a binary array in the right side you are given any array okay now let's see the PO statement you are given binary AR nums and an integer called as goal we have to return the number of nonempty sub arrays with a sum goal usually it's always non empty if we are asked for empty then okay it's just one add a one for empty also but the rest all will be nonempty now um and the exact same stuff is also told in the right side the only difference I told you that in the left side which is the problem which is of today it is saying that nums of I is either a zero or a one which means a binary array on the right side nums of I can be positive zero or negative again that's a plus Factor number can be zero number can be negative also if it would have been only positive I would have said it's exactly same as having a 01 but it's having a zero also okay AR what's the difference no worries no worri at all there's no difference at all let's see how we'll solve it again we'll come back to a very basic thing it just simply ask to return me total number of sub arrays who sum so I'll do exact same stuff I have an array I will find total number of subarrays my total number of subarrays are n square and then I will find the sum of those subarrays which is again o of n time so it will become o of n Cub the one basic for I can tell my interviewer method one is okay approach one is simple Brute Force now a bit optimized Brute Force we have usually seen that if we have a subar again we used to split okay firstly find the subar and then find the sum of that subar but I can just Club them up which means while finding my sub arrays which are of n Square I can parall compute the sum also of that subar how you can do it for example while you are moving your point moving your pointers in pointers you make sure okay I pointer J pointer so I'm saying as you have your in okay right now your sum will be one okay add a one by default your sum is zero add a one as soon as you are at J As you move on your J again for this specific subar the sum is one also and that's true as you move on your J earlier because of the basic root Force approach you had to go on to the entire subar but now I'm saying just simply add the component of J which means I'll only add my sum of two so now in the existing sum which was one I added a two it became sum of three so with this easily you can get a sub arism i2j again as you move on your J only add the G component so you will get the sub arism from i2j and that's how you can optimize it and get for all these sub arrays the sub aray some parall in N Square time also okay but still by the constraints still it will not work like neither for this nor for other problem again on the right side I have 560 on the left side I have what 9:30 now the left side I have what 9:30 now the left side I have what 9:30 now coming on back that how to actually improvise it no worries all always read the problem statement simply say one thing bro return me the total number of sub arrays whose sum so ultimately I am saying I have to find the subar sum which means I have to find again subar is a portion of an array so I have to find the range which means in a specific range I have to find the sum oh so ultimately my problem boils down to finding the range sum now we have a few algorithms okay we have Spar tables we have Fen Tre segment Tre but the basic most basic rain sum algorithm is prefix sum for us now if you know if you don't know what's the prefix no worries I'll give you a quick glance but you should be knowing what the prefix Su is because it's very important so prefix sum simply says okay keep the track again AR how would I know that I have to use a prefix sum or for sure you have not even studied and there's a high chance that you will not even study if you're considering only uh DSA if you want CP I highly recommend it's a very short crisp sweet algorithm um now coming on back how would I know okay if you don't have any updates and it's very simple you just have to compute do a pre competition and then find the prefix sum or find the range sum then for sure prefix sum is the best approach to find the range sum if you don't have any updates at all now the prefix some simply says one thing keep track and say okay my so far again prefix as in the starting part sum is the perfect sum which means one 1 two which is the sum is three okay 1 2 three the sum is six so it is how I'm keeping track so by default initially the sum is nothing zero then I added a one which means my sum became a one then I added one two then it became a three and then I added 1 two three it became a six and R so to compute this I have to get the entire row no row simply add this to get a this that's how you can simply compute your prefix sum which means prefix sum of I let's say I am at I it will be nothing but prefix sum of I minus one which is this Value Plus your nums of I which is this value nums of I that's how you can simply comp a prefix in O of end time okay when it is done how are you saying that it can give me the range sum bro if I ask you that you want to find the range sum from here to here then you can simply say Okay prefix sum of six minus prefix sum of 1 R in I is here J is here so you are saying that prefix sum of J minus prefix sum of IUS one is the answer yes bro that's how you come the perfect sum you can see 6 - 1 come the perfect sum you can see 6 - 1 come the perfect sum you can see 6 - 1 is 5 and you can see the range sum is five if I ask you any other range let's say if I ask you the sum of this range J is here I is here so my answer will be J minus IUS one prefix sum of J minus prefix sum of IUS one that's my range sum okay 3 minus 0 that's the r which is three okay so far you have got that okay you can easily figure out range sum which is the subar sum in O of One Time by doing a pre-computation by One Time by doing a pre-computation by One Time by doing a pre-computation by using a prefix so now you have got to know that okay your ultimate said this that you have to find goal or are not I know goal oh yeah bro you know goal and also you are at again if you're moving in you can move in any indexes okay as is as if I moving in I will be having my J okay imagine okay usually you move by I but as you saw my I is before J so something after should be moving right so let's say my J is moving okay which means if my J is moving I am at my J pointer so I know what is nums of J and I also know what is prefix of J which because I have precomputed this so I know my goal which is given in the question I am moving on my J so I know the prefix of j h I know this because I'm at this right now this is given to me I have to just simply figure out what is my prefix of IUS one no Aran you don't have to figure out what is prefix of IUS one because you already know because see prefix of IUS one will simply be prefix of J minus goal this is what you know your ultimate Mak your Mak was that you have to find out number of again remember your Tim name was number of sub arrays who some so I don't have to find like I can find okay this is the prefix sum of I which I require but I have wanted number of those so I'm just saying I wanted how many of those prefix sums are actually available how many as frequency okay I need the frequency to be there so what I'll do I will maintain the frequency of what prefix sums so I will have to maintain the frequency of perix sums so okay if let's say I know this is a perix sum of I one value which I need to figure out how many such per Su of IUS one are there these many number of sub arrays will be there for example let's say this was our nums I simply computed my prefix sum quickly you can simply see quickly again these are examples are built by me just because in the future I will tell you something great and that's the reason I had to build a bit examples from my end now goal is to okay great simply you will say bro if Aran I am at this specific index J I Need to Know Okay J is this so I know the prefix sum of J is this so what will be the prefix sum of IUS one value which I need to find this value what will be this value I know again it is a Al to this value I know it is two gold value was two so ultimately I'm trying to find prefix sum of IUS one as a zero so I'm saying okay if I am at this specific J I want to find zero but remember frequency of zero so how many zeros have occurred previously two zeros have occurred previously which ultimately indicates us that okay I will have two subarrays I will have these two subarrays and that's how you can simply keep on accumulating your prefix sum frequency okay firstly you will compute the some then or you can do everything parall also compute perect some parall compute the frequency of them also parall I'll show you guys that but yeah if a basic approach you want to take simply compute the perfect sum then it on the array again and then as you keep on moving keep on keeping track of the prefix some frequency and then update your actually okay at this specific J what is the frequency of prefix sum of I minus one which I require and that main number of sub arrays we actually be ending at J index cool the code again it's pretty simple again if you want to do a bit more dry run you can do it but I don't think so because it's a simple concept of perix sum which I explained above and then accumulating that with the concept of frequency that's a that's the major two concept which we will actually club with each other so again I will do it everything together which means I compute the prefix sum also parall and also I will be Computing my frequency also parall so I had my prefix Samar okay great I don't know there's one thing I saw today in lead code that some variables colors was being changed I don't know what's a bug but uh yeah that's a bug comment down below what you think could have been the bug in this case now um here I keep track of the frequency that frequency will be of perect sums now uh you will see that in the very beginning you always have a zero so frequency again frequency of zero will be one because zero is always there now I keep on going on to all the elements of my num as I land on to any element again increase the perfix sum value as you increase the perix Su value okay that's done that's great but as soon as you are at any specific prefix some value you have to go and find your prefix Su of I minus one so I'll go and just check okay bro prefix sum of IUS one that is nothing but that again that is nothing but current prefix sum minus gold current prefix sum minus go is the value which I'm looking for and that from that I have the frequency so I'll search in my frequency not map that prefix sum of prefix sum minus again this prefix sum is prefix sum of J which I was referring because I'm moving on to my J this is for J again I don't have to make a new are that's the reason I took as a variable right okay to reduce a bit space will not reduce like space complexity will still be open but a bit space will be reduced by this now uh I will simply go and find it if it is there great bro great if it's there then your frequency of how many times this value was there I will add that my number of times in my answer because that many number of sub arrays will be there okay then ultimately when this portion is which means the contribution of these zeros are added then okay bro for the future purposes this frequency needs to be increased for this specific two so I just said frequency of this prefix sum of J increase it by one because okay I have encountered two which is a prefix Su value so exact same stuff prefix sum of sorry frequency of prefix sum increase that by one and that's going simply trate and return back your answer in simply o of n time because you'll see it's a simple o of n operation everything is a o of n operation which is happening this Loop I'm saying now again this find is oone operation in an unordered map because we have used an unordered map which is a simple hash map so you saw the time we are using is orn but the space we are actually using is because of frequency we are using a space also of O ofn although we reduce the space by not making a prefix Samar but still unly we are making or using a space of offn now you might say AR this is the best case for sure again the exact same code will work for are this 560 which has been so many companies it will exactly work and you will be shocked to hear this is a best possible solution for your 560 problem best possible solution now coming on back um why you specifically said the best POS for 5 is this not the best for the this problem is it not the best um like did you think like did you ever think of one thing I never considered what could have been the value between these I never considered in this like in any point of time I ever asked you what could have been the value is it matter like will it matter or not I never asked you so now to think of that again the interview will say can you please improvise it now you are just shocked how you will improvise it no worries go back to the example so again that metaphor is danger for the folks again people on the YouTube and other stuff they will just teach you but it's a danger if you don't understand this how things work how two pointers how other again I not tell okay I have already spoiled but yeah if you don't know how to poin side all that stuff works you will end up wasting your time both in contest and also in an interview so your Basics should be clear that okay when what to apply that's what we're going to see now so again that's a danger for those who don't know and they end up applying anything so what happened in this case we saw that we simply had to find the goal of two so we saw that if we have an simple array then I can simply expand this oh expand this can you just remember something expand then shrink and then you'll see okay I just simply shifted this then I shrinked this did you like can you just recall of something okay you have a window in which you expand the window you shift the window you shrink the window oh that seems like a two-pointer and sliding seems like a two-pointer and sliding seems like a two-pointer and sliding window again uh both can be used interchangeably because it's a window and the window actually works on pointers so both can actually be used but I will say let's say 2.0 sliding but I will say let's say 2.0 sliding but I will say let's say 2.0 sliding window I can use both of them mean same so okay that's a window sliding Windows more of the window remain same but two pointer say windows can be sh or increased so now we can EAS see okay I can see something I can use two pointers and I can say okay this is the window for me this is the beginning window for me again let's erase it this is the beginning window for me I is here J is here I know that in my two pointers or in the sliding window I keep on increasing my J again that's a standard concept that if you had to use a sliding window or two pointer so either uh you increase your J at every step and then you can keep on shrinking your eye so that you can actually see how many number of such subarray are there so maybe I can just I know that okay I still have the capability to increase my J so I'll have my I here and J here okay then I try to increase my J again but then my sum became a three Ah that's a pain for me it should not so I'll just try to shrink okay if I try to shrink then my array will be become in like this again J is ended so for sure you will try to again maybe shrink okay again maybe shrink then IJ became like this now so far people are thinking okay I got it's a sing window I simply apply it bro you missed a lot of things there are many stuff happening here and you should be knowing when and what to apply although I have told a numerous times on the videos that when to use two pointers or maybe like I can again I'm actually using sliding window here but again remember sliding window is saying the concept that the window remains same you just keep on moving two pointer say Okay window can shrink expand all that stuff usually SL window concept is more used in let's say rabing C building hash and stuff sliding window is more of window remains same but two pointers window can shrink expand but both of them cannot happens has hly it means shrinking then shrinking expanding that's not s that then it's a simple two pointer sorry then it's a simple Loop for you happening now coming on back that I have already told that in a two pointers how we usually think of is okay if things are increasing again when I say things I mean it can be either array it can be either sum it is what you want to find the answer for or maybe it's a hop in between for example I'm just thinking of a number I just want to apply two pointers on a number maybe the numbers are increasing maybe I want to find the sum of them for example in this case maybe the sum is increasing Maybe the sum decreases and then decreas from the end so maybe it is decreasing and then increasing so in the cases when you think it increases or decreases or increases decreases in that cases it's highly likely that you will apply two pointers now what you we what you mean by thing in this case I so you can simply see the thing what I meant is was your sum for you your ultimate M was to find the sum so for sum you'll see the prefix sum as you saw also just to say the prefix was 1 3 and six so it is increasing har in but elements can be zero also here okay bro that's true it can be then same also like okay it can be 1 3 and six so okay when I say increasing I mean non decreasing always okay right okay make sure now and how to use two pointers in these cases simple we know that we have a window remember this fact we have a window I and j i and J is always later on like that's how I usually do it you can also keep I later on now G moves V to simplify stuff usually have a template of two pointers that again that's a two pointers in which we are actually compressing and expanding so while J is less than n is the size of the window then at every step no matter what you will increase your J that's a simple template and but okay which means we at every step I'm increasing my J but I'm saying that if what whatever condition satisfies for us that's good I will keep on moving as it but if some condition is not satisfying which means in this case this condition is some so if I'll keep on moving on j some keep on expanding that's true it will but as soon as it becomes more I have to start shrinking stuff so it is a simple case that while your any condition here in this case it was a sum if the sum becomes more than the goal then bro please keep on shrinking which means you will just keep on bringing your eye this is a basic template which we use for expanding and shrinking this is usually two pointers which we use now in this case you can simply see that your G always increases and then your I moves when you're when you actually have to improve like decrease or increase your thing again I'm using a thing word not the actual thing because it is generic so I'm just saying expand I and compress sorry expand J and compress I expand J compress I is compressing my window J is expanding my window and this to be simplified again you can actually implement it in many other ways but just to be on the safe side and just to build a template out that we don't have to apply our minds much we just usually have template okay at every step my J will increase and basis of the condition on the basis of the condition that okay if my condition has violated which was the sum for us if it has violated then okay please increase or basically please compress your eye now for sure we will again that's most important problem is for us is 560 which was having that the elements sorry the elements can be negative also because it has so many companies so that's so it's a prior problem for us like priority so what I will do is I will just try to think okay bro let's try this sliding window because okay it's a sliding window which means okay it's just using two pointers so for sure I can optimize my space I remember my space was being used as o of n time will for prob be it can never be reduced but still maybe space can be reduced so I might end up thinking I will apply two pointers here that's great Aran but you know the hint I told you it's not be applied let's see why I'm why I was seeing it again that's for when I had negative elements also so what will happen in this is that you have your I you have your again I took any middle okay currently your state is in now your current sum is one you can see - 1+ 1+ current sum is one you can see - 1+ 1+ current sum is one you can see - 1+ 1+ one it's one now if I ask you bro you are saying okay if I go by your template Aran if I go by your template you will say it every step J will increase okay and then if your sum becomes more then your like you will say okay your IE will actually increase which means you will compress okay but in that case it was fixed that my J will increase okay then my thumb becomes more then I will compress my eye okay here you will see my if even if currently my sum is one for sure which is lesser than my gold so you might end up thinking iren for sure which is it is less so it is obvious that I will increase my J so what you might end up happening is that okay your I is still here you will increase your J you can see my sum increased now my sum in nothing but three some increase with j and that's what was happening also okay bro great then you might end up saying okay my goal was to so I just end up decreasing my eye I might end up decreasing my eye which meanor increasing my eye which means compressing my eye so if you compress your eye okay compressing your eye you see what happened your sum earlier was a three now your sum became a four compressing your ey increased your sum oh Arin which means Arin maybe it is a case because um I was having I was compressing wrongly so what I will do is I will compress first earlier you were saying okay expand always put the J that was what you were doing so maybe I will just go reverse what I will do is I know this is a window so I want to I just want one thing okay I know one thing that maybe after compressing my window like my sum will increase so I just compress okay now my ey is here and now as you can see my Su also increased it has become a two you will end up increasing your eye just in the case you thinking maybe your sum will increase now but what if it is minus one you increase your eye your sum will again decrease so now it is super like confusing that okay you should shrink or you should expand because in expanding also you can increase your sum or decrease your sum in shrinking also you can increase sum or degrees of sum so it's a bit both are confusing that is it good to expand or it is bad to expand or shring anyways both will cause confusion so no way I will end up in a confusion okay I should expand shring expanding both on inj anything can happen on both sides so it's of no point I will end up having of n Square algorithm if I use sliding window in this so you saw that I cannot use again just to be just to give you a summary because of negative numbers I got to know that my sum will actually end up decreasing or increasing it can do it can go anyways as long as I move my eye or anyways the sum can either increase or decrease that's the reason I cannot apply my two pointers because I know my graph it can go it cannot go like this it should be consistent so if my sum will decrease increase then for sure I can never apply my two pointers so I got to know that because of the negative number only I cannot apply my two pointers here okay no worries bro let's come on to the existing problem because in the existing problem which was binary samaris we know the numbers are binary so numbers are not negative maybe we can apply RN R maybe we can apply two pointers here let's see again I'll take a very normal again you will see in every problem I always land on to a mid example because I don't go from very scratch because there's no time to go in from very scratch and then take a mid example always think of a mid example I took a mid example I again this is example which I made now uh my goal is to okay so now you will see um let's usually you say that okay always expand oh bro the goal is two your Su right now is also two so it's good right it's good so you should not increase rather you should ex like string compress the window so that this will be the new window size and this new window again please make sure to listen very carefully because it can be a bit confusing so right now your window is this now I'm saying considering I go by your fact which means your inance Iran if I go by aran's fact Aran always increases his J okay always increases J so now the window size becomes this still my sum is two oh my sum is two now I have the ability to compress it so I will do okay now my sum is two which is the good sum for me so maybe I can try compressing it okay compress it okay now still my sum is two I'll again try to compress it but I cannot compress it so maybe by so far I saw okay if I increase my J first then I have a chance to compress it then if I increase my J first so my possible windows or possible subar which I will give you as an answer will be this one and this one remember this fact so I will put this one and this one remember this fact and again no other subar was given by you to the answer but if I had choosed to compress first if I choose to compress because still I know the sum is two my goal is two so maybe I can compress it right now also right okay I'll compress it first So my answer the answer which it gave is it gave me this one then you might end up saying okay I now I cannot compress I'll try to expand it okay I'll expand it so this one so this is the answer which you end up giving your solution even if you follow my way which is expanding first J or if you say okay no I'll compress my I first so you end up giving this as an answer and this as an answer so you saw that this one the blue or like the pink one which I highlight okay it is covering but then if you shrink first then you will get the top one if you expand first you will get the bottom one and you can do one like either you can do either you can shrink first or you can do expand first anything you do one thing you will miss oh which means in simple two pointers cannot be applied here we have to use some other magic and that's the reason people just tell you oh it's a simple to points apply it bro it is not that simple now we have got the issue okay we if we start by shrinking then if we start again let's come back okay let's erase this if we start by shrinking I hear J here if we start by shrinking then either my sum will same my new sum because you saw my right now my sum was two if I shrink it my sum Still Remains Two or if it would have been a one so if I shrink it my sum would have become a two like if right now the existing sum would have been three so the new sum would have been become a two so I saw that with shrinking I either my sum will remain same or my sum will decrease my new sum will either remain same which means equal or my new sum will actually will be less and also the same will go for vice versa that if I expand either my sum will increase or my sum will remain same some will remain same and that's the fact this equal to is only possible because of zero as a number if zero would not have been there we would not have to even think of any of these conditions you have simply applied simple two poters simple expand simple compress that's how you would have solved it but now it is equal to which is causing an issue but still it is not that confusing as what we had previously that because in earlier case when we had negative numbers also expanding or compressing anything whatsoever you do you will end up having something different but here in this case I know bro it is either expanding or compressing which means either my area is like this or straightforward going up then my sum is this or going down that's how things are working okay great so now I got to know that we can't directly deal with equal to sum because I know okay my new sum it can be less or more so I can indirectly deal with less than equal to sum or more than equal to sum so I actually dealing with less than equal to sum or more than equal to sum and not directly with equal to sum I could have tell if I had only positive numbers so I cannot do that I will actually have to deal with less than equal to sum I what you mean by that is that okay so as to find the number of sub array with the sum equal to goal you will just simply go and ask bro question bro give me the number of subar with the sum less than equal to goal but you remember you want to find equal to goal so then you can simply Subtract with the number of sub RSM less than goal Arian what do you mean by less than goal like I only know for less than equal to Pro you can convert this less than goal to nothing but some less than equal to goal minus one so this became exactly like this it's just goal has just reduced by one so I can simply make a function let's name the function at most you will see why the function name as atmost but let's say I Nam this function I can simply call okay nums is my input array and now my goal is this specific goal again remember this function should return number of subarrays with some less than equal to your goal then again you will find and go same function with the nums and saying goal minus one which is nothing but less than your goal now let's see how this function will work for us again remember the aim of the question like aim of the specific function number of sub the Su less than equal to goal so now right now when your in are very at the beginning you know the sum right now is one but answer is the number of subar less than equal to your sum how many are there right now one are there okay this is the one is the number of Saar with the sum less than equal to your goal and I have showed on the right side what that one subar is for you to know that okay to just help you visualize now for sure my J will move again exact same concept J will move j will move I just simply compress it down now okay J Will moves okay J was zero so some will still remain same but my answer I increase by plus two is two more sub is added the sum whose sum is less than equal to your goal and the two sub is at one is Zer and one is 01 again remember the fact one as the subarray was already there okay now your J will again move again your J will keep on moving at every step no worries so your sum will increase to do again your sum is less than equal to K so your answer will be I'll add to plus three is saying 1 0 and 1 0 1 three subar is added three so again my J will move answer will my sum will still remain same again I'll simply add again now as I was showing you the numbers now I showed you what I'm actually adding I'm adding J minus I + 1 that's simple okay adding J minus I + 1 that's simple okay adding J minus I + 1 that's simple okay 0 1 2 3 so I'm adding 3 - 0 + 1 so I'm 0 1 2 3 so I'm adding 3 - 0 + 1 so I'm 0 1 2 3 so I'm adding 3 - 0 + 1 so I'm adding four sub which is 0 1 0 and 1 0 these four I'm adding when I'm at Che so this is the number of which I'm adding now I what if you increase your J much more okay as I increase my J my sum became a three as soon as you know okay if the sum became more bro do one thing bro simply compress your ey simply compress so while my sum is more than my goal I'll simply compress which means reduce my sum and increase my I and that's how compression works and that's how you can simply apply your simple logic of two pointers here itself so what will happen in the code ultimately firstly you have your i j answer sum and your n while your J is less than n again standard template of your simple two pointers while your J is less than n ultimately in the end remember increase your J everything will go in between as you are specifically on the J firstly add the contribution of J because at every step your J is moving add the contribution of J now what if your sum became more then your goal bro simply compress the array I'll keep on compressing the aray make sure to also put this condition because if you end up compressing a lot and you surpassed your eye then you will end up even increasing it either put in the condition that I is less than n or put in the condition that I is less than equal to J like put in anything so that your I should stop after a point cool um then I'll simply decrease my sum because I'm increasing my I and then I'll simply keep on moving compressing my eye simple concept and then answer plus is equals to j- I + 1 which is the contribution at to j- I + 1 which is the contribution at to j- I + 1 which is the contribution at the G index number of subarrays which I have added at the G index and that subarrays is all these subar is whose sum is less than equal to K because after this Loop any sum I get will be the sum Which is less than equal to K less than equal to my goal and simply ultimately return the answer again that's I called this function firstly for my less than equal to goal and then for my less than goal which is nothing but less than equal to goal minus one so this difference will give me equal to goal value and that's how I can simply say my time because I'm using simple two pointers my time Isn and space is one because I'm not using any space but remember this is only applicable when the numbers was positive and zero if the number would have negative it is not applicable in that because we saw we it will end up giving us o of n Square solution rather than o of n which will incre the time and that we don't want cool I know this video has gone bit long but I wanted to make you understand how to think of so that you don't waste your time on YouTube people will just tell you do this they will not tell you when to use the two pointers and when not which will actually hemper and you might end up thinking in an interview oh Arian taught us the similar problem and I can again apply two pointers here also sorry uh yeah s here also and 2. it will not be applicable you should be knowing the basics of when to apply what cool thank you so much goodby take care bye Cheers
Binary Subarrays With Sum
all-possible-full-binary-trees
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0,1\] \[**1,0,1,0**,1\] \[1,**0,1,0,1**\] \[1,0,**1,0,1**\] **Example 2:** **Input:** nums = \[0,0,0,0,0\], goal = 0 **Output:** 15 **Constraints:** * `1 <= nums.length <= 3 * 104` * `nums[i]` is either `0` or `1`. * `0 <= goal <= nums.length`
null
Dynamic Programming,Tree,Recursion,Memoization,Binary Tree
Medium
null
42
Loot Hello Viewers Welcome Back YouTube Channel Score Today Will Be Solving Tracking And Water Before You Start Prepare YouTube Channel Subscribe And Hit Notification Force And Latest Update In This Question In The Given Away With Certain Parts Example 06 2012 Total Arm Hole Example Subscribe Liquid water contains two three one two three idiots so 6 subscription this is this universe minimum of local maximum sleep will win this question is will be hydration from inductive one from near soaked left right left maximum Android maximum and minimum of friends maximum subscribe Video Total Subscribe Button Maximum Subscribe Our Face One Chittor Se Left Maximum Mirchi Nothing But One Drops Right No Maximum Is Nothing But 333 For Will Be Taking Minimum Of This 2 And Will Be Operating To Total Its Position Where No One Will Spread The Deficit In Wway Top 10 Water Ko Subscribe Button subscribe to subscribe our Ki Tum - 52 - 03 But One Improved Total Voters Ki Tum - 52 - 03 But One Improved Total Voters Ki Tum - 52 - 03 But One Improved Total Voters And Continues It's Nothing But One Should Move Into Position Top Maximum Too Left Is Nothing But Does Right Is Three Layer Will Take Minimum Of This Is Nothing but you will be selecting it was not good subscribe three minimum per 10 all the best all want to subscribe the soldiers were given a factor height show will just make a variable end for convenience and science main video singh bisht pailin for that so first will Make Available Total No Record Of Sex A Voice Mail Control Volumes Milk And Milk All Difficulties In President And Fennel Subscribe 508 121 Is All The Best To According To One That I Plus So Will Be Calling Left This Hello How To Fetch A Jhal Was Ki no will be running over lokpal starting from ki love sad song 0 way to i tomorrow morning meeting amar maximum set jo left equal to a minimum of left arm on do jhala height offer ki neeti do english se padhare light show willow Cutting and Write as a torch light of I Tags English Meaning of Votes Rights Will Be Hydration Will Start From I Plus One That All The Best To Add That I Will Update On Right To Jhal Ka Apart From Pradesh I Will Be Adding To Total In Which Ko improve ki sampras ko minimum of me left kumar 8 - till height me left kumar 8 - till height me left kumar 8 - till height ki and where present at right under current situation ki undercurrent hydration point will be cutting diet in veins open to 4 plus media platform tight - site is alarm set ireland uk the song of me successful ran jhal hai so lb max not minimum cosmetic gender maximum ko whatsapp mein good night mid day meal jhal gather problem air force with a meeting minimum but acid maximum acid discus throw ki mujhe time tak hoti jhal ki they stand for watching my video Then lighter video subscribe and notification belt thank you for watching
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
234
That welcome too much expressed in the chair and going to explain about fundamental list superman tourist places contract employee in english playlist begum elements humble subject vision spelling and notes the fair will create unrest north to turn the M.Ed value turn the M.Ed value turn the M.Ed value het the fifth month man tech ke Unclean Work Fuel And Secondarily E The Patient Tag Archives 153 Condition On Hair That Welcome Page Will Appear Tunnel That Dental Book York On This Site Post Templates Hair Oil Yet Another Love U That Bike Hello How Did Not Equal To And Null Hindi S M Getting Next People Not Lose Everything Under Lokpal Bill Account Shift I Have Just Done Value Satish Not Equal To Bank Statement Of Proven Strike On The Day Of Return For Him That A Legal Advisor And Have Written In The Statement Proof Of A Noble Area Harassment And A That This expectation is newly submitted yes thank you
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
91
hi everyone welcome back to lead coding i am your host faraz so let us continue solving some more questions on dynamic programming so this question decode ways is a really famous interview question it has come so many times in interviews and this question is going to teach you something really important it will teach us how to use recursion and then it will teach us how to use memoization into recursion and then convert it to the bottom of dynamic programming so we will go step by step first of all let's understand what the problem statement is so basically a is mapped to 1 b is mapped to 2 c is mapped to 3 and so on till z is mapped to 26. now we are given some digits and we have to tell the reverse mapping of this we have to decode that so for example if we have a j and f the corresponding to this the digits will be 1 for a for j is 10 and for f it is 6. now actually we are given this part and we have to generate all the possible decodes of this now one way obviously is this we can treat them as 1 10 and 6 and then reverse map them so it will be a j and f but there's one more way and that is to consider one and one together one and zero together and six so for this the decoding is k j and f so we have to tell for a given digits for a given sequence of digits how many d codes can we have for a given set of digits how many d codes can we generate we have to tell the number okay so let us see what are the possibilities are here with us i should take the same example there is 1 0 and 6. now for this given sequence of digits what i can do when i have been given this entire sequence i am at the beginning so there are two possibilities with me the first possibility is to replace this one with a and then generate the d code for the remaining sequence so we can consider a here and 1 0 6 corresponding to this i will generate all the decodes of course with the help of recursion we don't have to do anything here we just have to call recursion on i plus 1 that is starting from this point clear okay so this is one of the possibility now what is the other possibility is to take these starting two ones together that is 11 and corresponding to 11 we will be having k so we have k here and we should now call recursion on this part now for this part our i should become i plus 2 okay it should point over this place so we'll be left with 1 0 6 and we have to generate all the d codes of 1 0 6 with the help of regression of course okay so whatever decodes we have corresponding to 1 0 6 we are going to append that in front of a and whatever t chords we have corresponding to 1 0 6 we will append them at the back of k now if we add both these options we will get our answer so we only have to do two things the first thing is to pick up the first number okay and then call the recursion on remaining part and the second option is to pick up the starting two numbers and then call recursion on the remaining part and then add both these together so that is what we have to do now let me just show you how does this recursion work actually you won't have to do this every time because in some time you will have enough practice that you won't have to think that how is it working we'll just write these two steps and that's it but as of now as you want more clarity as to how this recursion work i will just explain it to you so here again we can either pick the first number so i will replace it by a and then call recursion on the remaining part that is 106. okay or i can take the starting two numbers that is going to give me k so if i pick up starting two numbers it's going to give me k and i'll call recursion on the remaining part now again corresponding to one zero six what i can do is i can take the starting one number so if i take starting one number i will replace it with a and then i will be left with 0 6 or i can take starting two numbers that is 1 0 10 could be replaced with the help of 10 could be mapped to j so j and the remaining number is 6. now if i want to expand this one if i expand this one i can take the starting one number that is 0 but i cannot replace 0 with any of the alphabet as we can see here we are starting from 1 and 26 there is no space for 0 so from here i will not be able to proceed so in this case simply return 0 y 0 because there is no way to generate such a decode all right so let us look at the right hand side in the right hand side what do we have we can take the starting two numbers that is zero six again for zero six we have no mapping so we will be returning zero from this as well so zero from both these places so zero will be returned here zero plus zero is zero it will be written here now let's see what is the right hand side this one so here we have 6 and 6 could be replaced with f so we will be having f and as we are done decoding the entire sequence because now we will be left with nothing as we are done decoding the entire sequence we will return one from here now one will be returned from here from the left hand side we got zero from the right hand side we got one so zero plus one will be returned back to here now again using the same procedure we cannot decode 0 6 as we were not able to decode it here itself so we will be returning 0 from this place again 0 1 is 1 so 1 will be returned here okay all right let's move on to this part if i want to record one zero six as i saw that one zero six could be decode into one of the ways that is j and f so i can return simply one from here i will not write all these steps such as a then taking 0 6 and then taking j and 6 will be left so actually these steps are same as this i will not write the entire thing i will simply return one from here so 1 plus 1 is 2 so 2 is the answer for this i hope you understand this if you don't understand this just hold on a minute i will just tell you how to write the code is really simple so what you have to do you have to create a function a recursive function and you have to start with i from 0 and then have a string s passing it as a reference again you can see now as i told you if i am able to exhaust the entire sequence if i am able to reach the end so when i is actually equal to s dot size in this case return one because i decoded the entire string otherwise i will create an answer and i will have two options either to pick up the first letter so how can i do that int option 1 is equal to s of i minus 0 so this is actually going to give me the integer of the first digit okay all right now let us take these starting two numbers so if for that i'll have to check this condition if s dot size is smaller than if i is smaller than s dot size minus one then only i will be having two numbers at least two numbers left in that case option two is equal to option one multiplied by ten plus s of i plus 1 minus 0. so i have to convert it into integer i hope this step is very clear option 1 into 10 plus the next number okay now if option 1 is greater than 0 in that case answer plus equal to help of i plus 1 s now checking the conditions for option 2 if option 2 is also greater than 0 and option 2 is smaller than or equal to 26 now in this case answer plus equal to help of i plus 1 return answer now let me just call this i hope these steps are very clear to you actually i'm just making these two integers option one and option two these two integers are the integer representation of these numbers so for this example option 1 will be 1 and option 2 will be 11 okay now i will check the conditions for both of these if option 1 is greater than 0 then i can proceed i can add this into the answer if option 2 is also greater than 0 as well as option 2 is smaller than 26 then i can decode it okay help of zero comma s and i can simply return it from here let us just try to run this and see if there are any compilation errors option 2 is equal to oops option i will have to create the option 2 is equal to option 1 into 10 plus s of i minus okay actually uh this there's a problem the problem is so the error is because of this i have to do i plus 2 instead of i plus 1 i'm jumping two steps aha so here the condition is when i is equal to s dot size but in some cases i might be equal to s or size plus one so in that case this condition will not return from here and it will simply start executing these steps which is obviously wrong so for that i is greater than equal to sort size then i will be returning from here also i should initialize this option to as zero now i am getting correct answer let me just try to submit this okay so i was waiting for this error now why am i getting this error so the reason is simple uh we had 0 6 now for 0 6 obviously there is no possibility because we cannot break it down into 0 and 6 neither can we have 0 6 so both these possibilities cannot be mapped back actually there is no d code for 0 6 and there is no decode for 0 and 6 but why are we getting 1 as the answer because when we took option 1 as 0 and we calculated option 2 was actually calculated 0 multiplied by 10 plus six which is equal to six now option two became six okay in this case in this example our option two became six we can see here so let me just print it out option two it became six here see it is six so that is why this condition is being satisfied but we should also check that option 1 should not be equal to 0 and option 2 is greater than 0 so these are the conditions that we need to check ok let me now submit it and hopefully i will be getting tle this time so the time limit is being exceeded why because we will be having so many repetitions in this so as we can see if we have 1 and so on so what we can do is we can break it as a and then one or we can break it as 11 that is k and one okay again we can break it as a and 1 and then we can break it as k 1 yes now we will have to compute this again but this is also being computed here so these are the reputations again we will have a lot of repetitions here so whenever we get reputations we try to store them using dynamic programming what is the state of dynamic programming the state is i actually i is changing in these recursive calls so we just have to memoize this i so for that i will create an array of size 100 because i can go at max still hundred and dp is of size 100 let me just initialize this with something like why i'm taking 101 because of the safety so i want to initialize this dp mem set dp minus 1 size of dp initializing this with -1 now here if dp of i is not equal to minus 1 then return dp of i otherwise before returning the answer we should store dp dpfi so now it is getting accepted so you should not make any global variables so that is why we should not make dp over here we're just making it here now if we if i'm making it here i should pass this into this function and start dp and dp here and here see so this is how you solve dynamic programming questions you first come up with a recursive solution the regular solution was very simple we just have two things to consider the first one was to either pick up the first character alone the second thing was to pick up the first and the second character and then to add both of these this was a recursive solution now as we saw in the recursive solution there was a lot of repetition so we just used memoization now after the memorization if you want to convert into the bottom up dynamic programming you can do that as well let me just show you how you can do that so when i is greater than s dot size the answer is 1 that means dp of let me just make n here int n is equal to s dot size so dp of n plus 1 should be equal to 1 now n could be 100 so i should make this dp of size 102. dp of n plus 1 is equal to 100 dp of n is equal to 1 because anything that is greater than or equal to s or size should be 1 then i will start looking at another conditions so to get the answer for the ith state i need the answer for the i plus 1 in the state and the answer for the i plus 2 state so it means that i should start generating my answers from i is equal to n minus 1 i greater than equal to 0 i minus to generate the answer for the if state i need the answer for the i plus one state as well as the answer for the i plus two with state that's why i am going backward now um i should create in option one this is s of i minus zero or maybe i should just copy this entire thing over here paste it then having both of these steps over here now instead of calling this recursive function i should just replace it with dp of i plus 1 and remove this okay and here instead of help of this dp of i plus 2 other things here this answer should be replaced by dp of i plus is equal to this and i should put 0 inside this entire dp so for that i can just name set it mem set dp 0 sizeofdp and finally what should i return as i was returning this help of 0 so i should return dp of 0 no need to write this and we can just get rid of this recursive function now this is bottom of dynamic programming let us see if it is working oops there is some issue option 1 option two what's the problem d okay dp it is giving us correct answer it is that simple to convert it a top down dynamic programming to a bottom up you just have to paste the entire code over here and then just change the recursive function to the state of tp that's it so this is it for this problem if you want more such content in future make sure you hit the like button make sure you subscribe to the channel and hit the bell icon so that you can get the notifications for the latest videos thank you
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
1,743
hey everyone today i'll be going over leak code problem 1743 you restore the array from adjacent pairs so we have all this junk but it's actually really simple so basically we're given some adjacent pairs array like this and it's really just edges so node two is connected to node one uh node three is connected to node four three to two so and forth and so forth we have to come up with an array and restore the array from these edges so if you can look here we're given this and we can come up with this because one is connected to two that's true here two is connected to three uh that's true here and three is connected to four and that's true here um so a couple things to note is uh this is always going to work out and it's always going to be a valid adjacence pairs which means that uh our result numbs is always going to be plus one length of the adjacent pairs and they actually say that right here um it's guaranteed that every adjacent period elements numbs i and num psi plus one will exist in the adjacent pair and it'll say that adjacent pair is size n minus one where the uh resulting array is of size n so a couple things we can do right away is we can have our result which is just going to be a new n of adjacent pairs uh dot length plus one uh just one more length than that uh the next thing we have to do is kind of like build a graph uh to connect these like edge nodes basically so we have to build a graph structure and what we'll do how we'll do that is we'll just have like a map of integer to a list of integers and just call this graph and this will be a new hash map and we'll just build it up so we'll go for it edge of adjacent pairs uh we have to like connect them so we have to reference the first node with the second node and the second node with the first node so let's actually do that so we'll get our default so graph dot get or default the first edge node and then a new empty array list if it doesn't exist yet that's why we have to do the getter default thing um and then what we want to do and we'll call this list uh we want to just simply add the other edge because it's now enabled to that edge right and we have to put it back in so let's actually go uh graph.put so let's actually go uh graph.put so let's actually go uh graph.put edge zero to list and let's copy this down because we have to do it for the other node here and let's just go ahead and go like that and let's change that okay so now that we have our structure here we actually have all the nodes that are connected to each node which means all we have to do is start a source node which is really just the node that only has one neighbor every other node will have two neighbors right because if we actually look at this output here like so we'll see that two has two neighbors one and three has two neighbors so we can either start at one and four order doesn't matter in this problem if you look if there's multiple solutions we can return any of them the pairs can be in any order so really we just have to find a source node now so how we do that it's the one that has only one neighbor right so let's do a stack for dfs and we'll have this just be a stack new stack and uh we know that we'll also need this for dfs so we'll just have scene which is going to be a new hash set and not seen but set and then what we want to do first is we want to find uh the source node right so we're going to actually go through basically uh for each entry which is going to be an integer of list of integers for each entry in our graph so an entry set here basically the one that has only one neighbor right so if and let's call this entry here so if entry dot get value which is just the list that it's mapped to uh dot size is equal to one that means it's a source node so we can just put this in the stack right off the bat and we can go entry dot get key which is like the starting node and then we can just break and then next what we want to do is we want to iterate through the stack so while not stack is empty uh we can get the curve so we can go stack dot pop uh we're going to put this in the scene so that we don't uh do a cycle and we're going to see add curve and we're going to go basically uh through each child so we're going to go for it child or neighbor you could call it uh let's actually call it neighbor instead so for each neighbor in graph dot get curve uh let's check if we've already seen it so if not scene dot contains key neighbor uh we can add it so we can go stack dot add neighbor okay so everything's good here uh the thing is we're actually dfs into this but we're not actually filling up the res so what we actually want to do is let's have like some variable here to keep track of where we are at in our result array so uh once we do this once we get our curve we know that this is the current one so we can go um res i and we can also increment it off of that we need to occur and then at the end here we can just go ahead and return res and then i'll re-reiterate some things that might not re-reiterate some things that might not re-reiterate some things that might not make sense once i run this actually contains not contains key let's run this and yeah it looks pretty good let's run all the test cases make sure it's fine before i talk and uh let's submit it so let's see what we got here um so it's 68 66 that's actually pretty good um so let's just reiterate like exactly what happened here so basically we treated these adjacent pairs of edges we built a graph out of them so we mapped every single node to its list of neighbors then we found the one with only neighbor one which will be a start node and that's because if we actually look at the array we're trying to build the start node should only have one and node should only have one neighbor as well just like an array then what we do is we add the one to the stack that only has one neighbor then we go through the stack just normal dfs you could do this recursively it doesn't matter and we increment some i and we go in order in dfs and we just fill this array so we start at the source node so we know that's the start of the array and then we go to its neighbor that's the next one then we go to that neighbor and then that's that we do this not seeing contains thing because we don't want to have a cycle or anything or add a node we've already seen because each one has actually two neighbors so we don't want to go backwards so yeah uh talking about time and space complexity uh time is actually uh just o of n uh the reason being is we're actually just going through every single adjacent pair an adjacent pair is actually bound to the length of the result array so it's just n uh we just go through that we build it once then we do a stack thing here but since we're actually keeping track of the ones we've seen we only actually process each node once so it's really like 2n which uh results to n and then uh so there's a time a space is actually o n as well for the same reason because we actually have a map and we just fill it up end times with the different nodes so yeah hope this made sense thank you for watching
Restore the Array From Adjacent Pairs
count-substrings-that-differ-by-one-character
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Hash Table,String,Dynamic Programming
Medium
2256
199
going to show you how to solve this legal question 199 binary tree right side view and it's a median legal question so given root of a binary tree imagine yourself standing on the right side of it return the value of the node you can see ordered or from top to bottom so a tree look like this in example one what the result that they wanted you to return is the most the right side view so basically the output you can see you want to get is one three four after running the function that you write and then the second example is one three um like one three the left side is no and then the result they want you to return is one three and uh if it's empty just written uh empty tree and the song constraints here and this is a uh interview question asked by um facebook 112 times in the last six months definitely a great question to practice on so if you think about this question return the right side view is not that tricky but the problem is that if they want you to return something like um like a tree like one and then if the left side is two and uh three the most the right side of course is one three right the difficult part is that if it's the most right side view on the level it's not on the most right value let's say the child node of two has another child node of four in this case the most the right side of view although the four is on the left side the most because the four there's nothing on the right side so the most the right side is the most the right side view so in this case that the answer they want you to retrieve is actually one three and four in this case if you imagine a tree that all the connections are connected and this is a question can be solved by both uh breakfast search and developer search but relatively speaking bradford search may be a little bit easier because bradford search is more of the level traversal instead of like that for search but breath depth research you can also do it easily by traverse to the end and you can easily do it recursively if you do i'm gonna show you how to do both ways and if you do using the buffer search what you can do is um you basically append this value to the queue right and then when the cue exists what i wanted to do is i want to pop the um most the right value so like uh like a q let's say i added the or the one to the q and then i want to pop the most the right side of value which is one after i pop this value i want to iterate through each length of q when i do that when i pop the one value after i pop it if the child exists i when i pop the one i want to add all its child right when i add a child if two i want to add it like this two three which is basically the next level and then what i wanted to do is i want to write the uh last value in the queue to the end result right so basically something like this and i want to make sure that i write a 3 to the result so previously i've already wrote one and i want to write three to this result and then after that i'm going to continue to pop and add pop the queue and add it to add its child as well then when i'm going to pop the two right i'm gonna add four because four is the only childhood there's nothing on the right side as well and there's nothing else left so then i'm gonna add four uh i'm gonna add a four because four is the i wanna add a last value from the queue to the result so then it's one three four right and then i'm pop the la uh three does not have any child and then i'm gonna pop the four and a four doesn't have any child either so in the end that the queue is empty then you have the result as one three four and then if you want to do the developer search that for search is that um you want to you can easily do it reversely uh recursively and then if the you want to involve the leveling right because this is level zero when the base condition is the length of the result equals to the leveling then you can start appending the result so let me write it for you uh lab the length of the result if length of the result equal to the leveling and you can start append the result the reason i'm saying this is because the length of the result at the beginning is zero right and the level started from zero also that's why we can simply just append the one to the end result first and then when you uh do this recursively and you want to run the same dfs function on the left node and the right node the tricky part is that you want to start from the right node is because you want to get the most the right view so for uh the child of one in the no right side of the note you want to when you run dfs you want to run this guy that first search first because it will ask you the right value if you run this first and when the length of the result under there's a one um because you the result the length of the result the second time when you run it the length of result equals one right and now this is level one zero here and when you go to three it's level one so that's why you're gonna append the result three here so you wanna make sure when you run the default search you wanna start the right node and then you run the left node that's the only tricky part you're gonna pay attention to and then you just call this that for search function and then you will be able to get the result that you want i'm going to show you first how to do this in code for the buffer search and we want to rule out some uh edge cases if not right and i want to return no and that's one of the example that they give to us for the breakfast search i want to use a i want to implement this queue by using oh can type by using a dq here so that i'm going to first append the real value to the dq before i start and then i'm going to assign a result basically what we need to return here to our list array here so i'll say wow q right and i want to start append the value i append in the example that i give to you is that i always append the most the right side of the value to the queue like um like the queue is like a one uh one right i wanna repent uh let's say that you already popped the one and then you have added a three two three in this case if i want to append so q is always um first uh a first in first out so if i wanna uh after i added two right when i start popping from the cube pop left and it always pop through first but in this case i actually wanted to when i add to the result i want to add the most the right side value to the result here so here is how you do it the minus 1 is the last value from the queue and then i want to append its value to the queue that's basically what you need to do um because if you don't append the last value then it will not be able to get the three here and then i'm gonna go through the iteration for i in range length of the queue right um and i'm gonna go through each of the iteration and i'm gonna uh do uh the node is q dot pop left i'm still gonna popping from the queue pop left every time when i pop a value i want to add its child when i add its child i'm gonna have to check if the child exists so if no dot left exists all right if node.left exists i'm just all right if node.left exists i'm just all right if node.left exists i'm just gonna q dot append no dot left and if node alright exists i'm gonna q dot append no dog right but either way every single time when you go back to the loop one more time you will still be able to append the most right value and then while q and then in the end i want to return the result right and that's the breakfast search and you can see it's uh it works and then i'm gonna show you how to do this in the dapper search like recursively and i'm already okay so uh i want to keep the edge cases because it's essentially is the same and i'm going to assign a result here um i'm going to define our data search function and i'm going to pass two parameter one is the root uh the node itself and the other one is the level and when i uh remember the base case i mentioned is that if the length of the result equals to the level that's when i wanted to repent the append the result to the end the result because at the beginning right level equals zero at the beginning and the result equals to this is empty that's why the first value i will actually repent to the end result uh the end result is actually the root value which is 1 in this case and then next time when i do it i'll show you the recursive function and then so i want to run this recursively right for the child in um in two items right one is the node all right and node.left all right and node.left all right and node.left this is super important that you have to make sure you start from node all right because it what it's trying to do is get the node.right value the node.right value the node.right value if you go through the if you go through this recursively you will see that why it needs to start with the node all right because this node all right leveling is when you go through three right and if you want to start the child node three the at that time the result equals 1 and the level equals to 1. that's the time you're going to append the second result but if you imagine if you start for child in node.left and you start for child in node.left and you start for child in node.left and doll right if you start from the left and the result is one and the um leveling is one also if you append that result you're gonna happen to end up being uh end up appending the node or left which is the wrong answer so that's why you gotta have to make sure the node all right is on the uh it's the beginning of the list so if child if the child node exists if they have if the one has a child node right i'm gonna run the default search on the child node itself basically repeating the same thing but the leveling since i'm down one level i want to say level plus one in this case and then that's it for the data search function and you just wanted to call the developer search on the node root node and the leveling star from zero and in the end you return the result and that should be what you are looking for essentially okay if you think that this is helpful please like my video and subscribe to my channel and i'll see you with more legal questions soon bye
Binary Tree Right Side View
binary-tree-right-side-view
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_. **Example 1:** **Input:** root = \[1,2,3,null,5,null,4\] **Output:** \[1,3,4\] **Example 2:** **Input:** root = \[1,null,3\] **Output:** \[1,3\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
116,545
657
yes I'll be solving found six five seven called robot returned to origin I promise it's that the robots are the in position 0 the origin on 2d plane given a sequence of moves judge if the robot ends up at 0 after its moves so the move sequence is represented by a string and the character moves I represents the eyes move ballot moves our right left up down robot returns to the origin after finish the olives moves turn true otherwise return false note that note the way that the robot is facing is irrelevant so right we'll always make them move it make the robot move right once I will make the robot move left also assume that the magnets of the robust movement are this information move so for example if the road moves up and down it'll be back to the origin it's but what moves left and left it would be to the exposition would be negative 2 so it would not be in the same spot so if you haven't given this shot pause the video and gotta solve this all right great so hopefully you've cut it out so one way I think one way of doing this is that we can keep the tact of the x position and y position throughout each of the moves and whenever we seem up we'll increase the Y and X or Y position and then obviously down we increase the life as well so same thing with left and right whenever we see the left will decrease to X or niversity of life will increase the water X and at the very end if our x and y are at the border then we can say that the robot is back to its original spot so let's first initialize X Y to be 0 and now wanna loop over all of you if the move is equal to left and the world has left once and I'll Stephanie this too right go ahead that's right and if you move is down then the rule of I had down once and otherwise the move must be I guess so will increase this else I can just so the very end its back to work if the accent wire is still 0 so I can just return actually y is equal to 0 so let's see if this works looks like it looks for that example attracts me and looks like it's good
Robot Return to Origin
robot-return-to-origin
There is a robot starting at the position `(0, 0)`, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot **ends up at** `(0, 0)` after it completes its moves. You are given a string `moves` that represents the move sequence of the robot where `moves[i]` represents its `ith` move. Valid moves are `'R'` (right), `'L'` (left), `'U'` (up), and `'D'` (down). Return `true` _if the robot returns to the origin after it finishes all of its moves, or_ `false` _otherwise_. **Note**: The way that the robot is "facing " is irrelevant. `'R'` will always make the robot move to the right once, `'L'` will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move. **Example 1:** **Input:** moves = "UD " **Output:** true **Explanation**: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true. **Example 2:** **Input:** moves = "LL " **Output:** false **Explanation**: The robot moves left twice. It ends up two "moves " to the left of the origin. We return false because it is not at the origin at the end of its moves. **Constraints:** * `1 <= moves.length <= 2 * 104` * `moves` only contains the characters `'U'`, `'D'`, `'L'` and `'R'`.
null
String,Simulation
Easy
547,2239
1,914
hey everybody this is larry this is me going with q2 of the weekly contest 247 uh cynically rotating uh grid uh hit the like button hit the subscribe button join me on discord and we'll chat about this or other contest problems in general right after the contest anyway so for this problem i think this is actually straightforward in that they tell you exactly what you they want you to do you just have to implement it and the implementation is kind of yucky uh at least the way that i did it maybe they'll you know maybe we'll go over some code that is quicker later on or uh shorter to write but for me in contests i just try to figure out you know a consistent way of doing it the only key trick is noticing that uh k could go up to 10 to the ninth so you cannot just do a simulation because you're just running out of time so you have to you know and this is not a hard mathematical thing once you've done it a few times which is that you have to take the cycle and then mod it by k because then that will allow you to um yeah that'll allow you to uh allow you to do it but yeah but this is my code i'm not happy about it to be honest so i'm not going to showcase it too much but i'll go over a little bit because a lot of it is just copy and paste to be honest from i mean like from itself like and you could watch me stop it live during the contest and even though i did spend 48 seconds on q1 i spent 13 minutes on this one which is longer than actually all the other problems because i think in q4 i spent a lot of time debugging but it's still like you know like i spent a reasonable amount of time but this one i knew like how to do it as soon as i opened it and it still took me 13 minutes because it just messed right anyway so this one the way that i implement it is just by doing this a traversal of the graph and then just putting them into a list rotate it k times k mod the length of the array times and then put it back into the grid so that's basically what i did here um i think you could probably simplify this to a for loop to be honest to like one for loop to have a queen of code but i was worried about like off by ones and consistencies and testings and stuff like that um it is a little bit tricky especially during a contest time because you have to make that judgment of debugging because if i have any typos or any weirdness here it's going to be a disaster to debug i'm not going to lie so that is a risk that i took versus writing for loops where it's concise but you still may have bugs and you might still have to get older like you have to be able to generalize it in a way that is maybe hard i don't know but maybe i uh if i was you know if i really am stressed about it i would take this offline and up solve it later by rewriting this even though i would have the correct solution rewriting this to be cleaner and then with that process after you do it a few more times you begin to gravitate to the better um mindset over time right it's not done in a day or whatever you just have to kind of keep doing it anyway so that's basically the idea is simple you just go around the grid layer by layer i start by you know the corner from you know starting from zero one two and then just rotate it uh i keep track of the things that we've done to kind of keep track of a border i go right down um write down left up and then i just put everything in this layers array put it into layers um like an array of arrays and then i just repopulated later with the same idea i just go okay so for each layer we start at the corner um as we said the actual k that we're rotating is going to be the k that is given modded by the size of the layer and then you know and then we just do the actual rotation here um and then we just walk the grid again by filling it in this is exactly the same code except if i change some stuff and you watch me solve it live you actually see me copy and paste it a lot i'm not proud of that but i am transparent about it and like i said you can probably rewrite this later but i just want to show you what quote unquote uh first draft of real code works like because once you have to have code that works i mean i know that on a contest especially in the contest they have test cases for you but in real life you know if as long as you get something that's working then now it becomes easier to verify your unit testing and once you verify your unit testing then now you can make uh end writing more test cases for example and then you can now rewrite the code and then run it against those unit testing again so that you can verify that you still have to write code and that's how you know there's no regression and then that's how you make improvements in a deliberate illustratively kind of way okay um that's pretty much all i have i'm just code like i said i'm not really happy about it but it is kind of what it looks like it just you just go down you know you take the numbers out you do a rotation and then you put it back in so that's basically it uh what is the complexity you may ask of course it's linear time uh roughly speaking because they're at least them at most end layers um and then for each layer you do this spiral thing of course the survival thing jimdo looks a lot confusing for to analyst analyze um it's just linear time right because or this for loop and the spiral things combine is linear time because you can think about each cell getting looked at once or twice depending on like boundary keeping and stuff like that but like constant number of times right um and then here the same thing right um the only thing that yeah i mean there's this thing which is a little bit awkward but again that's linear in the size of the input no matter what because that's bounded by the length of the layer uh size so all this again is linear and when i say linear by the way just to be clear is rows times columns people you know sometimes use n times m and then they say like oh n times m or n squared so you know it's quadratic on the length of the side which is true but linear in the size of the input which is what o n refers to um in this case or more uh if you want to be pendant about it uh but yeah um that's basically it uh that's why i have the code i don't know i mean i keep showing the code but it really is just sometimes you're gonna get these problems in contests or life you just have to grind through it uh some people did get it really quickly though so five i mean even the top people got in like six seven minutes and it's the longest problem give or take so i don't you know don't feel bad about it but sometimes in life you just have to do the hard stuff and the hard stuff is doing uninteresting stuff sometimes uh anyway uh that's all i have for this for now you can watch myself live next this is this seems like it could be annoying k is 10 to the nine i mean this isn't hard it's just annoying this is going to be like a 15 minute poem for me i'm just gonna do it the dumb way two so um uh oh you 8 12 16 but i'm not getting that right oh because this is oh this is such a mess i feel like there's definitely a better way to do this oh man i don't even think i'm gonna get this in 15 minutes has to go back to nine and five i'm missing the nine and the five two so oh this is five six seven eleven ten okay it's got that right finally okay what a mess okay uh what a mess uh 10 20 40 30 24 12 20 11 10 16. it seems okay let's try uh it looks okay let's give it some it okay i knew that was a good hey everybody thanks for watching uh hit the like button to subscribe and join me in discord again where we just hang out and chat about contests and problems and stuff like that uh i just like having people talking the uh shop you know because this is my hobby anyway um yeah hope you enjoyed this video so yeah uh have a great sunday have a great rest of the day or if you're watching it later just have a great week month whatever you need to do stay good stay cool and to good mental health and i'll see you later bye
Cyclically Rotating a Grid
find-the-subtasks-that-did-not-execute
You are given an `m x n` integer matrix `grid`​​​, where `m` and `n` are both **even** integers, and an integer `k`. The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically rotating **each layer** in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the **counter-clockwise** direction. An example rotation is shown below: Return _the matrix after applying_ `k` _cyclic rotations to it_. **Example 1:** **Input:** grid = \[\[40,10\],\[30,20\]\], k = 1 **Output:** \[\[10,20\],\[40,30\]\] **Explanation:** The figures above represent the grid at every state. **Example 2:** **Input:** grid = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\],\[13,14,15,16\]\], k = 2 **Output:** \[\[3,4,8,12\],\[2,11,10,16\],\[1,7,6,15\],\[5,9,13,14\]\] **Explanation:** The figures above represent the grid at every state. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `2 <= m, n <= 50` * Both `m` and `n` are **even** integers. * `1 <= grid[i][j] <= 5000` * `1 <= k <= 109`
null
Database
Hard
null
1,962
hey everybody this is Larry this is day 28 I believe of the liko day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this problem and this thing my assume is a little bit big but yeah uh hit the like button hit a subscribe I always say that oh man I am just having I don't know well either way then hit the like button again hit the Subscribe well unless that unclicks it anyway uh yeah do what you need to do uh today's problem is 1962. two we move stones to minimize the total uh we have about a week left of the year so hope you are having a good uh well I don't know for me the Year's been a little bit rough I hope y'all just have a good the rest of the year and maybe you know 2023 will be a little bit better um do I have the weekly today no that's tomorrow I could never tell when it kind of comes out okay uh so yeah so let's see so we have piles an energy K you want to do K times do you want to take any powers and remove half of it um and we moved four of it so that means we keep the ceiling uh and then okay we turn the minimum possible total number of stones we move remaining after applying K operations okay did we do like uh I don't remember that was the premium one that I did yesterday but this just seems to be so you know the logic here would be to kind of think for what is the operation that you want right so to minimize the pot the total number of stones afterwards what you want is to take the one with the most Stones like in a greedy way right and um you want to take one of the most stones and then take you know we move half of it and in this case you can apply it multiple times so these are the two things we have for this farm right uh keep getting the Max K times and then uh I guess put it back in but yeah right so um with some experience you'll be able to quickly identify that this is what you want from a heap so let's um but that's basically it really so let's get to it um you can maybe do some hipify and technically that's slightly faster but uh I just want to kind of write it out to be clear maybe I don't know but yeah so for X in Pius uh we want to push it to Heap and in this case what we actually want is we want to sort by Max right and I think in pipeline is I really wish they have like a Lambda thing for push and whatever in general but because they don't have a cheap data structure this is just a heat class operating on an away with doing variants and assumptions um it's a little bit weird so the way that I always short-handed is just by that I always short-handed is just by that I always short-handed is just by using the subtraction because then now you have to minimize um yeah you want to minimal minimize all the um this is a Min Heap in Python so now you have all the Macs because it's the negative right and then now so while K is greater than zero and you could do the two ways you can do it now I suppose and I'm just you know depends on the day maybe I would do it the other way but for example you could have the total count and then you could subtract it after you pop or you could just not you know trust yourself or something like that at the end it'll be good so then you could just sum it up because some in this case is a very cheap operation if you have to do if the you know with these operations on uh as trivial like if you have if you run the analysis or the time complex analysis and it's expensive to do certain things then you may lean one way or the other in this case it doesn't really matter so yeah so while K is greater than zero we want to get uh next from he pop of H and of course that's just you know flip it back to the right sign first um or maybe we could just do it this way I suppose and then now you want to remove half of the thing right so okay so you remove this and then now we push it back into the Heap for future use say and again this is negative X um and then at the way n well you had to subtract one otherwise that's sad I guess we could have done this in a for Loop actually um I'm just very used to lighting it that way for whatever reason and then just some of the Heap and that's pretty much it is what I would say if it's right but I forget that uh we have negative numbers so uh yeah there are no negative numbers I think I'm just absolute test though or maybe even just negative really um I forgot about that but uh yeah um you can also just pop each item but this is I guess linear let's give it a quick Summit and hopefully I didn't miss like a zero case or something like that might I get a wrong answer a year ago why did I get a wrong answer oh because of this thing I guess no oh because of that thing and I forgot to put it back into the thing so uh because it popped and then you forgot to put it back in okay silly mistake from a year ago but yeah um what is the complexity here right so uh I kind of uh I guess this is kind of optimal uh for that reason but hmm let's see actually I don't know I am relatively sure it is but um yeah so I mean you could replace this with hipify and hipify like if your library has it is you go to out of N I believe uh the way that I did it though is going to be uh and login because it's basically you know each one takes a login and then there's n of them right so yeah um and here this does K log n operations for obvious reasons uh there's K iteration and each one does again twice so it's Kayla again so in total um this is just going to be this press and again uh time and off and space just for the Heap um of course like I said you could reduce this to n and it'll be like this if you do a hit provide um and of course this is just a linear uh iteration to get a sum oh cool I think that's what I have for this one let me know what you think let me know if you have any struggles or whatever um that's what I have with this one so let me know what you think so stay good stay healthy to good mental health I'll see y'all later and take care bye
Remove Stones to Minimize the Total
single-threaded-cpu
You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times: * Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it. **Notice** that you can apply the operation on the **same** pile more than once. Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_. `floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down). **Example 1:** **Input:** piles = \[5,4,9\], k = 2 **Output:** 12 **Explanation:** Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are \[5,4,5\]. - Apply the operation on pile 0. The resulting piles are \[3,4,5\]. The total number of stones in \[3,4,5\] is 12. **Example 2:** **Input:** piles = \[4,3,6,7\], k = 3 **Output:** 12 **Explanation:** Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are \[4,3,3,7\]. - Apply the operation on pile 3. The resulting piles are \[4,3,3,4\]. - Apply the operation on pile 0. The resulting piles are \[2,3,3,4\]. The total number of stones in \[2,3,3,4\] is 12. **Constraints:** * `1 <= piles.length <= 105` * `1 <= piles[i] <= 104` * `1 <= k <= 105`
To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks
Array,Sorting,Heap (Priority Queue)
Medium
2176
1,758
And listen hello everyone welcome to my channel also in this video you will be cleaning this problem minimal changes to make an alternating by ministry of mines videos winters problem entertainment and print and you think absolutely taste selection most of the problems yes-yes that muni selection most of the problems yes-yes that muni selection most of the problems yes-yes that muni data has Been Given String And Dada Have To Be Kept Alternating Okay So Alternating Him Perfect Minimum Number Of Steps Should Stand Divided They Came Back And Chief And But Characters Withdrawal On Buff So Lets And Disabled And Lets Switch More Builder 2016 Under 101 Of Success MP3 The Meanwhile Greatest Benefit Characters Can Solve Work In The Alternating Possibilities That Can Be Possible How Sweater Intestine Alternating O King Soft Office Meeting Attend Computer Apni Life Is 1018 Can Be Easy Alternating Like This 04 2014 Inheritance Year Old Lovers Back 120 Hungry Can Hear Sunavai Fikar Operations at minimum over that supposed to convert I just try into this experiment can refer to other test now subscribe this mixture matching will have to take one subscribe channel subscribe suicide subscribe that get notified to convert test one who Did Due To A Gy Saffron Ki Problem No Problem Subscribe My Channel if you liked The Video then subscribe to the Video then Zandu Ka Fold Point Iodine and Iron Test Size Part Plus Scientist Da Know What IF YOU HAVE A TEST FOR A smile from someone who deserves all the evening 100 numbers to subscribe my channel and please subscribe my channel subscribe must subscribe to that I want to is equal to receive new updates basically then indexes key and exact position and decoration returned 621 days Water person in the country and number operations ok 18 on st kitts akbar subscribers * is equal to what is the correct * is equal to what is the correct * is equal to what is the correct questions 101 subscribe kare a point in this world will be happy avengers love quotes for the second class for second class 12th only butt adventures Pe alternating jaswant singh friend 20 seconds with this subject seconds always given injections ruby ​​and when it is 2018 all and men injections ruby ​​and when it is 2018 all and men injections ruby ​​and when it is 2018 all and men also time so and all events superintendent of police p 09 and king vaishno devi video edit like 0067 and even superintendent of police 2000 have been That End All And Push Was Not Satisfied And I Will Be Implemented By Second Operations Next King 202 Debit The Problem 16 Why Have Two Retail Pack Twitter The Minimum Of Just One Mobile Silent Test Match Against Tower Use Testis 102 Correct Knowledge Submit Attempt Working So Let's Celebrate Eid problem like develop these two cases subscribe this Channel Thanks and have a nice day
Minimum Changes To Make Alternating Binary String
distribute-repeating-integers
You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not. Return _the **minimum** number of operations needed to make_ `s` _alternating_. **Example 1:** **Input:** s = "0100 " **Output:** 1 **Explanation:** If you change the last character to '1', s will be "0101 ", which is alternating. **Example 2:** **Input:** s = "10 " **Output:** 0 **Explanation:** s is already alternating. **Example 3:** **Input:** s = "1111 " **Output:** 2 **Explanation:** You need two operations to reach "0101 " or "1010 ". **Constraints:** * `1 <= s.length <= 104` * `s[i]` is either `'0'` or `'1'`.
Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to be assigned to this number.
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
null
1,710
welcome to june's leeco challenge today's problem is maximum units on a truck you are assigned to put some amount of boxes onto one truck you are given a 2d array box types where box types i contains the number of boxes and the number of units per box now the number of boxes is the number of boxes of this type and the number of units per box is the number of units in each box of that type you're also given an integer truck size which is the maximum number of boxes that you can put onto the truck you can choose any of the boxes to put on the truck as long as the number of boxes does not exceed truck size return the maximum total number of units that can be put on the truck so what that means is we want to get the maximum number of units regardless of type so we want to maximize that while fitting as many boxes as we can onto our truck so there's really no reason to complicate this if we wanted to do this like manually what would we do we would take the boxes with them the most units and put those all onto the truck until we run out of space or we finished all the boxes so to do this i think the best way would be to sort our boxes and types by descending order of the total number of units per box because obviously we want to put the boxes with the most units onto our truck and then we'll just iterate down and try to fit as many boxes as we can so let's begin by first sorting our box types and we can use a lambda function say key equals lambda x which is going to be the second item on our list and we're going to make that negative to make it descending okay so now we have um we're gonna have to keep track of the capacity which is how many boxes that we put on so far it starts with zero and i'm gonna say four i guess number of boxes and the number of units in box types what are we going to do well generally we'll be just putting as many boxes as we can right but keep in mind that we have a certain number of boxes we might not be able to put in all those boxes into our truck depending on the truck size so what we'll do is check to see if we have enough space to begin with so we'll say if our let's see pass well i guess we'll keep track of it in truck size we'll say truck size if truck size is less than the number of boxes that we have well actually we'll start with if it's greater we'll say if it's greater or equal to the number of boxes we have then all we need to do is first decrease from our truck size however many boxes there are and we need to add to our capacity box times units now otherwise if we find that we don't have enough truck size for all the boxes in this unit type we're going to try to fit as many as we can which would just be however many we have left our truck size right so that would be capacity uh plus equal truck size times units and make sure to break here because after that we've technically run out of space in our truck size and i just returned up the capacity and that would be it let's see if this works okay that looks like it works so submit it there we go accepted there's certainly ways that you can clean up this code but it's probably the most optimal one time complexity wise it's going to be n log n and we go over this just n times so one thing that we've been able to avoid here is doing a while loop in here running it multiple times for every single box we don't need to do that we just need to see if we have enough space and then just multiply that by the number of units and if we don't then however much space is remaining multiply that by the number of units and add that and break it okay thanks for watching my channel remember do not trust me i know nothing
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
96
hello and welcome to my channel so let's uh today let's look at the litco 96 unique binary search tree given integer and return the number of unique psts which has exactly n nodes of unique values from 1 to n so the first example is a 1 n is 3. the number of unique binary is five second example is one n is one the number of unique binary search trees is one so the n is between one and nineteen um so this question we can use a dynamic programming we can define a dp where dpi is represent to a number of unique psts for which has a which has exactly i nodes so the this is to define so where i is between one and n so then we want to initialize the this so the dp0 the db 0 is actually there is only one it's a it should be one because uh empty it is also a uh like uh now is also a tree so we can um so then we needed to have the equation so the dpi is uh will be the sum of dp j minus 1 times dp i minus j so where the where j will be between one the one i so the this equation we can actually think about uh we are either reading through all the possibilities so one when the tree is using know the one root and the one the tree is using node two as root and then like a such until like you are using i as a root so we are adding all those together uh so it will be the uh the possibility of like a i nodes so and uh for example also like a for using 2 as a root node we actually have everything larger than 2 will be on the right side everything smaller than 2 will be on the left side so this actually on the left side there is a like dp1 which is 2 minus 1 is a dp1 of uh possibility and on the right side that will be dp i minus two so here j is two so uh in the equation so actually we need to multiply this too which will be the uh the number of unique pst uh using two as a root node root value so uh so actually then we i that's how we got the this transition function so in the end the output will be dpn so the time complexity will be over n square and the space will be of one let's start writing the code so we define an n plus one length dp and then define dp uh initialize dp0 as well and then we can um iterate i and j so the then we are we can just do dpi update the dpi j minus 1 times dp i minus j and then in the end just to return the dp and let's check if okay yeah so let's submit it okay yeah it passed so this concludes today's session so if you have any question please let me know in
Unique Binary Search Trees
unique-binary-search-trees
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. **Example 1:** **Input:** n = 3 **Output:** 5 **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 19`
null
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
95
382
Hai Everyone So Today I Will Like To Share The Problem Ka The Daily Cheat Code Challenge Linked List You Can Read The Problem Statement From Her The Problem Statement You Can Take D Screenshot Of D C Plus Solution To This Problem Date Ise Ki Humane Reverse Kya Link It is ok, note using other express then the time complexity of this approach will also be off because initially we would have added all the values, then we would have done the linked list which will create the time but after that when we will do the get random function tomorrow. We just generated a random number and returned its value to the index, so it becomes one of one. In this approach, the base complexity of n is reduced because they are making what is, they are incrementing, you can see. Because rand plus percentage i thi value will be zero till i minus and if we do plus one then all the value will be in between one tu i, after that if x = i it becomes that after that if x = i it becomes that after that if x = i it becomes that means if the value of Only then we change the rest and it has that value and if it does not happen then we shift the same t to the next number. For the problem, The value A would be 121 meaning T is pointing to the head, the value of Given means why the probability should be Shakti which is head and it will be definitely tight then the initial value of By one clarity, the value will increase that if the value of this condition matches then brother you will be there, now what was the race i.e. if brother you will be there, now what was the race i.e. if brother you will be there, now what was the race i.e. if X is not equal, you have come, then what will be We will flood ahead of the loop. Okay, so what is the probability that the race will continue? We saw in the last how that the probability is one by one. In this how we saw here that in this race one can only end because if X2 comes then We will update the rest. This property of equal to one is fine and if we want the recipe to be done then what will be its probability. The value of rest will be reached when the value of x will be reached because then we will update it. If it is from the value then its probability is given by the value of We know that we update it and what is the value of current or we move it forward, we do one plus, so initially it was here, it must be pointing to the right, so in titration, if If the condition matches then we will sign the race by 3 then we will update [Praise] Right in the [Praise] Right in the [Praise] Right in the first edition there was no choice, in the second edition we had a raha ki P Rijiju tu ki probability a jati hai na to tu If the probability of occurrence is one, then its probability is one. We know this because we are on the third attrition, otherwise we would be coming from the second attrition, so if what is the probability of the second, we had written that its probability of being second is one. By you are right. Okay, his property is with Whatever is the value of I then the probability is one by one similarly or if you are the power then we somehow insure through family technique that the probability of both of them is one by one, then we insure the property of all three. Let's say one by three and fourth when we do right and extra space.
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
994
hello guys welcome to algorithms made easy today we will go through the day 9 problem from august lead coding challenge rotting oranges please like the video and if you are new don't forget to subscribe to our channel so that you never miss any update in a given grid each cell can have one of the three values the value 0 representing an empty cell the value 1 representing a fresh orange and value 2 representing a rotten orange every minute any fresh orange that is adjacent to a rotten orange becomes rotten return the minimum number of minutes that must ellipse until no cell has a fresh orange if this is impossible written -1 in the if this is impossible written -1 in the if this is impossible written -1 in the sample example we can see how with each passing minute fresh oranges turns rotten here are two more example attached with the problem let's start with our approach as we need to traverse all the nodes in the four direction with respect to the initial node we need to use a search technique which in this case will be bfs we'll start off with this example it is much more clearer when displayed visually now that we will be implementing bfs we will need a cube we will also need two more variables first fresh orange which will hold the number of fresh orange and the minutes which will hold the number of minutes which has ellipse till now we first need to know the number of fresh oranges and also the index of all the rotten ones so we will loop on the grid and increment fresh orange when the value is 1 and add the pair of row and column into q when the value is 2. this gives us the fresh oranges 6 and the index of the rotten into q now we will loop till the queue becomes empty similar to bfs we will first find the size of the queue it comes out to be one now we pop the element from the queue till the size variable becomes zero for every element popped we will update its four adjacent value to two if they are one and add their index into the queue and decrement the fresh orange count for index 0 comma 0 only these two positions have the value 1 so we update them to 2 and add their index into q also decrementing the fresh orange count as size becomes zero we come out of the inner loop and then increment the minutes we repeat the same steps first by finding the size and then removing the element till the size is not zero then we update the fresh oranges to rotten while decrementing their count and adding their indexes into the queue now 1 comma 0 do not have any fresh adjacent so we move ahead and increment minutes continuing with this loop till the queue becomes empty as now the queue is empty we return the result if the fresh orange is zero it means it is possible to make all the fresh orange to rotten so we written minutes otherwise we written minus one in this case we return four summarizing all the steps we first initialize the minutes variable to minus one a q and a fresh orange to 0 we loop over the grid and add index into the queue if the value is 2 or increment the fresh orange when the value is 1. if fresh orange is 0 then we return 0 we loop till the queue is not empty and then find the size of the queue we loop till the size is not zero we pop the first element and update the value in all the four directions if the value is one and add the pair into the queue at the end of the while we increment minutes if fresh orange is zero we return minutes else we return -1 the time in space else we return -1 the time in space else we return -1 the time in space complexity is often here is the actual java code snippet you can also find the link to the code in the description below thanks for watching the video if you like the video please like share and subscribe to the channel let me know in the comment section what you think about the video
Rotting Oranges
prison-cells-after-n-days
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`. **Example 1:** **Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\] **Output:** 4 **Example 2:** **Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\] **Output:** -1 **Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. **Example 3:** **Input:** grid = \[\[0,2\]\] **Output:** 0 **Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 10` * `grid[i][j]` is `0`, `1`, or `2`.
null
Array,Hash Table,Math,Bit Manipulation
Medium
null
455
hello guys and welcome back to lead Logics this is the sign cookies problem from lead code this is a lead code easy and the number for this is 455 and before starting with the question I want to wish you all a very happy New Year and may you all succeed in your career paths so let's start with the question so in the question we are given assume that you are an awesome parent and want to give your child some cookies children some cookies but you should give each child at most one cookie and uh so we have but we have a constraint that each child should at most get one cookie and each child I has a greed factor which is the minimum size of the cookie that the child will be content with and each cookie J has a size SJ where if SJ is greater than G of five that is the greed factor that means we can assign the cookie to the child and the child will be content okay so our goal is to maximize the number of your content children and output the maximum number of children so we want to maximize the number of satisfied children and uh a children is satisfied if he gets the cookie of the size he wants that is the greed factor or Bri greater so let's see how we are going to do this let's suppose we have example one with grd Factor equal to 1 2 3 and size equal to 1 so the gr factors are 1 2 3 and cookie size are 1 one in this the gr factor and the cookie size are already sorted but for the question uh where for the problems or the test cases where the these are not sorted we will be performing ascending sort so you are going to sort in the ascending order or the non decreasing order so after sorting the for this question the array Remains the Same now what you will do you will start one pointer at the greed factor and one pointer at the cookie and check if you can assign a cookie to the child or not so if the child has a grid factor of one and we have a cookie size of one so we can def itely uh assign yes we can assign so that's why it is assigned here yes it is assigned here and similarly we will be checking for each and every uh each and every greed factors and the cookie pairs so and at every point of time where the greed factor that is this condition we have that the cookie size is greater than the greed factor that means we can assign the cookie to the child and thus we will increase our maximum content children so in this case for one we have increased and uh the rest the grade factors are two and three and we still have the cookie size of only one that means we cannot assign more cookies so the maximum number of content children is one only in this case and you can solve it for similarly the second example like you have the great factor of 1 and two and we have cookie sizes of 1 2 and three so this two can get either a cookie of size of two or three and one can get a cookie size of one and two if this two takes three so that means both the children can be satisfied in this case and the output is so let's come to the code section but before that do like the video share it with your friends and subscribe to the channel if you're new to the channel so first of all we'll take a in Keys num and we initialize it with the length and if cookies nums I'm sorry for this equal to zero if it is equal to Z we will return a zero no possible arrays do sort the gr factors and also arrays not sure the size of the cookies and then we have in Max num and then we have a cookie index the cookie index uh we'll be starting from the back so we'll be taking cookies nums minus one and uh we having a chck index like will which child will be given with which cookie so that also we are having you can also do it from the starting it doesn't matter but allocation matters in this case now we'll check like if cookies index so what is the first condition cookies index is greater than equal to zero and then children or I think the child index is also greater than equal to Z so what we'll do if the previous condition is true and then the cie size the P size is greater than or equal to the G factor of the child this the GRE factor of the child so we are checking the main condition now if it is correct then Max nums Max num Plus+ this is our final nums Max num Plus+ this is our final nums Max num Plus+ this is our final answer counter and the cookie uh cookie num cookie index can be reduced and the child index can also be reduced because we have used the cookie and we have allocated the cookie to the child so we can move both to the left because we were moving from the right so this is how performs if we don't allocate the cookie to the child then only the child is shifted not the kogi and finally we can return the max nums num let's see if it runs therey and uh some spelling mistakes here and there you can see it passes for the sample test cases let's Le for the hidden test cases as well my last solution was uh pretty good let's try to submit again so the time complexity for this solution is O of n log n and the space complexity is O of n this is a very much optimized approach if you are talking about in an interview the interviewer will be very happy with you if you tell this solution it although it doesn't passes this 100% beats 100% but it is passes this 100% beats 100% but it is passes this 100% beats 100% but it is still the one of the most optimized solution because you are not using a space and you are just sorting the uh the arrays so this is a very much optimized approach I hope you understood the logic this is very simple to understand please do like the video share it with your friends and subscribe to the channel thank you for watching the video have a nice day
Assign Cookies
assign-cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. **Example 1:** **Input:** g = \[1,2,3\], s = \[1,1\] **Output:** 1 **Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. **Example 2:** **Input:** g = \[1,2\], s = \[1,2,3\] **Output:** 2 **Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. **Constraints:** * `1 <= g.length <= 3 * 104` * `0 <= s.length <= 3 * 104` * `1 <= g[i], s[j] <= 231 - 1`
null
Array,Greedy,Sorting
Easy
null
111
hey guys welcome back to this video in this video we're going to work through the intuition to find the minimum depth of a binary tree for example if you're given this binary tree we have to return to because the minimum depth of this binary tree is two and this path okay now how we can find minimum depth of a binary tree we're going to traverse the given binary tree in dfs manner first we'll visit the left most node okay the left most node here we have two here we have null and here we have now for null node we have depth 0 okay that means we have nothing there is no depth so for null node will return 0. for this null node it will return 0 and for this null node will return zero now we have to find out the minimum depth for this node two how can find that to find that we're going to get the minimum of left and right is zero because minimum of zero and zero is zero we get the minimum then we're going to add one why because we have here one node right so zero plus one is one the minimum depth for this node two is one here we have found the minimum depth for the left subtree of this node one now let's find out the minimum depth for the right subtree of this node one okay here we have three then we have four okay here we have two download so we'll return zero here as well zero because now node means nothing so there is no existent so that is zero now for this node four now we're going to get the minimum of zero and zero that is zero and one that is one so we'll return here one and here we clearly see that the depth of this node four is one now let's go to right here we have five left is null so for left node zero for right node as well zero the minimum of left and right for this node five is zero so zero plus 1 is 1 for this node 5 will return 1 okay now for this node 3 we found minimum depth for the left sub 3 and minimum depth for the right subtree now let's get the minimum of them so minimum of one and one is one so one plus one is two well we're adding one because when you are encountering a node that means we'll have a depth one for that node that's why we're adding one and here we have found the minimum depth two for the right subtree of this node one now let's get the minimum of left subtree and right subtree the minimum of one and two is one so one plus one is two so we'll return 2 for this given binary 3 if you are given this binary tree we have to return 2 because the minimum depth we see here two now how we can solve this problem now let me go through the intuition first our goal is to find the minimum depth for the left subtree of this root node okay so here we have two then here you have null so for null will return zero now so minimum plus one that is one okay here we have found the minimum depth for the left subtree of this node one now for right subtree here we have three then we have here four then we have four okay so it will return zero now node it will return zero minimum of zero and zero is zero plus one is one then this node 5 we have null so it will return 0 here it will return 0 because this is a download so minimum of 0 and 0 is 0 plus 1 is 1 then for this node we found the minimum depth for left subtree that is one and minimum depth of right subtree that is one so let's get the minimum so minimum of one and one is one plus one is two then this sub three now so it will return zero here now it will return zero so minimum of zero and zero is zero plus one is one now for this node we have found the minimum depth for left sub tree and minimum depth for right subtree so let's get the minimum and the minimum of two and one is one and 1 plus 1 is 2 all right and for this node we found the minimum depth for left sub 3 and minimum depth of right subtree all right the minimum depth of right subtree of this node 1 is 2 so minimum of 2 and 1 is 1 and 1 plus 1 is 2 and we will return 2 for this given binary tree and this is how we can solve this problem the solution will takes figure of n time complexity since we are visiting is nodes in the given binary tree once and this solution also takes big of end time complexity for the recursion call stack because we'll traverse this binary tree using dfs source and this is how we can solve this problem i'm not going to go through the pseudo code i have attached the source code to this video link in the description check that out i have another video to this problem i'll link that video in the description as well you can check that out all right guys this is my solution to this problem if you want more video like this stay tuned with cs ninja
Minimum Depth of Binary Tree
minimum-depth-of-binary-tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. **Note:** A leaf is a node with no children. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 2 **Example 2:** **Input:** root = \[2,null,3,null,4,null,5,null,6\] **Output:** 5 **Constraints:** * The number of nodes in the tree is in the range `[0, 105]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102,104
684
welcome to june's leeco challenge today's problem is redundant connection in this problem a tree is an undirected graph that is connected and has no cycles you are given a graph that started as a tree with n nodes labeled from 1 to n with one additional edge added the added edge has two different vertices chosen from one to n and was not an edge that already existed the graph is represented as an array edges of length n where edges i has two nodes a and b indicating that there's an edge between nodes a and b return an edge that can be removed so that the resulting graph is a tree of n nodes if there are multiple answers return the answer that occurs last in the input so i feel like this should be marked as hard because i had personally no idea how to do it but after looking it up i get the idea here's what we're going to do we're going to move through our edges build up our tree and find the edge that creates a cycle now why is that well you can imagine if we're building up this tree we start with one and two then we add one and three but as soon as we add two and three here we find that there's a cycle here right that means that this one has to be removed because as soon as we have a cycle there's no way that this can be a tree so essentially really the question is what edge when we add creates a cycle and then just return that edge now we how do we uh formulate that well what we're going to do is create an array that marks each node here and say that we start with one and two what we'll do is see if each node is pointing what it's pointing to as its parent and right now currently each node is just pointing to itself but when we say one and two what we'll do is just update one um like you can choose arbitrarily but let's say we'll mark the y like we'll mark this one's parent as two so this way we kind of know that we marked these two are like union together so we add one and three we have to check hey do these have the same parent or the same marker that these are like unions of the same tree now here with one we see one has root of two and three has root of itself three so it's not it's the same so what we'll do is if it's pointing to itself we'll merge it with this part so this one will not be a two now as soon as we get to two and three we find that well these have the same parent so adding this is going to create a cycle right so that's what we do we return this and we could find the parent by just recursively calling up to see what the highest mark note is and each time we update everything and eventually all these should be the same if there was no cycle in the same way let's look at this example uh we'll have some sort of lookup that marks each one of these nodes we start with line two update one to two and three uh update this two three and four update this two one and four oh where we know the same parent right and that's when we return one and four and you can see the answer it indeed is one and four it makes sense right because we had one and two we had two and three we had three and four but as soon as we add one at four what happened here this created a cycle so they can't have the same parent okay so let's begin by first figuring out what our n is just going to be the length of a set of all our edges and what we'll do is just use the chain function passing in the edges that should give us all so i'm just going to call it root even though that's kind of a misnomer but this will indicate to us what that representative node is of this tree so i'll say 4 i in range of n plus one and i realized that zero is going to be in there but we'll just ignore that because i mean you know it's zero indexed so okay next let's have a function that's going to recursively call up what the parent is so let's say we pass in a value we'll say if root.x we'll say if root.x we'll say if root.x equals x well just return x but otherwise um return we're going to recursively call the root.x to see the root.x to see the root.x to see how far up we can get to the parents here yes okay so four let's call it x and y and edges let's find the representative and i'll just call it xr for x root and y root and this will be recursively called x and this because we call y so at this point if x r equals y r we've found a cycle right so that's when we just return x and y immediately now otherwise if the parents aren't equal we need to set all these we should set the one node that's by itself if it is to the rest of the unioned you know nodes so let's see if uh x r which is the x equals x r then we will set root of x to equal y r and the other way around as well if y equals y r by itself and set the y to equal to x r now finally if none of these are true we need to set let's see root dot x r equal to y r so that's kind of arbitrary but it shouldn't matter at this point all right finally that should be it like we can assume that there is a cycle in here no matter what and the given graph is connected so this algorithm should return something in the end so let's see if this works all right so i think that's working let's go and submit it and there we go accepted so time complexity wise it's going to be and worst case n squared because of this recursive call now there is a method where you could reduce this down to o of n by using disjoint set unions but that requires like some stuff that i just didn't understand i didn't want to you know put that in here without really understanding it and sometimes like it works and to me this is confusing enough so i'm just going to end it here maybe someday i'll go back to you know try and understand that this joint said even better so all right hope that helps thanks for watching my channel and remember do not trust me i know nothing
Redundant Connection
redundant-connection
In this problem, a tree is an **undirected graph** that is connected and has no cycles. You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. The graph is represented as an array `edges` of length `n` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the graph. Return _an edge that can be removed so that the resulting graph is a tree of_ `n` _nodes_. If there are multiple answers, return the answer that occurs last in the input. **Example 1:** **Input:** edges = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** \[2,3\] **Example 2:** **Input:** edges = \[\[1,2\],\[2,3\],\[3,4\],\[1,4\],\[1,5\]\] **Output:** \[1,4\] **Constraints:** * `n == edges.length` * `3 <= n <= 1000` * `edges[i].length == 2` * `1 <= ai < bi <= edges.length` * `ai != bi` * There are no repeated edges. * The given graph is connected.
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
685,721,2246
825
In this video, we friends shop appropriate agency are going to solve this question, we have a question which is quite fantastic, brother-in-law are people on social fantastic, brother-in-law are people on social fantastic, brother-in-law are people on social media website, you are living and waiting, error is where the age of I is the day after tomorrow, we have There are n persons on a social media website and we are given an area whose where jo i the day after tomorrow ko dino does right n day after tomorrow x they bill note send n friend request tu n the day before yesterday same D The following conditions are true: A who is true: A who is What is written in the note? No date if It is not that the one who is A will also do the same to What to do is how many total friend requests have been received, what do we have to do with it, do we have to return it, so let me explain the question to you in a very simple way and tell you how you will be able to do it very easily, so what we have given is the area of ​​an agent. so what we have given is the area of ​​an agent. so what we have given is the area of ​​an agent. And we have been given one by one three conditions 16, 17 and 18 are A is more than 100 and when X is less than 100 then if I consider this day after tomorrow as If he is 16, he can represent 17 or not, this has to be checked and the one who is 16, can he send a request to 18 or not, this will have to be done right, so first of all, if I call him X, then we will have to consider both of them as A. What will I do, I will start checking these three conditions, what will happen if our first turn is A is 17 So I will be able to check, for this I cannot send a friend request, 16 can do 17, now for 16, I will check with 18, from 18, now what has happened to me, which has become A, here 89 A will go, okay then I Will I check the condition, which area is applicable, give 18 li, equal tu hai kitna, we will have to check our water from 8 plus 7, nor can we make a friend request on 18, that means even one is not true here, so what will I have to do now, pay attention, understand now. What will I have to do, I will tell you now what will have to be done, till then you have to understand the video carefully, only then you will understand, otherwise you will not understand, as if I am telling you again and again, okay, so what will I do now, I will move it to X, now X I will create this and A will become our A and this will become our A. Okay because if our What happened A Now again I will check the condition Now what will I do Again I will check the condition Look now how much is our &gt;is ≥ is not means all three conditions are true. When all three conditions are true then what will happen which is You can send a friend request on 17 and 16, one condition has become true for us, okay now what will I do, here we are 16, we have 16, now I will update the value of A, now I will check on 18, this much has become true for 18. If I check, then what will I do now? What is the value of A? 18 of 18 is equal to you. Half of Jo is 17. Ca n't send friend request on 17th and 18th, that means till now our request has been received. Okay, what will I do now, what will I do to us, I will check the condition again and will adopt again, now I have met my love, you are mine. How much has Ca n't send friend request 18 which is 16 ca n't send friend request ok now I will check 18 and enemy A = now I will check 18 and enemy A = now I will check 18 and enemy A = how much is 17 ok now what is 70 give li equal tu 9 plus 7 ke hi How much is the condition, give it greater than 18, what else, who is 18, can send friend request to 18 and 17, then I think you must have understood this explanation, what will I do, I will catch one, I will accept it, X, you have to understand carefully, what will I do I will consider this as If it is true then what will I do, I will not update the request and will return it last and friend, if you have not subscribed the channel yet and are watching the video, then please subscribe because there are many thoughts, I am making a video for you which Rohit No brothers, there are 726 questions of Bhaiya, I have solved this in a much better way only plus and where I have solved many questions, so see that too and if you have any doubt then comment me. Link of WhatsApp group. Link of Telegram group. You will find it in the description, join it, type it, see what we did, how the solution will be made You will check this condition for everyone and what you will do, you will take out the output, then O of n² will come out, okay and space is not yours, I will give you a I will tell you the best question, why is the map made because look, if there are 16, 17 and 18, then have we counted the number, who are the people of Solar Age, how many are there from 17, how many are there from 18, whatever further group is given. I have to count the frequency of everyone so that I can know how many people are there. I don't have to send anything to my friend. Once you know that all of them are unique, then I have to compare them. If all the meanings are like only 16. If it remains the same then there will be a problem. Okay, so what will I do? For this, if you want, you can create a count area, Count A Ray, which will establish the frequency of each element, or if you want, I will do it, which is the best solution for you. Just writing one more time in Noted is a relief, it counts and stores it, okay then the result is saved, now what to do is to catch an element, like catch 16, if you catch 16, then what do you have to check for that 18 If you want to do it, then first catch it, okay, so what have I done, I have got one element, so first of all, what will I do? First of all, what will I do? Once I have counted the frequency of 17, I have counted one element, one is 18. I have reduced one here, now what will I do, I will catch the first level of both because this is our next, its frequency, so we mean otherwise, what should I do, I will catch 16 and 17 and send both of them to it and have created a request function. Its first element means 16 here and 17 here. If you want then send it to Listen and you can also check 16 along with 16 because you must be seeing in the question what is yours that only two elements have been given. I will give it to you in any way, okay or send it to 16. Whatever bill you send, it will go into the bill function. The request function here is of flower type, it will check all the three conditions as a result, the note is written here, meaning you have to water. If any of them is true then we have to count and copy its value from one to our increment and finally return the result then this is our solution which is a perfect solution in itself for this type of It is fine for questions, if time solution is required for this type of question, then how much will it be n², if the size is the maximum length of the edit, its timing will not be anything, then it will be of one, see what we have done here. Show again what we have done since 17, what we have done since 18, what we have done since 17, what we have done since 16, what we have done here, the same thing is happening here with you, by the way, I can make it here, but I am not coming, friend. If you understand the video solution of DISA, then you can take this force of DISA. If you enter any of these two phone codes, then you can apply and take the maximum discount in which you get. Because one of the best DSP in the world is available in both C+Plus and Java languages, so available in both C+Plus and Java languages, so available in both C+Plus and Java languages, so what will I do now, I will turn it to you and then you have to go and take whatever you like in the description. Now what will I do to you. I will show you the code of C plus, see what I will do because it is raining a lot, you will please pause the video, you will write yourself and please try run, if you do not try run then you will not understand and then do the video on YouTube. You will be wondering who is the best video is fine tomorrow, if you have any doubt, if you want to comment then please subscribe the channel and like the video because we are going to come up with all such questions in a very fierce manner, see you in the next video. Cup support with such steamy videos
Friends Of Appropriate Ages
max-increase-to-keep-city-skyline
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
Array,Greedy,Matrix
Medium
null
37
hello everyone welcome to coding culture this channel will contain those programs whose explanation is either not present on youtube or the explanation is present but not up to the mark so without wasting time let's get started so today's question is the sudoku solver so which is also the daily question of 21 of august so we must have solved sudoku in our childhood and most of us will be solving it today also and it is a very interesting game so in this question what we have to do is that we will be given an incomplete sudoku 9x9 table and we have to complete it okay so those who don't know what is sudoku and how it is solved i have already explained it in its in the previous video and i will provide you the link and you can go there and understand what is sudoku and how it is played okay so i will not be explaining it in detail in this question because the questions video will become long and most people will get bored okay so i will provide the link but i will explain it a bit so what is sudoku in sudoku there are nine rows and nine columns so how we have to fill it is that in each row there should not be repeating element or we can say that in each row there should be one to nine numbers each time like every time one number like there's one should be present one time two should be present one time in each row and in each column and in each three by three sub matrix it's a box okay so three by three it doesn't mean that every three by three first three by three and next six four five sixth rows and three columns and in this way three this the highlighted boxes like this box and this and in these boxes also there should not be any repetitive number and each number should be present one once okay so if it's if the number is not repetitive it will be every number will be present at least once yeah it's a both same thing okay so yeah now how we will solve it so this question is a classic example of the backtracking and is also very important question if you want to understand backtracking and want to impress children like you can solve sudoku easily in seconds with this program by running this program okay so now let's uh first of all let's talk about the approach and then we will go to the code section and try to code it okay first of all be patient this video may become longer as it uh it's a bit a long question and uh at the coding the solution will also be long but i assure you if you will keep patience i will you will understand bit by bit of this program and you will be able to do it anytime okay so first of all how we will do it okay so i will put one here in such a backtracking box in this way i will put one here and then i will move to the next row and i will check if one is or if one is already present yes one is present so i will there the cursor is in at this point i will place 2 because 2 is not present then i will move here it is 7 it is filled then i will come here what will be dot okay so empty space is denoted by a dot here i will check one is already present here two is present here three is present here and i will put four here okay in this way i will put five is already present six seven is present eight and nine okay so this row is complete now i will check this row and in okay so if any ones is not complete if any there can be many possibilities like i put one here and but if one is also present here maybe then i should i will have to remove one and i will have to place two here okay so how we will tackle it by returning false i will check if furthermore is returning true then okay and if it is returning false then what we will do i will move it to the next and next value to it okay so i think that you may not get to the point now but when i will code it you will be very much sure what i want to say okay so let's try to code it and then you will understand okay so we will start okay so i will make a function solve and what we will add it in it i will add a bold zeroth row and zero column okay so static void and the function name is solve and the parameters will be no it will be boolean why because we want to know if the values i filled is good or not okay if the values i have filled it is correct or not okay so when i will code more and with the coding i will explain you will get why i have taken it boolean so what will be the parameters here bold into say r and intersect c okay and now what i will okay so if yeah so first of all let's uh try to check if the road if the cell is already filled then we have to do nothing so now what i will do is if board i word r c not equal to dot it means it is filled then what i will do i will try to go next okay i will what i will return i will see it later and otherwise if it is not filled then what i will do then i will have to fill it and how i will fill it i will check from where we i started to fill it i will start to fill from one and let's say okay it is a character array so i will take care there and let's name the variable val and it's a val one and how long we will run it i will run till val is less than yeah or equal to nine and val plus okay so now the major thing is if i will pass this value and the roth and column to uh checker to a checker and to check if it is correct in the row column and sub matrix it is not present okay if it is not present then we will move forward otherwise we will run this loop once again so okay so let's take see if is valid is a function that will return you don't mind the function here that what how we will make this function just let it be okay just keep in mind that it will return that if it is correct or not so bold i j and which value well if it is valid then what i will do i will put board r okay oh sorry r c equal to what equal to val yeah it's a good that uh if it is valid then i can put it here okay now what i will do yes now what i will do is a very good question here okay now what i will do i will move on i will move forward and i will again call the same function solve and here what i will do i will pass board and now there is a problem here the problem is if i move till this row this cell then if i will do c plus 1 then it will move out so what i will do i will check if it is equal to the last cell or the last column then what i will do i will add a value in r otherwise i will add a value in the c itself okay so yeah i think you have got it so i will not explain it more and first of all okay so now let's check into okay so let's check enter n i equal to 0 and n j equal to 0 and now what i will do i will check if c equal to what bold c dot length bold zero dot length this is the way i we will check the column yeah you must have know it if you are solving this hard level problem okay you must have known it and then what i will do n i equal to r plus 1 and n j equal to 0 yeah it's uh obvious otherwise what we will do is i will simply and i equal to the same row which row r through and n j equal to what another next column c plus one so yeah it's a good and if okay now let's fill this also if we are doing so if it is filled so what we will do we will move to the next gel and next cell is bold ni comma nj okay and otherwise if this if it is valid i have already told you then i will put the value in the board and i will move further okay so move further means ni comma and j yeah it's a good okay then if this is true it means that by putting the value one or two whatever it is at this cell we can move on and we will get true then what i will do i will return true otherwise what otherwise i will again put the value of bold r and c equal to dot which means that it is not true and now move on and again what i will do i will this loop will run again yeah this rope other if this is true then it will return true and this loop will not run again but it is not true then this loop will run again okay so yeah and we will return false here if we can't put any value then what i will do will return false like we can't put 1 here we can't put 2 here we can't put 3 here and it mean till 9 we can't put here everything is present either in sub matrix or the row or the column then we will return false and this false will be accepted by the previous is valid function no solve function okay and then whatever it will do it will change the value so it's like a chain to the previous ancestors this is simply backtracking okay so let's now okay so the only one thing is remaining now and that is what that is to make the is valid function and is valid function is a bit very easy i will not explain it more as i have already explained in the previous video and i will provide you the link there already okay so is valid and what are the parameters bold rc and well and okay so what we will check i will run the loop for equal to zero for the row and what i will check if this element what val is already present in that row so how we will check it bold i in which row in the row equal to val it means it is already present we will return false similarly the same thing we will do for the columns i and what is the column co so basically it is checking for each column for the same row okay for column and this is checking for the row and now what we will have to do we will have to check for the sub boxes of three by three so how we will check it i will take into a small i semi row by three into three and similarly for the column i will explain it don't panic i will explain smj column and what now for the column smi and smg okay so let's uh run the loop that will be always 3x3 you can do it in any other way i like this okay and now if board smi plus i yeah and sm j plus j yeah equal to val it means it is already present and then what return false if all these conditions are true then what then return true okay so now let's talk about this point here suppose my row is suppose my row i have given is 2 and column is one so second row and first column second row this and second row is this row and first column is this so it is nine it is filled here okay let's suppose this column okay now which sub box we will check it will be given by this okay row by 3 into 3 so my row is what my row is second and column let's suppose zero then our s m i will be row by three two by three it's zero into three it is zero column is zero so column by three into three it will be zero so now okay we can simply traverse this way yeah we can do it smi plus i zero for once it will 0 1 2 and then okay i hope you have got it now suppose my row is 4 and my column is 6. let's go to the array and check 4th row and sixth column okay fourth row and sixth column this now it is in what my smi what will be my smi should be four and my smj column it should be 4th now let's check if it is true or not smi 4 by 3 it is 1 into 3 yeah it is 3 ok so i was right here and let's check for the column six by three into three two into three is six okay i think that i have okay yeah this column six is this i should have taken it five here to check it in this way it is six and my row is four okay so yeah it should be good and this will be our row and column so smi is zero into three and column should be what zero one two three four five six three and six i think i should have got it let's comment it out and check if it is executing correctly or no i should i think that it should run oh okay oh yes my way is not it's a capital and it is not here no problem and we will try to run it again and okay i think i have done something wrong here and let me ch oh yes so what i forgot is the end condition when we will terminate it so when we will terminate it is if i equal to what okay so when we will terminate is when i equal to what i equal to my bold dot length ball dot length means it has come out all the columns are covered and the last row is also covered then what we will do we will return true now it will run comfort oh i am doing this i can't believe it is r run moja please yeah it's running and let's try to check if it is accepting or not it should be accepted yeah it's accepted so yeah that's it that was today's video hope you have liked if you have liked please like the channel and subscribe it and do the comments as it motivates the creators like us to do more hard work and then keep on coding and yeah keep on coding enjoy okay bye you
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy **all of the following rules**: 1. Each of the digits `1-9` must occur exactly once in each row. 2. Each of the digits `1-9` must occur exactly once in each column. 3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid. The `'.'` character indicates empty cells. **Example 1:** **Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\],\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\],\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\],\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\],\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\],\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\],\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\],\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\],\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** \[\[ "5 ", "3 ", "4 ", "6 ", "7 ", "8 ", "9 ", "1 ", "2 "\],\[ "6 ", "7 ", "2 ", "1 ", "9 ", "5 ", "3 ", "4 ", "8 "\],\[ "1 ", "9 ", "8 ", "3 ", "4 ", "2 ", "5 ", "6 ", "7 "\],\[ "8 ", "5 ", "9 ", "7 ", "6 ", "1 ", "4 ", "2 ", "3 "\],\[ "4 ", "2 ", "6 ", "8 ", "5 ", "3 ", "7 ", "9 ", "1 "\],\[ "7 ", "1 ", "3 ", "9 ", "2 ", "4 ", "8 ", "5 ", "6 "\],\[ "9 ", "6 ", "1 ", "5 ", "3 ", "7 ", "2 ", "8 ", "4 "\],\[ "2 ", "8 ", "7 ", "4 ", "1 ", "9 ", "6 ", "3 ", "5 "\],\[ "3 ", "4 ", "5 ", "2 ", "8 ", "6 ", "1 ", "7 ", "9 "\]\] **Explanation:** The input board is shown above and the only valid solution is shown below: **Constraints:** * `board.length == 9` * `board[i].length == 9` * `board[i][j]` is a digit or `'.'`. * It is **guaranteed** that the input board has only one solution.
null
Array,Backtracking,Matrix
Hard
36,1022
1,268
Hello everyone, welcome to 10 off DSL practice and as promised, I will practice this week too, whether it is New Year or whatever, I will not leave you, I have to practice for 5 days, is it okay, so the question you asked today. The question that has been asked is the search suggestion system. What is the question inside it? It is a very simple question but it is not easy to do, so if we look at this question, what the question is saying in it is that it has given us a list of words like mobile. Mouse Mani Pot Monitor Mouse Word Okay, now we have given a search word mouse, so we have to implement the type as it is. For example, when the user entered M, what are the top three characters printed we have to show. In sorted manner, so now here you will see which are the mobile manipot monitors from M, so it is in this increase in order and three top three, we have to show then when the user entered M O, okay, then what we have is empty mouse and The mouse is not even here, it is canceled, so you understand that we have to implement the type system, as the user keeps entering word characters, we have to show its top three which are in sorted manner. Okay, so whenever such a question arises. When it comes to the first strike, there are two approaches, I am telling you, one is with try and one is with pointer, it is okay, time complexity of both of them etc. will also be seen, the first strike of mine was in mind, whenever try is stringed by some words. If you search anything of character then try it is very simple to make it, right, so now see what I did first, here I am telling you the first one to try, this one is fine, time complexity is also off, wait, I will tell you. How did I implement try? Here I have made the simplest tree. Here we have zero to 25. We will take one which will be treated as a character. Okay, now what will we do inside this tree, we will put these words: mobile mouse. Mani pot put these words: mobile mouse. Mani pot put these words: mobile mouse. Mani pot monitor mouse post, which are all our words, we will put them in the tree in this, okay and you know in which way we will put this like for example first time mobile let's insert mobile in this try so the first is M so here for example This is my am right then here is here inside this also for this also its done which way Okay so here you see so how I have taken try string word meaning with each one up to here now word what Tha yahan pe mat hai yahan pe also, now my word is empty mat hai whenever one word of mine is finished, I will say to the here pe word that Han what has become mine, so here I have taken the word and try to search one. The arrear has been taken from 26 type, okay, so now what I am doing here first of all, I am trying to fill it, how I am filling it, I will iterate from here, okay, this is the one who has given me the lace, I am doing this. I will make the thing straight, I will insert each and every word, so that means I will have to draw on the characters inside each word, so let's create a filter tree here, so I will insert each and every product, each and every one of my Pass is the word in it, now I am inserting each product, so now look here at each character for example, first what is mobile, now the characters inside the mobile and I am inserting the characters and they are like this. I am going to enter and as soon as my whole word is finished, what am I doing, I will put this group on the word, okay, in this way I will store all the words, okay, so my try will be created first, okay now I Second what's less I have to implement this type ahead mouse so now I'm doing M first so what's my M now this is my search word mouse so right now what's the first thing is M okay so now I'm doing M so M to I now I will search in this inside try okay so now here I go here search string so far what is my prefix M okay so now I will go to this M first okay so this is mine okay now what am I doing with M I am fine here because I want top three, so maybe there is a word from here too, there is a word here too, okay if there is a word here too, then what am I doing, I will implement it from here inside DFS after M. And first of all I will find three characters in which I will get the word completely filled up till 26 where I will find its word, I will stop there where the word is not equals, you will be null, I am stopping, okay and in the same manner. When I search from, man, let's go, when I come to O, what is my prefix, what is the prefix, so now I will first go here from M, then from O, now from here I will start searching, from here I will implement DFS and from here I will take three words. I will search till I find the word. Ok so coding is simple. Try key is a little big but it's always good. You implement tree. I get a little handsome. What is the time complexity? First try creation key and D. Number of words I have. How many words are there, this is 12345, okay, and each one has to iterate my word, write each length of what, so n * average length of what, so this is my try n * average length of what, so this is my try n * average length of what, so this is my try for creation, after that I have to search, right then o of. Where is this d length of query string because I have to search on every single query string on every single mouse and then one more thing I forgot plus the time complexity of DFS right my so 3* here what I am doing it right my so 3* here what I am doing it okay, here I have to search three words, that is, I have to search three times, but every 26 times I have to go into its depth. Okay, so here plus here, forgot the time complexity, here also add the time complexity of DFS. You will have to do it, okay, so this is our try one, now there is another simple method other than this, okay now what is that first, do the sorting of the world in it, okay, what was there, I used the mobile mouse mani pot, so this is the first one. After sorting, first write here, right here, I copy paste this one here, so now first of all, what am I saying, how will we solve it, first of all, let's open this word. Short So now I am shortening the word, so how did it become short, here it became mobile, then it became Mani Pot, then it became monitor, okay, then it became your mouse, and then it became mouse, okay, left point here. But I put the right point Right here, my right point, now I'm iterating on the mouse, which is my search word, mouse, now where I am at first is MP, okay, now I will search, which is its index, which is zero now. So I will search its zero if MK is there then if it is not then I will badhaunga left if it is equal then I will keep it here. Similarly I will check with the right pointer whether it is equal to it or not. If not then I will check the right pointer. If there is then I will keep it equal. Now if it is from M then now I will increase then A has gone I. What has happened, this one will also be from so I will print the top 3 from here, the will also be from so I will print the top 3 from here, the will also be from so I will print the top 3 from here, the top three from left to right here. I will go on printing Is this the third index of this which is equal to you, otherwise it is left, here is M O N O U, it is not from here, it is from here, it means left is right, from here I am as many threes as possible. If I print that, then we have two, so empty two will be printed here, okay, then what came U, then came S, what is the third index, Han, so the left will remain here, this is also equal, this will also remain the same, so I will print it. I will give second time also, this got printed and then came last. If we do not read back and forth from both then it will remain in this manner. Okay, first of all I have shortened its word. Okay, I have shortened it. After that, assign the left and right pointer. Okay, now I'm trading on the word. This word is is is important because for example, this is your search string, it can be very big, mouse word monitor can be a very big string and here we have empty mouse. Okay, so when you go to man, here it is being indexed, these are some seven and here there is only empty four, so it should not go out of index, okay, so this thing is necessary to save the exception and then where Mine is left right, from there I just have to take out three outputs and group them into outputs. Okay, so what is its time complexity? Big Boss, n people, plus n * m for sorting, n people, plus n * m for sorting, n people, plus n * m for sorting, why because I have to iterate over all the words in it. Okay, total number of words and m is d length because here I am taking left and right pointer because I have to iterate the left pointer also, I have to iterate the right pointer also. What is the worst case that the left pointer goes down completely? And the right pointer should go all the way up, okay, so once Puri can be seen, N * N means here also, I am searching for a trick, * N means here also, I am searching for a trick, * N means here also, I am searching for a trick, okay, so the length of D string is N * M plus O off string is N * M plus O off string is N * M plus O off which is this character. If I have to search on these also, then this is its time complexity and but both the methods, this is a little sample on implementation, but you can also implement a little with try and you can see the coding, maybe it looks like this, but you have to understand it once. If you practice, it will go right, so let me browse a cursor a little, then you will pause and see, tomorrow you will practice tomorrow too, you will do the day after tomorrow too, just empty New Year, this time also keep practicing your good butt, Happy New Year, Happy Christmas, enjoy. Do phuli, if you can spare half an hour, then you can spare an hour. Tree and best but enjoy the holidays. Property Gauge. I was just saying, I was joking that you will do your daily practice. Enjoy the holiday time but if you can spare one hour, then enjoy yours. You can also ask a question, ok gas, thank you bye.
Search Suggestions System
market-analysis-i
You are given an array of strings `products` and a string `searchWord`. Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix return the three lexicographically minimums products. Return _a list of lists of the suggested products after each character of_ `searchWord` _is typed_. **Example 1:** **Input:** products = \[ "mobile ", "mouse ", "moneypot ", "monitor ", "mousepad "\], searchWord = "mouse " **Output:** \[\[ "mobile ", "moneypot ", "monitor "\],\[ "mobile ", "moneypot ", "monitor "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\]\] **Explanation:** products sorted lexicographically = \[ "mobile ", "moneypot ", "monitor ", "mouse ", "mousepad "\]. After typing m and mo all products match and we show user \[ "mobile ", "moneypot ", "monitor "\]. After typing mou, mous and mouse the system suggests \[ "mouse ", "mousepad "\]. **Example 2:** **Input:** products = \[ "havana "\], searchWord = "havana " **Output:** \[\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\]\] **Explanation:** The only word "havana " will be always suggested while typing the search word. **Constraints:** * `1 <= products.length <= 1000` * `1 <= products[i].length <= 3000` * `1 <= sum(products[i].length) <= 2 * 104` * All the strings of `products` are **unique**. * `products[i]` consists of lowercase English letters. * `1 <= searchWord.length <= 1000` * `searchWord` consists of lowercase English letters.
null
Database
Medium
null
349
this is the question 349 intersection of two arrays what it has is that you have two arrays and you want to find the intersection of them and the output should not be any element that is repeated like it should be all unique values so let's do this so i want to use a set high step equals to set and then i'm looking i'm going to loop through the first array and get all the values that are unique yeah that's it we're going to get all the values that are in four idx actually i don't really need to enumerate i can just do for num in numbers one if num not in hash set then hash set dot add so that's how you add to a set um that's what you do and then if you print this out a hash set you would see that there is one and two which are the unrepeated values their unique values of this array let's run this see that there's one and two here okay so we don't need this print statement anymore the next thing is that i want to output an outset another set this is the output set and the reason i'm using a set instead of an array is that i think i don't want to do another set at the end because if i have an array uh there might be this uh problem of um repeating values added so if they're if these repeated values are inside array 2 or nums 2. so let's move over numbers to now so we loop through numbers 1 we got the values that are not repeated they're unique values now we want to see if those values are in numbers one numbers two which is which will give us the intersection so for num in numbers 2 now if none in set outset dot add no and that's it uh so what does this do let's just do it return outside first so this one looks really nice to the array it says if this number um each of these numbers are inside high set just add it to the outset and then return outside so that would give us the actual value and that's it so you can see that this is accepted and uh it's going to end here and then another end here so two minutes
Intersection of Two Arrays
intersection-of-two-arrays
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**. **Example 1:** **Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\] **Output:** \[2\] **Example 2:** **Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\] **Output:** \[9,4\] **Explanation:** \[4,9\] is also accepted. **Constraints:** * `1 <= nums1.length, nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 1000`
null
Array,Hash Table,Two Pointers,Binary Search,Sorting
Easy
350,1149,1392,2190,2282
218
Do it In this video channel today's video, we solve the skyline problem that the suicide problem asks something in such a way that on one side it seems that the girls have that their start point and end point is given by the nutrition channel which is required from rectangle 1 2 80 for 3 minutes Next rectangle is 327 Friends, we have many rectangles Governor, some of them are boiled, you are able to see all of them that now you have been asked to print its length, you will get its powder outline basically. I have asked you to paint the outline on the plane, but it is a pimple, but a salary. If I ask you to print this complete outline, when will you start printing infinite points or some lines, dots etc. Collectors got something. If this outline is to be printed then it is very difficult to convert it into the form of obscene output, then the provident has given such that this is a chord of the points you want to make, there is a one quarter procedure, you will follow it, what is that? If you give us points, then don't give me a complete outline. If you give me only points, then which points at which you want to change the side, if I change the height of all those points, then the outline is created, that is, something which if its output. Let me show you, it's something like this, if you click on it is cat 210 338, then it is 210. Loot may be a wooden 1571 half wave scientist Ram Sir, he has given you the answer. Boss has said, 'How can I convert? Man, what should I do? Now he will be said, 'How can I convert? Man, what should I do? Now he will be said, 'How can I convert? Man, what should I do? Now he will be chatting online. It will start from 0 and onwards there will be years. He must have put one point here or Answer: OK Answer. How to convert in hotel?' Answer: OK Answer. How to convert in hotel?' Answer: OK Answer. How to convert in hotel?' That's what I am showing, so that 210 means that the match is going on this line, I am going on the site like a simple two, I will get the height tanning dark then convert it to 2-3 minutes and then convert it to 2-3 minutes and then convert it to 2-3 minutes and then I will start moving forward. Then next time I will get free electricity like electricity, then the side effects will also go away, then I will move forward that if a simple thing like Naxalism gets time, then I will go on the light bill and automatically I have got this line to grow from here. The work is done and the ventures said that I will do it myself, you just tell me the position where you want to change something, go to zero with a film like Side Effects, then make that change, you tell me the rest to go ahead and throw the line. I will tell you in the work, then there is a button of three, then the temperature on the team in just 120 comments on the printer for the last two days, Chairman PL Punia And so we have to print only those points of that outline where you want to change that you want to change. I don't like want to change the energy that now we want to do this so I told them that while following this project the up output is something like this which if I really follow it then it is a complete style which is and well now One thing, if you remove it from this side, I am from Abhishek Chopra on behalf of the director 's police team, when how can we do this, 's police team, when how can we do this, 's police team, when how can we do this, how can we do it, if I have been asked to print only from the point that changes the line, that point. Here someone's start will be closed, friends, apart from this, it can be anyone here, so here you will not change, you are available in me, then from below it upwards, not possible, you want the upper part of someone, Hisar to enter. When it happens, I said that I will process all the stars and ends meaningfully, no, I will separate one point and think whether something is increasing at this point, what is the need to input the point along with it, then what is the need to break this employee. If there is a need, I will separate the stars and process all the rectangles, then I said, start point S2 less than 80, then in this amendment, make one rectangle for 2 minutes. If the lips are in the conversation, then one more thing has been given, cotton hippy has been given. This silence button hit Teamwork Tank and print comment So if I wrote to everyone like this then I would not be able to know that according to which is the start point of the rectangle which is the endpoint because I could have guessed whether it is 2009 then we do not know 507 someone What should I do to reduce the pension point from this? Now I could have kept the item bullion, one sabri Ankit Bhai, tell me the city is two, if there is a point fall, then I will make end points par class, these two things, then the stomach will be covered with that, better than that, I will make the height negative because the height Positive yoga drop if someone's so many get even number to start point now log this is what you do why don't you make food or do this less many education sass handle weeks that I will tell in April wipes second acting inside the obscene rectangle be good that type Answer: If you make the start point that type Answer: If you make the start point that type Answer: If you make the start point negative then it will automatically go to Hundu. As per the clear explanation at this time, 2010 has been there only. If I delete it, then I will come to know about it. Torch light, they would like more that online. Maintained it now similarly fine - 15th Amendment Come on 16th - 15th Amendment Come on 16th - 15th Amendment Come on 16th Voice Mail 5 Comments Paris Oil Must 3 - 01 2010 Paris Oil Must 3 - 01 2010 Paris Oil Must 3 - 01 2010 Vid Mate that now do these do set two sort needles in the answer is to give increasing order. Can't it be said that this tree If you want to change then put it at the end first and then put the one you want to change later because in the same way and said to the mint that we are one way, I will check your answer and here I will see it in the change, mother. If I change it, then increasing and tummy are required. Said that you will make all these points famous in increase in wards, only then if the answer comes out in the increasing heart, then make half an inch in increase in wards. If you make its best friend in increase secondary, then you will get six points. It will be used on the basis that the answer depends on the export, then after that when I do the prince, then you will - after that when I do the prince, then you will - after that when I do the prince, then you will - nothing, first turn to a nanny, you will find this intern pipe - 117 less 10 on 9 not till the day of 20 Twelfth Commerce 12th Ajay Ko Mere Dil MP3 Ko - MP3 Ko - MP3 Ko - 09 - 800 124 Computer Ajay Ko Jhaal Hips And I have set it now soft I have made it butt main Ishq India Twenty-20 Ishq India Twenty-20 Ishq India Twenty-20 &amp; Twenty 459 till hotspot closed &amp; Twenty 459 till hotspot closed &amp; Twenty 459 till hotspot closed butt apocyanesis all points answer Not going to happen, I am not going to answer all these points, shut up friend, no, like this point is the setting point of the triangle, it is also according to the starting point of the one, no, why friend, because it is over honey and because of this, there is a distortion of the rectangle. Due to this point, the campaign cannot be cemented tight, so how did we lag behind, what will be felt, will not benefit, it is simple, what should I do, will I give a current affair, do thank, what difference does it mean, what height am I now, then and online like now At which height is the line drawn by Suji Rohit Prudential Life or like me because in the increasing and draft, it is on me, like me to you - draft, it is on me, like me to you - draft, it is on me, like me to you - this is the starting point of the tender, now a new rectangle is starting here. is tight so I will do something like that I still have a new rectangle storage on the divider whose height enter and because we have to draw the outline if you look at the quantum, museum wisdom I want to do that whose height is the highest, to some extent rice If you want to do this, then how can you start traveling on the side which has the highest triangle meat out of all the active tenders, then where would you be traveling to this point for one reason, that is, you want to make an outline and make a style. Whose one will be the highest and will be posted on the porn site at this point, all the times active and among them whose heater will not leak out the most, the Dubai rectangle will remain, whose height is the highest, all those active rectangles remain, so as I process it, let me know. Felt that now I have activated a Bangalore first year plug and now I travel at zero. Its high-tech is its maximum height. Its high-tech is its maximum height. Its high-tech is its maximum height. Whose m-cap is it? You will get to know. Well, if you Whose m-cap is it? You will get to know. Well, if you Whose m-cap is it? You will get to know. Well, if you comment and make a change, X is equal to two, but make a change on that side. I have to take the tank, I have to take it, which is the maximum brother panel among all the active rectangles, then I will move ahead, the next nearest restaurant is 12323, from the month it was 2.5 feet more from the point and there are 1000 e. Now why five months leave? As a stubborn person, this is the maximum, so there toys us for a long time at this point, 15th change free foot, my answer is 350 na jaaye ka or a mixture of freedom of Kunwar chiffon, let's go to the next 555, one came my love triangle juice starting point. How to understand the good of height in negative effect, if one mode setting is on then there is another active rectangle in it, how many up in it, all the active rectangles in it, the maximum is how much is the holiday, you are absolutely right in 2015 and how many types of rice are there in us now. Whoever is doing it on the team, because of this, there will be no need to do any tricks or side effects. Children, in this event, the next change point is, I am 1000 height to positive a height positive, it means a rectangle and it is happening that You are removing a rectangle, you are going to keep one, you are removing its height, you remove an active rectangle, basically, you use this height as your butt SIM, now we maximize which one is 12th among all the active rectangles, so now your site But let's put it and on fifteen the meaning is changing here too. If you have to make any change then to what extent are you changing this point. The reason is that some rectangle is coming to an end now because of that the fight is going on. Its picture and setting. To start, I am looking for and at what height will I go, all the activated triangles, why is its maximum, if it is stylishly becoming the maximum one, then I will see Candy Crush playlist and drinking water, I will maintain the set alarm, the next nearest point of this rectangle, how to change it? Appointment Back Side Positive Meaning and Appointment End Points So you are removing a rectangle, you remove its height, it is not an active rectangle, the knowledge is absolutely correct that now among all the active likes, who has the maximum 12:00 that you can do this who has the maximum 12:00 that you can do this who has the maximum 12:00 that you can do this experiment 12th and this one who has changed anything with his skill and not even Kushwaha, please keep it, what is it now, next welcome meaning make a height because positive one hangal's encounter meaning someone is removing all your manifest activate. Get up at any time from the angles and remove the circle, this is absolutely true, now we maximize all the actives, whose is it, I don't have any active, I had kept it in one hero so that Jio comes out, so many collections are friendly to the family, the good feeling is zero now. We are on the play list, so what needs to be changed, you are on this coordinator, which hyper will I go to, in all the articles, which must be up to the maximum, then start moving forward that I have started the step starting point together, if a new color is clear. Do it otherwise, as many as 1000 active election live channels have scattered them or this coordinate has now been changed or placed on you, this flower is now purchased in this cord, as many team relative me, maximum light, when they melt, when they add it. Our current hide and maximize different is that the money goes to next 99831 nor sunshine will get spent on nominates point because inch 9 m that not one comment how to reserve it from month try starting point 19 - 600 from month try starting point 19 - 600 from month try starting point 19 - 600 negative box oil so - that's all No and negative box oil so - that's all No and negative box oil so - that's all No and I will add saffron interesting point, maximum retail in as many active, which site am I on now, near the temple, then to do something to maintain the children of the world, this is the encounter because only positive one, remove it, put 132 to the friends. Now after the report comes, which sites will take some changes in my maximum night and after the clans, I will have to add that the squad has snatched the chain and which one we want to go to, all the active ones in the maximum entry comment in the next flight comment. Car and Pointed, just remove the positive now that we have become whose rice now, the same rice does the same and now what is the maximum height, zero, there has been some change, because of this there has been a change in 2014 and now the maximum height is zero, so I am zero. Gotta recognize now look at this quickly let me show you what so let's just have one item okay 15742 help welcome 10 13 talking about Enfield looting in the ballot boxes this butt is nothing else this cut and something No, this is not a priority but why do we still have to find the maximum, so I will make the maximum practical, I will keep one current height, this is what I control right now, till when there is a point, I will add the height to the penalty key, but their maximum. And check the karma type, have you ever seen which one came then I will have to see if there is no change which one I will talk about if after removing some hair the current is in the last match then there is no need to do anything when the end point If it comes, you will remove its height from it, that side will not be necessary top, that IS not necessary toe will be played, if I know you about this point then what should I say in the party, you will know it once quickly I will tell you and You watch carefully what I am trying to say, then when I come to the security maximum, when I come to the ace endpoint, it could not be removed from the back remove. Platinum Singh, more names, what am I saying, if you keep it aside - 10.00, then we will get this. My keep it aside - 10.00, then we will get this. My keep it aside - 10.00, then we will get this. My answer is, if you have contacted me, then we will go to this channel and subscribe, because of different differences and do the maximum typing, it has come in handy, where did you add the twelfth train and set it. I drank the country right and Maximo, there is no difference in doing this, after all it is St. Martin, if the Bluetooth settings are turned off, then remove the positive one, now it is ₹ 15 parfait maximum na remove the positive one, now it is ₹ 15 parfait maximum na remove the positive one, now it is ₹ 15 parfait maximum na grind, then I said to print it, then remove it. On TV, it was removed on its own, which is not difficult to remove on its own, maximum, due to which height, some change is needed in this team, a simple one, there will be a change on seven, you will change maximum 512, then you will start its alliance, maximum, previous brother, now next or see the rules. Se Shyam Tere Naam Next Do not maintain this line because tank positive PM points, you want to remove it, murder priority because then who knows only the feet, when and what can't you do, you ca n't remove the guy that time and sign That we have another operation, a number on tut free mode in which I will write the letter that time, then I will write the properties, the place to remove the pet, find the stand, unmute it, increase, find it, remove it, that this thing Keep in mind that although now one more thing that I want to tell you before crowning is that I have sorted the institute according to increasing difficulty marks then all should be coordinated at water but in this beginning those tips are not the same as simple time. But I will give you an example that here I have two rectangles 624, so these six pieces will be cut from it 10th board Tenth Chapter Tu Kamal - Starting Point - 600 Subscribe for 1 minute from this point for specific information about increasing the height from if. But it will be here I had appointed the starting point, so it is very useful here, like if I wanted to mean two hundred of it, then in the way, I can do it from here on mutton 608 first iterates it's commit later I write recording this. Why will you put this right and this wrong? I will show it to the criminals by driving, points will be charged, why open it subscribe Free, if you don't drive in it before now then you will get this my front, this is my friend tight gyan-02 got the maintenance starting point, if it is gyan-02 got the maintenance starting point, if it is gyan-02 got the maintenance starting point, if it is negative then 10:00 I negative then 10:00 I negative then 10:00 I alarmed in half an hour, there is a difference between the two, the correction is maximum, it is different, it needs to be changed, till now I will permit you, Ravana - set your luck, starting point you, Ravana - set your luck, starting point you, Ravana - set your luck, starting point 86869000, different rules, so keep rice on this, rule six comments, then subscribe to our channel. Subscribe now and give different in the mix, change yours and follow the show as maximum item, then commit six and remove one. If different in correct sentence, six less 10 kya hua tha to aapne bola tu par temple chali jaaye request. Where did you go then your last six pack shrunk to 268, go to this wrong post, look at this, you have to go here, that erase the mixture aspect, not the stopping point here, you have to add, you have to force the six to be written in. Don't add points. Ok 600, you can go. Bring it for you. Sorry, definitely see. Six food, zero. Will you add staff awards? Commendation. Get set first and ask to avoid these points every day. After all, the artist will leave from here if we do second shopping. How does this expiry date happen, if you make it 7th in different wards of this height, now let's see how it will work, it is absolutely a good method, then in the FD account - channel, I have method, then in the FD account - channel, I have method, then in the FD account - channel, I have added Amla height different and what is the maximum that can be extended that which will be more Ram Mandal Ayukta There is no Mexico, remove dad, first Play Store Google, I have to do two quits, then time, I remove clothes, remove tan, now different has come, maximized will join, tension so x is equal to six, you need to go to zero. And the point is over, then the matter has been made, so this is your correct approaches, how will you sleep, how can you subscribe, this will work in this, kiss Brian, I will show you the information commissioner from the wound, try it once, then you will get the ID like this guy. What was the case when both are ending at the same point but it is important that both are starting, if you do the range in the increasing day then in the right way we are starting lighter, then you need to tell this point daily. Now see, if you tell it above. If you go, then go for the loot, there is no need to point this here, when you increase the height increase in these wards, if you do it in your style, then it will also come against you, as you can see, make some examples and check the cup. Final Fantasy What is this text, one of us is becoming the other, if in this also because both of them have SIM in 101st place, if you do increasing in water marriage, then things will take years, if you do it in decreasing or not, then it is his own creation, so it is decided just. Shark slide problem, turn it quickly, if you all complete it, then it will be absolutely fun, one drop, two call, loot site, hello viewers, Ajay has one, this is dishonor, sexy ghoom juice, you are worried that copy in trans. Can do it yes son do it to Ajay Jhaal video has happened Jhaal to Ajay that this class is supported friend I have six only two But in this model, I told you that ok, I will soften it, if I ever get a final chance on the decision of space class, if I keep it, now there is a skirt, then the first thing I will think of is that I need a play list, I need an address, and if it is ten, I will give him the Chanur list. A question: A question: A question: What will be kept in the new tariff list, what will be written in it, because here we have given the toys for it combination, first of all we have separated this, the one who separates them is that all these cords are island building good thought loop I plus It's new background so I will tell this for that I need start points 8083 but building fennel free mode on ke din paun inch right hu invented that these were teachers now I have to do only to list dot add new people new on Mukesh K I will pass the number in the new leg, think about it, because I am on it, start point with negative file and quite impressed, add point in it with hydrogen, fixed limit, now 100 tattoo collection sports ki Laxman spotless, now we have to set a pin Play Store So let's find one and make one, which I request. The answer is equal to one that New Year, a steam, a plate, now we will rice on it, I went to them, Max Player, Tubelight Solid, all these active rectangles, practice of these teachers for Sangh Block. The situation is to new poverty why then one Sim's karma brother to friend thank 120 only now the problem is in the list so this was my 471 120 Scotland list start speech that I plus one more add one more to the low priority queue and set it to zero Four, when a person is in the western street, then I have a maximum of zero, that child, when the news came, then I started doing rice, then the contact will come out after having fun, then list dot that I do not acid, I have taken one. I have taken a me this or so much that I have taken out 2012latest Cancer has happened that this I returned took a stay for father now things two things variety of top cosmopolitan meaning starting point and white skirt amazon places points 105 I another newton start If this is happening then it will be made in the active rectangle then I will add it in the wells, the height from the butts is negative, I have placed it, so one is this positive, then try to come to the ground, this is the starting point 10 top 10 news on TV - I will add in this way August solution I will - I will add in this way August solution I will - I will add in this way August solution I will remove the positive APN point, I will not just write like this, the one with the back is not mobile that I will finalize the height or those who do Taimur and soldier complex video love oo now you have to check, so what should you check, whatever time brother do. Fighter and Juppy Chuke is tied on the felt tip and the life tube is made by me in its collection. Start the revolver. I want to do something different from Ghr. That these teacher type tamping to new address were on a pedestal, first of all I will find you, which contract, where will I change my life, I will come together and investigate, what will I do in a week, I am going to give you the maximum of the taught laddus, which is the active rectangle. In the maximum liter you have, it changed after doing it and on which site you should spend time. Now let us simply slide it and add it to take Yadav. I have a small one on it, I have not given it to Temple Run. In that ex-cop wanted to go to PT, made In that ex-cop wanted to go to PT, made In that ex-cop wanted to go to PT, made a perspective and gave it a list of two sizes to the play list, he gave his blessings, friend, in this list of lists across the state, it is white, sat for 15 minutes, now covered it, take it and fiber current you. Don't forget to update, don't say update the current, it's half an hour of your decision in some corner, Com has also added 30 which are activated, see from everywhere or have done Snapdeal. Dear friends, it's like you will come out from here and start touching it. This site has to be given. Malfunction in time, College Monday, as soon as possible, Lipsy, I did something, that Rachna Crore Fall, that the telecast was given to Ajay, A straight updated, Ajay should collect his clothes, These robbers have made a mistake that a ball has fallen from the building, here English language Language Jhal I made it a priority, which one has become Sushil accent and started to submit previous song Phir Cross Samadhi Jhal Ajay Ko 2013 I week - Previous is blank 2013 I week - Previous is blank 2013 I week - Previous is blank MP3 is a matter of importance to Ajay, this chapter is complete then you decide The problem is that Ajay can get the electrolyte without any problem in the mix video.
The Skyline Problem
the-skyline-problem
A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_. The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`: * `lefti` is the x coordinate of the left edge of the `ith` building. * `righti` is the x coordinate of the right edge of the `ith` building. * `heighti` is the height of the `ith` building. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`. The **skyline** should be represented as a list of "key points " **sorted by their x-coordinate** in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. **Note:** There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]` **Example 1:** **Input:** buildings = \[\[2,9,10\],\[3,7,15\],\[5,12,12\],\[15,20,10\],\[19,24,8\]\] **Output:** \[\[2,10\],\[3,15\],\[7,12\],\[12,0\],\[15,10\],\[20,8\],\[24,0\]\] **Explanation:** Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. **Example 2:** **Input:** buildings = \[\[0,2,3\],\[2,5,3\]\] **Output:** \[\[0,3\],\[5,0\]\] **Constraints:** * `1 <= buildings.length <= 104` * `0 <= lefti < righti <= 231 - 1` * `1 <= heighti <= 231 - 1` * `buildings` is sorted by `lefti` in non-decreasing order.
null
Array,Divide and Conquer,Binary Indexed Tree,Segment Tree,Line Sweep,Heap (Priority Queue),Ordered Set
Hard
699
350
this question is question number 350 intersection of two arrays two given two integer arrays numbers one and numbers two return an array of their intersection each element in the result must appear as many times as it shows in both arrays and you may return the result in any order so uh let's say we have something like num is a one num is one equal to one two one and plus 2 equal to 2 and 2. so the intersection is 2 and 2 here or if you have something like numbers on 495 and number 2 9 4 nine eight four interception is four nine or nine four okay so um how am i going to solve this there might be different ways to do this uh the way that first of all came to my mind was two pointers um so that's what i'm going to do before that i want to sort the array so the complexity of sorting it is not going to be that bad compared to um going over the whole thing uh all of them so let's uh do that let's just say number one equal to sorted uh nuns one and numbs two nickel two sword numbers two so these are the two uh sort of arrays that we have and after that so this will give you something like uh let's say uh one two i'm gonna delete this one and also this one so let me join with the other one so i'm going to delete these two here and say the other one would be after sorting the little tool too so uh i need two pointers i equals to uh zero and j close to zero and i'm gonna have a list of the list equals to nothing and i want to look through the uh the arrays okay so i'm going to say while i is less than len of the first one number one and j less than of number two when i say that means that whatever is the smaller one i'll just end at that point part like if this gets uh bigger or equal then it just stops there so it will just loop over the smaller one basically okay so while we're looping over we start with one and two we check if these are equal or not uh so we want to see the intersection right so we have to check if it's equal or not so let's say they are equal if uh is one i equally equal to numbers to j then what do you basically say output dot append you want to have to the output array uh that numbers of 1 i or minus 2j doesn't matter either of them because they're equal and then i just uh add to it one time back to the both uh pointers here if there are duplicates like let's say here let's say i is here and j is here these are equal then you go to the next one they're again the same thing you will just add the same thing again so uh the question earth uh each element in the result must appear as many times as it shows in both arrays so that's something we want okay lf um this is not equal anymore and let's say this one is smaller if not i is smaller then what do you basically say hey all right well it's difficult with one so one is smaller you just go to the next one is smaller than you go to the next one okay else would give you i'm not uh explaining the next condition i'm not saying lf is because else is the only condition that is remaining which is uh one eye bigger than those two i thought let's say this is three i mean let's say we had something like this actually three and three if this is uh three then you just go to the next one um you just uh yeah you basically say this goes to the next one basically j plus equal to one yeah so that you want to see that if there's a bigger one something like this let's say you had something like this so you say this equals to this now this is bigger then you go to this one with this now this is uh bigger then you go to this one then so yeah this one is satisfied then you go loop through this one equal i mean and that's done basically because this one is done yeah so it's done so this is it this is uh the whole thing the whole loop and you return output here that should work yep it worked and if you submit this you'll say see that it works so this is the answer to question number 350 intersection of two arrays two we did it with two pointers we sorted two arrays at first
Intersection of Two Arrays II
intersection-of-two-arrays-ii
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**. **Example 1:** **Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\] **Output:** \[2,2\] **Example 2:** **Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\] **Output:** \[4,9\] **Explanation:** \[9,4\] is also accepted. **Constraints:** * `1 <= nums1.length, nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 1000` **Follow up:** * What if the given array is already sorted? How would you optimize your algorithm? * What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better? * What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
null
Array,Hash Table,Two Pointers,Binary Search,Sorting
Easy
349,1044,1392,2282
35
this is the 35th leeco Challenge and it is called search insert position give an assorted array of distinct integers and a Target value return the index if the target is found if not return the index where it would be if it were inserted in order you must write an algorithm with olog and runtime complexity so if you get one three five six and the target is 2 the output will be one because currently at index 2 or index 1 is 3 but 3 is greater than two so two would be there instead and three would be pushed upwards if you I skipped one up here so if you get Target five that just returns two because that's where it is if you have Target seven that would be four because there would have to be an extra spot up here so zero one two three seven is greater than six so I put before okay let's get started okay so first things this is going to be another band research one so we'll do int lower equals zero and upper nums minus one so some things we can do straight right if nums lower is greater than not equal to Target turns zero if nums upper is less than Target return num's length and I guess we can just also do if it equals Target turn upper Okay so we'll do while lower is less than upper we then need to do int current equals upper minus lower then divided by two its current is less than lower do that if current is a Target current is less than Target yeah lower equals Target if current nums there we go we do that if nums current equals Target turn current also add a check the top f lower equals upper minus one return low I think or would this be returned upper I think so that actually even turn upper because we're kind of Shifting it up and then in which they return upper so let's run it just to see what outputs we'll get and we've got the correct outputs cool okay let's copy this put into liquid and see if it works with all the other ones so put it here run it just make sure with the test cases if those are all good which they also now submit okay cool that was the solution sorry that's the 35th leaky challenge called search insert position if you like this video make sure to like And subscribe
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
1,653
hello all right let's uh code minimum deletions to make string balance done this before but don't think i've made a video about it you're given a string s consisting only of characters a and b you can delete any number of characters in s to make s balance s is balanced if there is no pair of indices i j such that i is less than j and s i is equal to b and s j is equal to a return the minimum number of deletions to make s balance no pair of indices such that there is a b before an a so for this one i know i definitely have to remove either this b or this a here definitely all the deletions would be somewhere within this range here because you have two a's here i don't need to do anything with those the b at the end don't have to do anything with those that for sure so out of this range here what do i need to delete well i could either delete three b's or two a's so it would be two now is there a problem with that logic um i have a feeling i'm oversimplifying it hey i just realized um there must be some examples where i have to move number of a's and a number of b if i have a b and i replace this with an a replace this with a b moving all either all a's or b's is definitely not the optimal solution in this case here it's best to just remove this b and this a i see this is a somewhat difficult question how do i actually figure that out think it all depends on finding a split point so for any position i want to find out what happens if i remove all b's from this substring and remove all a's from this substring now does that work for this case here yes it does this split would be here and here so in this case i'm removing all a's from here and removing all b's from here which is not so it's all about finding a split which means i can have some prefix sums for the number of a's given a split and a number of b's given a split okay let's implement this i need to keep track of the prefix sums of size s dot size plus one and have two of these should i initialize it to zero no i don't need to i just have to say p0 at zero is equal to zero p1 at zero is equal to zero and then go through each character in the string and say ps of i plus 1 is equal to ps of i plus whether or not this character here at s is equal to a or not this one here would be equal to whether or not it's equal to b um and then we can go through each of the positions and check so given that your string has let's say a b there's actually many different positions so we have zero one two three four let's say zero represents removing all a's from the string and the feet and four represents moving all b's from the string and one represents moving all b's from this substring here just a there's none so that's fine in fact i don't need the 4 here because when i'm at the 3 that's inclusive of 3 the left sub string less than or equal to s size plus i so for zero basically asking how many in the left substring will be ps of zero or how many b's in the left substring so ps of one at i minus ps of one at zero i didn't need that's always zero so i just i didn't need to subtract that the right on the other hand is everything up to the end of the string minus ps of zero so not including i think that's correct and then we keep track of an answer to be equal to the whole string and then do answers equal to min of the answer and the left plus the right and then return enter this should be zero and it should be one the answer is 2 here and i'm thinking that the answers is 2 as well for this case all right let's give that a run and see awesome that uh seems to work time complexity would be o of n space is also o of n because of the prefix sums which is definitely good enough thanks for watching if you have any questions leave it in the comments leave a like and subscribe and i'll see you next time
Minimum Deletions to Make String Balanced
number-of-good-leaf-nodes-pairs
You are given a string `s` consisting only of characters `'a'` and `'b'`​​​​. You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`. Return _the **minimum** number of deletions needed to make_ `s` _**balanced**_. **Example 1:** **Input:** s = "aababbab " **Output:** 2 **Explanation:** You can either: Delete the characters at 0-indexed positions 2 and 6 ( "aababbab " -> "aaabbb "), or Delete the characters at 0-indexed positions 3 and 6 ( "aababbab " -> "aabbbb "). **Example 2:** **Input:** s = "bbaaaaabb " **Output:** 2 **Explanation:** The only solution is to delete the first two characters. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is `'a'` or `'b'`​​.
Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2.
Tree,Depth-First Search,Binary Tree
Medium
null
1,962
Hi gas welcome and welcome back to my channel so today our problem is remove stones you minimize the total so this is the problem statement what have they given us here they have given us a wait called Piles where your Piles I represent. Here is the number of stones Hindi rectangle file ok and here we have given you a wait so what can you do here you can perform exactly the operation this operation is yours what if someone piles i pay and number of stones is there So what you can do is, you can remove as many stones as the fluid value of N/2 from there. what you can do is, you can remove as many stones as the fluid value of N/2 from there. Okay, so what you have to find, here you have to find the minimum possible total number of stones remaining after applying the operations. So you have to perform these operations and examples of finding the minimum possible number are this is your pie, what is in it is your forest and what is this second yellow paper nine stones are okay what you can do is you can perform an operation here. Inside which, when you do what, if you have n number of stones on any yellow, then what will be the floor value of it and by you, okay, this much, what can I do from here, can you mine, okay, what can you do with this, mines? If you can then look here twice you can reduce this either you do this or do this then if here you have to reduce If you want to reduce the total number of stones, then in which operation will you perform it? Which one will have more names? Which one will have the maximum number of stones? I will perform it first so that you will think about reducing it. What answer do you have to do? How to find the answer? Finding the minimum. If yes, then when will be the minimum? When you halve a big number and mince it, then what will be the biggest number here? If the smallest number is nine, then what will be the half of nine? The fluid value of 9/2 here. fluid value of 9/2 here. fluid value of 9/2 here. This will be your four, right, so if we remove four number of students from here, then how much will be left here, this five will be left, okay, now what happened to the stones you have, five is four, five is right, now you have one operation. You have done it, now how much operation do you have left, one more is left, so now you have the option, which of these three would you like to do? There is a five here too, here there is also a 5, here there is a four, so we will do it only on the one with five because If this will reduce the loss to half then we can do either of these two things. Otherwise, if we remove the floor of five from here, the flop value of 5/2 will be floor of five from here, the flop value of 5/2 will be floor of five from here, the flop value of 5/2 will be this. If you do it from here Or do it from here, let's do it from here, so it will be three, so what will be the total, once 3 4 7 5 12, then in the end, this will be your minimum amount, this will be the total amount left after performing this operation, that will be your answer, you will add. If you make it dependent then how much will you get if you add here, you will get 12, you will return 12, okay, let us also look at this example, how many operations can we perform here, you can perform three operations, you have the option that you can here You can do it here, you can do it here, but you can only do three, so now who should give preference, if we remove the floor value of 7 - 2 we remove the floor value of 7 - 2 we remove the floor value of 7 - 2 from here, then it is 7/2. What will be the floral value of ? from here, then it is 7/2. What will be the floral value of ? from here, then it is 7/2. What will be the floral value of ? If it is three, then here 4 will be left, so this is done, your 4 is already four, this three is six, now you will have to perform the second operation because now you will have two operations saved because you have done one right, so one. If you have done this then now in which one would you like to do it in six because it is the highest otherwise if you do it here then what will you be left with? The load value of six minus six by tu will be your three. Six minus three equals tu three so here three. Now you have one more operation left. Now where will you perform? Here, there is a four. Here, there is also a four. Both are maximum, so you can do it on any of these two. So, here, four by four. Minus. If you do four by you, then you will be there, then you will be left. Okay, so what will be your total? 2 3 5 538 84 12, right? What can we do in this way, if we can solve this problem, then how will we know which is the maximum number? For this, what will we do, will we give it a priority, what will we do, we will put all the data in it, so here let's look at this example, if we put the second one here, then we will give it the maximum priority of 7, then it will be on top. Yours will be six, then yours will be three, then what will be yours, what will be four? How many times will we perform this operation, we can do it three times, so when we do it for the first time, the top element will be the maximum, we know that because the maximum priority of the priority because which The element on the top is maximum, so if we find from here, we will get 7, then what will we do from 7 by 7 we find from here, we will get 7, then what will we do from 7 by 2, if we subtract it, then how much will be left, your 7 - 3 / 2 is ok, it will be three, ok, I wrote it by mistake. Given four here, if you insert four, then four will come somewhere here, right then now how much operation do you have left, two are left, then you can do it with three, then where will you get the maximum element at the top, then you will put it at the top, then top. You will mine the top half of it, three will be left, then you will insert it, then where will the three come, here will the four come on your top, otherwise you will have only one operation left, now you can do only one, then the top will come out, 4 by 4. If you do four minus four by you, then 2 will come out here, so what will you do with this tu, if you insert it here, it will be somewhere here, you do not have any operation left, so you will not do this further, whatever element is left. What will we do? We will take each one out and add it, then four plus three by plus you, then what will happen here is 7310 you 12. If this is done, then I hope you must have understood this, we would have seen its code also. This is quite easy, see here, what will we do here, why will we take a priority and what will we do in it? First of all, we will insert all the elements in it. Right, so here we have taken the priority by the name PK and what have we done by inserting all the elements in it? Okay, after that what will we do by taking a Vile loop - - This means what operation will we - - This means what operation will we - - This means what operation will we perform in it, what will we do in it, will the top element come out, okay, we will also pop it, then what we will do is push it in X - Floor X - Floor We will add it in one element, okay, we will keep adding it till our PK i.e. okay, we will keep adding it till our PK i.e. okay, we will keep adding it till our PK i.e. priority is not being done, then we will add all the elements in all, then what will we do in the last, we will return it, okay that is ours. What will be the remaining stones because if it is minimum then I hope you have understood this. If you liked the video then please like, share and subscribe. Thank you.
Remove Stones to Minimize the Total
single-threaded-cpu
You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times: * Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it. **Notice** that you can apply the operation on the **same** pile more than once. Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_. `floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down). **Example 1:** **Input:** piles = \[5,4,9\], k = 2 **Output:** 12 **Explanation:** Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are \[5,4,5\]. - Apply the operation on pile 0. The resulting piles are \[3,4,5\]. The total number of stones in \[3,4,5\] is 12. **Example 2:** **Input:** piles = \[4,3,6,7\], k = 3 **Output:** 12 **Explanation:** Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are \[4,3,3,7\]. - Apply the operation on pile 3. The resulting piles are \[4,3,3,4\]. - Apply the operation on pile 0. The resulting piles are \[2,3,3,4\]. The total number of stones in \[2,3,3,4\] is 12. **Constraints:** * `1 <= piles.length <= 105` * `1 <= piles[i] <= 104` * `1 <= k <= 105`
To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks
Array,Sorting,Heap (Priority Queue)
Medium
2176
1,675
welcome to Pomodoro Joe for Friday February 24th 2023 today we're looking at lead code problem 1675 minimize deviation in Array this is a hard one you're given an array nums of n positive integers you can perform two types of operations on any element in the array any number of times if the element is even you can divide it by two if the element is odd you can multiply it by two 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 okay and let's see we have at least two elements but fewer than five times ten to the fourth and the elements can range from 1 to 10 to the ninth that's a big range all right so we'll put 25 minutes on the Pomodoro Timer and get started all right first thing I always like to do is create some result placeholders let's start with that and now I'm looking for the minimum value so I'm going to set this to infinite to start with and we'll work our way down and then we'll return result at the end okay so I'll walk you through this step by step we'll build this up from basic principles until we have a working solution now the first thing we need to do is figure out how do we approach this problem so in this problem we just have this list of nums and we're trying to find the minimum deviation between any two elements so I think the first thing that I'll do is figure out the current minimum deviation before performing any operations and for that let's see we could compare all the elements to each other but I don't think we need to do that we really just need to find the maximum element and the minimum element and that's going to be our minimum deviation that the array can have so that's pretty straightforward we just Source the numbers and now we can set our result to this new minimum deviation that we can find so the sorted numbers are going to go from lowest to highest so we'll take the highest element and we'll subtract the lowest element and that gives us our current result before we perform any operations so we can actually get rid of this up here because we already have a better answer the next thing I think I want to do is figure out how do we use these operations to impact our minimum deviation here looks like we have two operations we can do we can divide even Elements by two or we can multiply odd Elements by two okay so here's a little diagram of our goal here we have some low value and some high value and we want to bring those two closer together that's basically all it comes down to we have a low value a high value that's our current minimum deviation I need to bring these two closer together to get a smaller minimum deviation now from the low end we can make these go higher and from the high end we can make them go lower so we can take the lowest element and multiply by two to get it higher we can take the highest element and divide it by 2 to make it go lower so let's see on the low end with odd numbers we can multiply by two so we can make odd numbers go higher and on the other end we can make even numbers go lower by dividing by two so this is kind of a diagram that illustrates where we're going with this we can bring our lower values toward the high we can bring our higher values toward the low but only odd values can increase and only even values can decrease so we'll basically look for odd values at the beginning of our sorted nums and push them higher and we'll look for even values at the large end of our nums and push them lower that's pretty much all we can do so let's just start with that all right let's start by pushing the lower numbers higher so let's see while the numbers at the low end are odd we can push them higher so I'll sort of nums at 0 mod 2 is equal to one then we can push this higher so we'll just say we'll just multiply that lowest number by two oh but now that we've changed this number we have to resort okay that's already a red flag we'll probably come back to this so sorting over and over again is already an indicator that we probably need to do this a different way okay so now we've brought our lower end towards our upper end we need to do the same for the upper end okay so now while our highest number is even let's divide it by two to bring it lower and again because we've changed this value we're going to have to resort another red flag okay now we've brought our highest value lower and our lowest value higher let's calculate a new result so let's see our result now will be well we'll probably need the minimum of either the result or this new Range so what will that be okay so this is pretty good I think we might need to actually do some recalculation of our result sooner than this though for example this could be bringing numbers down that give us a smaller result before we finish this entire Loop there could be some intermediary results that are actually lower than our current result so let's recalculate this result every time we go through that way we catch any minimum results let's try this okay we pass so again we're just sorting our numbers finding the biggest number the smallest number and the difference in between then we're going to take all of the odd numbers that are on the low side and we're going to bring them up by multiplying them by two so we'll bring them closer to the high end and then we'll find all the even numbers on the high end and we'll bring them lower by dividing by two let's submit this and see how we do foreign but we do get a wrong answer in here so we beat 59 out of 75 but we've got one wrong answer now I think that one wrong answer could be because we're not calculating this result while we're changing our minimum values we're only calculating it while we're changing our high values we might need to do both okay so we didn't get any wrong answers this time but we do run out of time we only go through 72 out of 75 test cases although 72 out of 75 is pretty good we're really close we just need to pick up those last three test cases okay so how do we optimize this we have a decent solution it just needs to be optimized it all comes back to this one red flag here now resorting these numbers over and over again is a lot of extra work especially because they're mostly sorted all we're doing is changing one element now there's a data structure that we can use that will help us with this that's a heap the Heap is a sorted data structure that sorts on insert so it remains sorted the entire time we don't have to resort every single element so let's use a heap and in Python that is the Heap Q Library all right so now we will transform this whole thing to use a heap instead of sorted nums this is going to get a little bit complicated so let's break this down now in the very beginning well we're bringing lower numbers higher we'll want to use a Min Heap that means we'll be able to find the minimum numbers very quickly so let's create our Min heat to start with so to create a heap you just call heapify on a list so in this case it's our sorted nums and that's it to create our Min Heap okay now the mean Heap will always have the minimum value at the zero index so instead of saying sorted nums here we can say Min Heap and then this will be replaced so I'll just comment these out so in this case we actually have to do a pop and a push so we'll do Min num is a heat pop on our main Heap then we'll multiply it by two and then instead of having to sort our nums we just will do a heat push and that keeps everything sorted all right this looks pretty good so while the smallest number on our Heap is odd we'll pop it multiply it by two and push it back onto our Heat all right what about this now the sorted numbers was sorted every time so we could get our max value really easily and our Min value we can still get our Min value here really easily by just using the Min Heap but this max value is not the same we're changing our values inside our mint Heap we can't get the max value that easily so we'll just have to keep track of that ourselves so we'll set it equal to our maximum from the sorted nums to begin with and then we'll have to just keep track of our new values that we're pushing in and possibly replace our max value because we're multiplying this Min num by two it's possible that we will exceed our Max num so we'll want to keep track of that and then down here this will be Max num minus our Min heaps minimum value so that takes care of the low end what about the high end we'll have to do something similar for the high end but the high end gets a little bit more complicated because this needs a Max Heap now python doesn't give you a Min Heap and a Max Heap they just give you a heap that is a Min Heap by default in order to get a Max Heap you have to basically set your values to their negative which means that the largest value will be the most negative value or the minimum value so let's write some helper functions to help us out with this okay so to help us with the higher side the maximum side I wrote some Max Heap push Max Heap pop and Max Heap Peak so these helper functions essentially just convert our items from positive to negative values while they're stored in the Heap and then returns them as positive values when we pop them out so now we need to create our Max Heap let's do that here so in this case we actually need to start our Max Heap with negative values so that gets our Max Heap initialized then we'll heapify okay so now we've heatified our Max Heap and I think we'll need to do the same thing we did up here with keeping track of our Max num I think we'll need to keep track of our Min num so let's do that here okay and now instead of looking at our sorted nums at the largest value we need to get the largest value from our Max Heap so we'll do a heap Peak on our Max Heap and just as we did with the minimum we'll change these guys all right so we'll do a Max heat pop on our Max Heap to get the largest value and then we'll divide it by two and then we'll check our Min num again when we divide this maximum by two we could be going below our minimum value so let's just keep track of that minimum value and then instead of having to do the sort we'll just do a Max push or Max Heap and then in here we need to change these so this is going to be our maximum number now which is just our Max Heap Peak and this will be our minimum value our minimum okay let's give this a shot let's see I did something wrong here oh right the Min Heap needs to be equal to so that was setting it equal to the function which is not what we want we need to actually initialize our midheat here and then we heapify it okay I am running low on time so hopefully we don't have any typos okay that works let's see if we can pass and we pass we don't do very well with our run time here we only beat 41 for runtime and we beat 64 from memory so we pass we don't do great but we pass one thing we can do which I didn't do initially so we have these sorted numbers there could be duplicates in here we don't know so let's remove our duplicates before we start doing all this processing so one way to remove duplicates is creating a set so we create a set that will remove duplicates then we turn that into a list and we sort them so that's going to remove whatever duplicates we have in our list and I am almost out of time see if this gains us anything and we gain a huge increase we beat 100 for runtime and 31 from memory that is fantastic I'm super pleased with that all right that's it for me hope you had fun hope you enjoyed this hope you learned something hope you can try this one on your own this is definitely a tricky problem so check this one out all right that's it for me
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
43
foreign problem number 43 in this we multiply two strings welcome to the video let us begin we are given two non-empty begin we are given two non-empty begin we are given two non-empty non-negative strings consisting of non-negative strings consisting of non-negative strings consisting of digits only they don't have any leading zeros except when the number is itself 0. we have to find the product of the two strings without using big integer Library maximum length of each string is 200. the first method is a computer simulation of elementary math we multiply numbers in str1 and str2 to get a new string first we check and Edge case if either of these strings is 0 the result is also zero consider the two numbers their multiplication is shown here for convenience we reverse these things and call them first and second we Define a list card products turn button we will append three products in this list in a loop we fetch the digits in the second string and also their indices at index 0 digit is 7 we will find product of 7 with the first string for which we call the function get product in the first call of this function index is 0 D2 is 7 and the string first is 983 we Define carry equal to 0 and we Define a list called Product as index is 0 no 0 is appended to it in a loop we fetch characters from first one by one and call them D1 in the first iteration D1 is 9. multiplication of D1 and D2 plus carry is 63. 6 becomes carry and 3 is appended to the product in the next iteration D1 is 8 so multiplication plus carry is 62. so carry becomes 6 and 2 is appended to the product in the third iteration D1 is 3 so multiplication plus carry is 27. so 2 becomes carry and 7 is appended to the product when we come out of the loop carry is 2 Note it will always be a single digit if this carry is not 0 we append it to the product finally product is returned to the main function and is appended to the list products in the second iteration of the main function index is 1 so 1 0 is appended to the product at the beginning D2 is 6 in this iteration at the end of the get product function 0 4 3 2 is appended to products and in the third iteration the third list is appended which has two leading zeros at this point the loop ends and we have computed all the three products now we have to add these integer lists to get the final answer we call another function named add products which adds all these products in the list there is always at least one list present in products we pop out the last list from products and save it as total this reduces one entry in products all the remaining lists in products are processed one by one in a for Loop in the first iteration the first list is called Product next we Define carry with initial value 0 and an empty list called new Total next we take zip longest of total and product which also fills zeros to make them of equal length and we start a loop that runs over all the digits in them we add digits of total product and carry in the first iteration the sum is three so we append 3 to new Total and zero becomes next carry in the second iteration the sum is 2 is appended to new Total and 0 is the next carry in the third iteration sum is 16 so 6 is appended to new Total and one becomes the next carry at the end of the loop we get this if carry is not 0 it is appended to new Total in the last statement of the outer loop new Total is saved in total in the next iteration of the outer loop process is repeated with next product and the new Total is obtained at the end of the outer loop total of all the three products is obtained which is returned to the main program and is saved as result in the end we process the digits in the reverse order convert the digits to characters and join them as a single string which is returned as the final solution M digits of first and N digits of second are multiplied with each other in time M into n then M products of length M plus n are added to each other so time complexity is M into M plus n reversing of strings at beginning and end is of the order of M plus n which is negligible compared to the squared terms M products are saved each has length M plus n so space complexity is of the order of M into M plus n there is a scope for space optimization in this method without any change in its time complexity so now we will discuss the space optimization of the earlier method instead of saving all the products we can find each product and immediately add it to the final result once again we consider the edge case if either of the strings is 0 the result is also zero consider the same problem once again we ensure that both the numbers are on zero and then reverse them we now create space for result we know that the maximum size of result will be M plus n so we append six zeros to result next we iterate over the digits in second in the first iteration index is 0 and digit is 7. we use the same function get product to get the product of 7 with 983 and store the result in the list product next we add this product to result we use the same add strings function used previously and the new value of result is obtained in the second iteration the old value of product is not needed so product of 6 with 983 is stored in the same memory area note that this product has one leading zero this product is also added to result and the result becomes as shown product in the third iteration is 1 into 983 with two leading zeros this product is also saved in the same memory area and added to result this becomes the final value of result before proceeding further we must remove any trailing zeros present in the result we notice that one extra zero is present in the result we pop out that zero now we join the character form of the digits in the Reversed order and get the desired string which is returned to the main program the computation is same as before so time complexity is unchanged extra memory is used only by product and result both are of size less than or equal to M plus n same is the size of the output string so space complexity becomes M plus n so far we have been finding a product of all the digits and then adding it to the result with a simple change in logic we can add the products of the digits directly into result once again we ensure that neither of the two strings is zero we make room for result and reverse the strings we Define a loop within a loop to get all the pairs of digits in the two strings next we find the position in result where the entry is to be updated in the first iteration both the indices are 0 so position is the beginning of result old value of the result at pause is the carry 9 into 7 plus 0 is 63. 3 goes to the result at pause and 6 is added to result at pause Plus 1. in the next iteration index 1 becomes 1 while index 2 remains a 0. pause is the sum of the two indices so pause becomes one eight into seven plus six is 62. 2 goes to cos and 6 is carry that is added at plus one in the next iteration index 1 is 2. 7 into 3 plus 6 is 27. 7 goes to pause and 2 is carry in the second iteration of the outer loop index 2 is 1 so starting value of pause is 1 and not 0. 9 into 6 plus 2 is 56. 6 goes to pause and 5 as carry is added to result at pause Plus 1. do not worry if an entry after carry is of double digits it will be taken care of in the subsequent iterations now 8 into 6 plus 12 is 60. 0 goes to pause and 6 added to pause Plus 1. in the next iteration value is 26 6 goes to pause and 2 is carry process continues at the end of the two Loops the result becomes this next we remove the zero if it is present at the end and return the result after joining all the digits in the reverse order in the form of a string constant work is done in the double Loop so time complexity is the number of pairs of digits that is of the order of M into n there is some saving in space because products are not saved separately however this phase complexity remains same which is the size of the output string I have modified the program further we only add products in the result in the double Loop and carry updations are done only once in a single Loop execution time is one third of the earlier program but overall time complexity remains same as the max length of strings is 200 characters there is no risk of overflow in the results the sum is much less than 32767 which is the limit even in two byte integers thanks for watching my videos and supporting my work stay tuned
Multiply Strings
multiply-strings
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. **Example 1:** **Input:** num1 = "2", num2 = "3" **Output:** "6" **Example 2:** **Input:** num1 = "123", num2 = "456" **Output:** "56088" **Constraints:** * `1 <= num1.length, num2.length <= 200` * `num1` and `num2` consist of digits only. * Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
null
Math,String,Simulation
Medium
2,66,67,415
100
Hello everyone, Evgeniy Sulima nov is with you and today we are looking at solving the problem easily from number 100 cm3, according to the conditions of this problem, I was given two binary trees and I must implement a method that checks whether these two trees are at peace with themselves or not, that is, for example, there are two trees 123 and I understand that these two detmers would be equal because the structure is the same and correspond and are also equal to each other in the second example I have a discrepancy in the structure, that is, here the left is not equal to 2, the right is driven away and here the mirror left is equal to nope is equal to the right is equal to 2 therefore two trees are uneven, but the answer falls in the third, which means that we see that the two trees have the same structure, but the correspondence between the meaning of the raccoons is not observed, that is, here the left one is equal to 2 and here Libya is equal to 1 and vice versa for the right ones, but yes, now we look at the structure itself class friends at the entrance I get like a router, that is, the top left and right element here I drink and Beijing is indicated, each not has three fields for itself, this is and we'll try not love 3 well, troit, that is, a link to the left and to the right element, then we'll think about it how can I solve this problem, then a recursive approach directly suggests itself, that is, I can very easily understand at each iteration for two mods whether day 2 died by itself or not, that is, I say that if at some point you are not raving you well then In this case, I boldly say that 32 trees are not equal, that is, I rotate falls further if at some point I understand that one is not aravind and the second is not equal, so in this case, then I also say that these two trees are not equal to each other, that is and vpi is equal to 0 or Q is equal, otherwise in this case I say that two trees with them are unequal ranfors and are equal to 2. In fact, we will be with each other only when I perform the same checks for each floor, that is, for each level for each element and I will come to the very end of the end, will I start so that the elements become equal to cash, that is, I say that and p is equal to and drink is equal to and then in this case I return the pipes now I want or perform all this logic for each pair I this I can do it very easily, that is, I write red top is so in two and that is, call the same function for pi lift and you left and you also created the same function for pi right and kai. right everything seems to be correct, that is, we look at the example let's say on successful I come to this floor I ask you both are equal cash don't play no failure to do what one of you is equal to all he says no we're fine we move on between your value between in each other are not equal to each other yes no equal everything is good excellent let's move on we perform this operation for each floor, that is, here for two twos and for three threes, that is, they are equal, so we get pipes for the second example and for the first yes, it’s a pity and second example and for the first yes, it’s a pity and second example and for the first yes, it’s a pity and everything is fine, but here give us a problem, I come and understand that here I have the left one not, I have a two and the right one is on y, that is, this condition is met, I return the phones in this one, my legs are on the second floor, here they work out the conditions translated is not equal to q in let's try to run this solution build that there are no compilation errors from forum we think and everything is fine, that is, it worked now he doesn’t know how and worked now he doesn’t know how and worked now he doesn’t know how and Torina is considered good form in years in algorithmic problems, she is considered good form in commercial work, now it’s not good form what I’ll do now it’s not good form what I’ll do now it’s not good form what I’ll do here, you can reduce the number the code is essential, that is, we know that according to the specification for each we don’t according to the specification for each we don’t according to the specification for each we don’t need parentheses if we are working with one line, then here I write about the true turn here I return for in a hurry removing the parentheses here I also remove the parentheses I write aratorna falls and you can even use these remove the gaps and everything will be fine, and according to the results, I have four more lines of code to publish through, let’s run four more lines of code to publish through, let’s run four more lines of code to publish through, let’s run this solution so that we don’t make mistakes, and after that don’t make mistakes, and after that don’t make mistakes, and after that he tries the solution to combine the final well done; I missed it final well done; I missed it final well done; I missed it here, the compilation was yes, everything was fine, now I click farm to run it through different test cases and the project, everything was fine, we see that the problem was successfully solved quite quickly, that is, the complexity of this solution is o.n. that is, we must go through the slim o.n. that is, we must go through the slim o.n. that is, we must go through the slim case for all memory elements, we select one of them for a new memory, that is, are we working with the same nodes, and with this we finish, I say goodbye to you until we meet again
Same Tree
same-tree
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. **Example 1:** **Input:** p = \[1,2,3\], q = \[1,2,3\] **Output:** true **Example 2:** **Input:** p = \[1,2\], q = \[1,null,2\] **Output:** false **Example 3:** **Input:** p = \[1,2,1\], q = \[1,1,2\] **Output:** false **Constraints:** * The number of nodes in both trees is in the range `[0, 100]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
1
Hello hello everybody welcome to my channel it's all the very famous problem tourism delinquent problem number 520 this problem given energy of India has written in basis of two numbers given to specific target that they have one solution and you may not use this element sorry for example 1327 1115 That's Not Every Element So What We Will Do And 09 2014 Festival To Constipation Simple Solution And Have To 10 And At Mid 200 Cold Increase Targets Nine Show Vijay Simply Root For Children Tools 143 From 202 Number Of Element Sister - Vanshdhar Insisted 202 Number Of Element Sister - Vanshdhar Insisted 202 Number Of Element Sister - Vanshdhar Insisted You For Brighter to idea plus one to end will check the independent se names of ideal place for a day that is equal to target TV and notice will return i costing repair and will regret for all subscribe to strengthen at the same time complexity of dissolution inside the time complexity of Subscribe to Subscribe button on Thursday 191 Father Optimized This Show As they know about solution is the time no1 Space to Space Can we do something like Aadha No time complexity Subscribe We can increase the places to try to reduce the time complexity subscribe our Channel and subscribe the example 2014 speed 900 to 1000 and one to three will feel the values ​​into a 1000 and one to three will feel the values ​​into a trip basically Sotheby's to visit in 100 index valve widget index 2nd ed 2nd T20 - 2 eggs contain acid attacks from witch T20 - 2 eggs contain acid attacks from witch T20 - 2 eggs contain acid attacks from witch app is not equal to the lava the map That dot net of target - number basically to That dot net of target - number basically to That dot net of target - number basically to just e did not inform and they will drop oil member solution time will explain first time limit for be id event e that teaser map and which day is lies with new house map and evaluation pass for in tie 2202 Popular Tower Map And Electronic Plus Neither Any Sacrifice Plus Neither Any Sacrifice Plus Neither Any Sacrifice Will Use This Is The Temperature Of Side Map Don It Contains Key For Target 900 Fiber The Bank Will Also Have Checked In Text Mod A Call I Not Equal To Map Dot Net Target - Numbers of I effective till Target - Numbers of I effective till Target - Numbers of I effective till swift truth on Vijay Seervi new in top player icon considered player icon considered player icon considered a target - Names of I Dhowe literate and a target - Names of I Dhowe literate and a target - Names of I Dhowe literate and Vijay written a b road and problem and ladies sexual more return to compile tower up solution hai you slept Pipad City has compiled and submitted that Addison updates what is the time complexity of this is one rupee each year in the sequence of butter give one time complexity of dissolution and subscribe maps open to all elements in first time complexity and complexity of dissolution and is open So Acid * Pass Can We Do It In This Way So Acid * Pass Can We Do It In This Way So Acid * Pass Can We Do It In This Way Can Do Not Wick And Which Aims To Be Written Enfield NSS Edison To The Number White 56001 On Thursday Share Thank you liked The Video then subscribe to the Page if you liked The Video then subscribe To My Channel press Bell Icon to get notification Thank you for watching
Two Sum
two-sum
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. You can return the answer in any order. **Example 1:** **Input:** nums = \[2,7,11,15\], target = 9 **Output:** \[0,1\] **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. **Example 2:** **Input:** nums = \[3,2,4\], target = 6 **Output:** \[1,2\] **Example 3:** **Input:** nums = \[3,3\], target = 6 **Output:** \[0,1\] **Constraints:** * `2 <= nums.length <= 104` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109` * **Only one valid answer exists.** **Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Hash Table
Easy
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
1,844
all right howdy guys this is uh Josh here with another Elite code question so today we're doing leak code uh question number 1844 replace all digits with characters you are given a zero index string s that has lowercase English letters and it's even indices and digits and it's odd indices there's a function shift c x where C is a character and X is a digit that Returns the X character after C for example shift a Char a and then into five equals F and then shift at Char X zero equals X for every odd index I you want to replace the digit s i with shift s i minus 1 and S I return s after replacing all digits it is guaranteed that shift s i minus 1 and S I will never exceed Z alright so this one's um this is marked as easy it's pretty easy one I'm gonna go ahead and fling a like on in like that um yeah so here we have the example here so this is the character and then this is how many characters um after the um the first character that we want to give so one character after a is B and then one character after c is should be D and then yeah as you see here e and then f so yeah so the way I this is gonna be my solution it's not like the most uh fastest one but uh this is this helped me learn about um ASCII digits kind of a bit more because whenever I do these liko questions I always see like a I always see people type this they'll do like an equation so like we'll do like resolve plus equals s I and then I'll always see this like minus Char zero I always wondered like what this Maya 0 represents and so um yeah so today if you in case you're new to leak code or you're curious about like doing this question this is pretty much my answer and this is how I solved it so first let's go ahead and make this variable here or this function the shift function um so we'll do we want to return a char as it says here so we want to have two parameters so we want to have shift and then we ought to have um the first parameter be a Char and then the second would be an integer so we're not going to do anything too crazy here we'll just call it shift and then Char a or I'll do Char C actually on that integer number and then here it's fairly straightforward so in my last video we talked about ASCII characters and the same applies for this question here um we're going to want to know how to convert a Char variable into a like a integer so here we go so we'll do just we could just do this C plus number all right so for those of you that didn't see the last video um let me go ahead and write this it's going to be a quick little edit here okay now we're back so I went ahead and um create this variable called ASCII and we're sending it to the representation of a char so on the surface you'd think you know if you're new to programming you'd think oh okay well uh shouldn't it be this I shouldn't our variable be like something like this shouldn't be a Char but actually all characters and programming are actually number representations using the um using ASCII and so what we can even do here we get set Char to 90. which we'll do ASCII to I don't remember exactly what uh result the Springs out but we'll find out in a second ASCII to undefined because I added two C's instead of two eyes that's unfortunate so I guess I'll make this a bit clearer so when we hit run here as you see we don't get any errors I should have used inline that sucks so as you can see here we have 97 and this is the integer so the integer representation of the a Char or a character is 97 and ASCII and then for the actual character um the number 90 oops the number 90 represents the letter Z here let me all right I made a brief edit here just to make it a bit easier to read um added the end line here but as you can see here 97 is the uh ASCII representation of the a character and as you can see here this is the Char variable so ASCII 2 90 is the representation of the letter z so with this knowledge what we can do is we can make this function here whereas Char where it turns a Char and then we just simply add the character plus the number um so this number here is going to be pretty much the equivalent of right here s dot i and this should be the placement of the string which is here and yeah so let's go ahead and we went to our main function here we'll do string result equals we'll just make it blank for now just initialize it blank um so since we have to go through a list of characters we want to whenever you have to go through something always keep in mind like okay we have to do either a for Loop or for each Loop for us it's better to do a for Loop here because it pretty much tells us here that we're going to want to use the wherever we're at in the loop we want to keep track of wherever we're at in the loop and it's easier to do that with a for Loop instead of like a for each Loop um so let's do we're not going to do anything too crazy here so I is less than S size and then I plus all right so now what we want to do is we want to make an integer we're going to do number and we're going to set this to s i minus zero so you're probably wondering like okay well why are we doing this why are we subtracting minus by zero so the reason why we're doing this is because remember this as key equivalent that we have so what's happening is when this function gets called it's going to take the character and it's going to take the ASCII equivalent of that character the number and it's going to add this number to it so the reason why we're going to subtract 0 we're actually subtracting the character representation the ASCII representation of zero this is pretty much a quick way to convert a chart data type into an integer data type so now what we do is we just do an if statement here so if uh s dot i oops we'll do s i modulus so the modulus operator pretty much the remainder of whatever this is if it's as long as it's not zero or if it's not zero but what we want to do is we want to have result plus equals um shift and then I want to do our I minus one and then the number all right and then we want to else and then for the else statement let's do plus c we just go ahead and add whatever's in the string or just add it to a to our result variable and then from there on we do is just return our result so to recap and we went ahead and made a new function called shift uh pretty much copying the parameters required um on this sentence here so we have one character and then we pretty much what we're doing is we're adding the ASCII representation of these together and so um and so what this will do is this will give us the alphabetical number or alphabetical representation and the Char format so then we made that and then we went ahead and you know placed our create a variable and memory so we can store our result create a for each Loop since we have to iterate through all the characters and the string and so the reason why we put this here so we have s i minus Char zero we do this because this is actually a Char representation of an ASCII uh number so whatever character this is the s i is so let's say a we're going to subtract uh Char Zero from it to get the uh integer representation of this number so then what we do is we do run our if statement so if I modulus 2 does not equal zero so this pretty much checks if the I is even or odd so if it's even this is going to return zero but if it's odd it's going to return um it's going to turn a number that's greater than zero or anything other than zero and so once it does that then we know that it's an odd number and then we go ahead and we run our function here our shift function that we made and then anything else it just gets returned as um the string that's already present so like for example a so a sense a is in the zeroth position it'll this will probably return zero and so we just do the else and then we'll just do um it'll just return the a character so if we run this we get accepted and yeah and then that should be all she wrote yep so yeah hopefully guys you found that helpful yeah it's definitely not the uh it's not the cleanest of solutions but this is what I came up with uh the oh the time complexity for this should be o of n because we're iterating through all of the pretty much iterating through every single um character in the string function and so the bigger that the string parameter that gets fed into it the more time it's going to take so it's going to be o of n so yeah hopefully you guys enjoy it and hopefully you found it helpful adios
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
290
Hello friends uh very happy New Year so in this video we will solve lead code daily challenge problem one that is the first day of January and the problem named is word pattern so we are given a pattern and a string s and we need to find if string as follows the same pattern so here follows means a full match and there is a bijection between a letter and pattern and known empty word in s okay so let me take the first example is a b a and my word is dog cat dog okay dog cat and dog right so this is my string and this is my pattern right so I just need to check if my string follows the pattern and pattern follows the string means I mean that there is a bijection between both of them so what do you mean by bijection so here initially the first position is a and the last position is a so in this pattern or in my word the same thing should be there so dog and dog are already present similarly B and B so here should it should be the same word means it is not required that it should be the cat only it can be anything it can be ABC so that this is also a correct solution so this is called bijection and similarly if I check if I first start checking from here then dog there are two dogs I mean first and the fourth position there is a dog so in the similar fashion in my pattern also the first and the last position uh letters should be the same so here it is letters here we have letters and we here we have words okay so yeah it if the problem looks simple yeah it is a good I would say combination of I would say hash map and uh One More Concept so yeah it is a good combination of that you could think directly of solving it using an hash map but uh yeah you would get stuck when you have to check by both ways right see if you had to check only if the string follows the pattern then you could have done in using simple way and yeah that is we all know right but now how would you solve this problem okay there would be a possibility so yeah we would use a combination of hazmap and set okay yeah you could think of a much more different ways brute force and all that but this is not uh I would say this is problem is stacked as an easy category problem so we can I'm directly telling you the solution so uh initially I would first of all see this is given as a string okay this entire what is given as a string separated with a space okay so we just need to convert this string to Vector of string y because we need to uh maintain the indexes right so we need to maintain the index of this I need to change to Vector of string so for that I will use C plus STL Library function I stream which will convert this space separated string to Vector of string okay so that is uh this is so this is a zero Index this is first second and third correct and similarly for the pattern this is our these all are letters so we need we will require a map right would we require a map to see that c first of all I would start iterating now I would start iterating from my pattern okay I would start iterating from my pattern so initially I am at a right I would check if my a exists in my map or not means either a is mapped to any of the words or not so initially a is not mapped to any of the words so I would map it to dog okay and similarly at the same time I would in insert the word in my set so in my set I have a till now okay now why I am doing this it is a very important thing to notice right so if before inserting into my map I would check if my set has already that one present or not I would say that letter present or not and if that letter is already present that means that there exists already a mapping means a was previously mapped to some other character right but now it is mapping to some other character so I would directly return a false from there so if my current character is present in my set okay then I would find file see first thing to find out is that if it is present in map if it is not present in map then it should not have been present in set also right but if we find out that if it is present in set that means that it was mapped to an uh some another character previously so a would have map a would have been mapped to some let's say cat okay now it is inside okay and it is in map also right but it I mean what in map in my map I would need to check if a is mapping to dock right because current mapping is a and Dot correct so uh both we would run a loop from equal to 0 to equal to n right so I would map from s of I which is my string and my pattern of I or pattern or whatever you need to check okay so I would check for both of this right so I would have to check for mapping a is to do so if my a instead of mapping is not present in my map and if I found that it is present in set a is present in set then that means that in my map it there exists a mapping where a is not mapped to dock but a is mapped to cat and finally here I would directly return false okay and if none of the cases is this then I would insert in my map and insert it myself so let me explain it to again in a simple words see initially this is my dog cat let's say base map to dog game and uh yeah again it is also mapped to dog okay so this is the case okay so now a I would find search for Aries to Doc mapping in my map would be of character and string correct whatever you can name it as it is so I would search for Ace to dog mapping it does not exist so in my set I would check my account if my if a exists or not so it does not exist so I will insert it and in my map also is to Doc mapping is now inserted correct now B is to cat mapping similar is the case b is to get mapping does not exist in my map and does not exist in B does not exist in my set I would insert it and B is to get mapping I would paste in my map now I have B is to dog mapping correct base to dog mapping is there now I am searching my map I am searching if my ma of b m a of B is equal to V of oh yeah this is that name this Vector as V okay V of I means current index is 2 so 0 1 and 2 and 3. so what my Mi of B would give m a of B in my map already the value stored is cat and what is V of I it is dog so is this equal no it is not equal that means in my set B would the B has different mapping right that already exists in my map so here I would return false because this is mapping this is not a bijection right initially B is mapping to get now B saying that I want to map to dog so this is the case I was explaining to you so that is the reason we require set and finally I would return a false from here correct so we would break out from the loop else finally go to tone true I would show you the code now yeah so I take I took one vector B and yeah as I told you this is a C plus St Library function string stream ISS and then what I am doing I am pushing each of the words in my space separate words in my Vector I am taking one set initially I am pretty sure that the number of correct letters in my string pattern and the number of words in my string should map and if it is not the case I would finally here directly return a false then I told you I am taking a map okay I am searching for my map if the character is present in my map and then I am checking if the mapping is correct if it is not current then finally I will return a false over here and if a character is not present that means I am checking if my if it is present in my set so if it is present in my set and map does not give the correct mapping then that means that the previously it was matched to some another character right so I would return a false and if it is not the case I would insert in my map and in my set finally you would return a true correct so the time complexity would be bigger off and only yeah and in case if you have any doubts comment it down I would try to explain it to you again and thank you for watching do not forget to like And subscribe to the channel for such content yeah thank you
Word Pattern
word-pattern
Given a `pattern` and a string `s`, find if `s` follows the same pattern. Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`. **Example 1:** **Input:** pattern = "abba ", s = "dog cat cat dog " **Output:** true **Example 2:** **Input:** pattern = "abba ", s = "dog cat cat fish " **Output:** false **Example 3:** **Input:** pattern = "aaaa ", s = "dog cat cat dog " **Output:** false **Constraints:** * `1 <= pattern.length <= 300` * `pattern` contains only lower-case English letters. * `1 <= s.length <= 3000` * `s` contains only lowercase English letters and spaces `' '`. * `s` **does not contain** any leading or trailing spaces. * All the words in `s` are separated by a **single space**.
null
Hash Table,String
Easy
205,291
1,721
hello friends welcome to coding interviews channel 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 problems such as bfs dfs dynamic programming and so on please check them out i have uploaded the code for this problem to the github repository you can get the link from description below this video let's jump into today's problem swapping notes in a linked list you are given the head of the link list and an integer k written the head of the linked list after swapping the values of the kth node from the beginning and kth node from the end the list is one index so basically the problem statement is we are given with a linked list and a value k okay and the linked list we are given with the first node basically the head node of the linked list and k is denoted as basically the one case starts with one index right that's what it said so essentially what we say is just like how you count from one so one two three four five right so that means this one is the first element in the linked list two is the second element in the linked list three the third and the element in linked list and so on and we are given with the k value right so we are supposed to swap the k from the starting and kth node from the ending those values and then written the linked list right the head of the linked list basically right so if you look at the example one right so the head is basically one two three four five that is the order head is pointing to the linked list ah node with value one right and k is given as two so now we have to swap the values in the second node from the beginning and second node from the end right so what is the second node from the beginning in the example one obviously the node two and what is the second node from the end of the linked list it is four so now we have to swap those values two and four that is how the second picture basically the second one after swapping it looks like this so four is going to come into the second place and two is going to go to the fourth place so this is the linked list that we are going to return so that is the reason why output is one four two sorry one four three two five right so that's how it is going to work simply so let's look at and try to understand more into this problem right so now let's say we have n nodes in a linked list but we are given the access to only the head node right if we want to determine what is the kth node from the start and what is the k-th node from what is the k-th node from what is the k-th node from end there are multiple ways doing it right so for example let's go do it ah in the first way right so the first way is about ok count the nodes in linked list right so that's the one right so first one we can do count node in the linked list right so once we do that right basically what we can essentially do is subtract k from that right subtract k from that simply right so let us call this as n nodes right and to get kth node basically from the beginning k from beginning this we can get it simply while we are counting the nodes right so that is another optimization we can do it but assume that we have n nodes that is the first pass so let us say this is pass one ah and get the kth from the beginning it is pass two right and the third step is about kth from end so what is the kth from end will become basically you need to count the k from android in this particular case there are 5 nodes right so 5 nodes and second k is equal to 2 right second from the end would be what so 5 minus 2 plus 1 right so that would give you the kth node from end right so what is 5 minus 2 plus 1 it's 4 so that's the node that we so in this particular example right the num node number and node position are matching it so happened that but yeah so we are looking at the position is fourth right so this is one way right so that means we have done in three passes so basically we in the past one we were able to get the nodes count and the second pass we got the kth from beginning and third pass we got the key from end and after that we just do as the fourth step swap right so this is what we need to do right but can we do any optimization here yes definitely we can do optimization right so let us call this as approach 1 right and let's look into the approach 2 right so let me take this and see if we are able to improve let me copy this all right and paste it and call this as approach 2. what can we do so in the past 1 we are able to do the n right so can we combine pass 1 and pass 2 so all it takes is while you are trying to count the n right you can just get the kth from beginning and in that pass one itself right so essentially what we are saying is we get the count of the node and what we are going to do is get this and kth from the beginning this is all we can do it in one pass right and then we have to do the pass two from the kth from the end right so this will be our second step right and the third step would be basically swap so in this particular case also since we know n in this particular case n is equal to five minus two plus one so this will still hold good right in order to calculate the kth from end so in this particular case what we essentially did is we combined the step one and step two into one single uh pass that way we are down to two pass now can we do even better like not even going to do the second pass can we do the single pass and get away with the right answer yes so approach 3 right so in this particular case what we are going to do is we are going to count basically the first pass will remain same right but we are going to add addition additional logic to the first pass itself so now count the notes in l linked list as n right n is where we're counting so while we count we can do the kth from the beginning also right kth from the beginning also good so now we are going to store this kate from the beginning in some pointer let's say keith begin is equal to kth from beginning right k from beginning right let's call that and now we need to know what is kth from end right so what we are going to do is since we recorded the kth from beginning in begin that is a temporary variable now we are going to use this kth from beginning also getting updated to advance the pointer so that we will keep the kth from end right kth from end in that itself right so while we count n nodes we will keep the kth from beginning keep updating so that at the end of the linked list right at the end of the linked list kth from beginning will have keith from kate from beginning will point to right will point to ketuman keth from end like that so that is way and then obviously at the end we will have only two steps here swap right that's the third approach we can say so we started with three pass and then split down to two pass and we are down to one pass so now for the code wise i am going to show the code for approaches 2 and 3 because approach 1 is trivial i would say because we have to do the three times passing right so let's go look at the approach two and approach three the code four right so let's see so let's go to the two pass first and then we'll come down to the one pass right so we store the k ah in temporary temp value and the head will be stored in temp head and i have a previous pointer that is also pointing to the template right so while temp is greater than zero basically we are looking to go past the k values right so that is where we have the begin pointing to the right so pre whatever we have collected that we are going to call it as begin right so that means what so we have passed through k value i mean k nodes right we have passed through k nodes and in this particular point the count is getting initialized to k because we have passed through k values or k nodes already and then reassign the previous pointer to head we don't use previous pointer here itself in this next value what we will be doing next so now our temp head is pointing to the kth node right so k nodes we have passed so k plus one i would say k plus one throughout we have passed and now while temp head is still not null we are going to move further so why are we doing this so basically in the second parcel two pass algorithm right while we calculate the kth from the beginning we are also trying to calculate the n so in this case i am calling this n as count here that's it so count is initialized to k because we have passed through k values and then we are going through the end of the linked list to find out what is the real number of nodes in that particular linked list so once we get through that right so we are reassigning the temp head to the head and as remember the count how many nodes we need to essentially pass so if you go back and understand right this is the number of nodes minus k plus 1. so that many number of nodes we need to pass through to get the kth from end right so that is what we are doing essentially count minus k plus 1 right so while count is greater than 0 we are going through that many nodes from the starting so that we can get the kth node from the end so once we have the kth node from end we are going to put that in the end right so begin is having the kth node from the start and end will have the kth node from the end after that all you have to do is just swap so once you swap right on the head that's it so essentially these two while loops are going through them going through the linked list as once if you closely observe right because we are going through the through k nodes here and count minus k nodes here so that means these two while loops combinedly going one pass the first pass and this one is second pass that's it so this is a two pass algorithm so the complexity the time complexity would be order of n still so the first time it will be order of n plus second time is also order of n in the worst case right so the total complexity will be order of two n but since constants will be ignored in the bigger notation it will be order of 2n so now let's go back and understand a single pass algorithm okay so it will be very similar right so in this particular case again temp is uh case uh ascendant to temp and head is assigned to temp head previous is also tempered while temp is greater than zero we are going to go through the k notes first in this particular while we are going to go through the k notes so after going through the k notes right so we have the kth note from the beginning so that we are putting into begin right good so kth node from the back right that we are assigning it to the whatever the pre value we have just call we are calling it as kth node from the back what we said we are going to advance k note from the back so that when the we have exhausted the linked list right the kth node from the back will have the kth node from the back in reality right so we will be advancing the k-th note on the back the k-th note on the back the k-th note on the back and we will be advancing the temp head also so here we went through the k right k notes and in this particular way while loop we are going through n minus k n so entirely if you combine them right two while loops k notes plus n minus k nodes totally we are going through n nodes that two while loops combiningly we are going through the entire linked list only once and this is just a swapping code right i made it like little bit verbose so that you can understand and then finally you can written the head of the linked list so the time complexity will still remain same right in here so order of n so in the previous case is also order of n and the current case also is order of one so in fact in all three approaches one two and three the time complexity the big goal notation time complexity will be order of n still the only difference is this is a process the one pass approach two is two pass approach one is three pass that is the only difference altogether right so that's how we are able to solve this problem with order of n time complexity overall so if you have any further questions please post them in the comment section below this video and also 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 please go ahead and subscribe and share among your friends please click on the bell icon so that you will be notified about my future videos thank you for watching i will be back with another problem soon till then stay safe and goodbye thank you
Swapping Nodes in a Linked List
maximum-profit-of-operating-a-centennial-wheel
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Array,Simulation
Medium
null
1,590
Hello everyone so today we will be discussing question number 15908 code which is make sum divisible by p so in this question what is told to us that c have you remove sach date d sum of remaining element is divisible by p means we have to make a smaller sub Hey, if we have to remove as little as is possible from this ray, then we will get the remaining ray from it, all its elements, all the child elements, we are drinking at this time Do you understand what Arvind has said that we have to return? And what can happen if there are all the elements of the whole, which is the time of all this Okay, then if it is impossible, now this question is then all the concepts will be clear to you and I will skip a little, there are a lot of things in it. thing, because I have discussed everything about this playlist in the previous questions, so I will do it a little quickly because if you have seen the previous questions of this playlist, then you will understand it very easily and its prefix The questions of our pattern will become very easy to understand. Okay, so let's discuss its approach. Okay, so what we did is we are discussing in the questions like in the previous one, we are taking one hey and one prefix sub my. Hey our n1n2n3n4 is just we have zero before n1 + N2 n1 + N2 + n3 zero before n1 + N2 n1 + N2 + n3 zero before n1 + N2 n1 + N2 + n3 doing it like this is our pi and i is for element and this is our pk okay back till here time As I have discussed below, there is an equation in Minus Pi, the whole is playing with this, we will give us a continuous, it is fine like every time and all this has to be played correctly, we have made the deduction. What is asked in this question, what is asked in this question will come out from this equation, your question will be solved, here that thing is very simple, here what has been told to us that what is left is okay, this is the total time, what I want is the total number of mines. I have found this thing behind mine that should be equal to zero, I have found the equation, you have to see the thing which can cause you further problems, I will also discuss it, but your core question is not your concept right here. It is clear that you had to make this equation, you have to total all sums P, meaning its mode should be zero. Okay, whatever I said, let's discuss what we have to pay attention to. What is that? I have written down the question in advance, I will be total sums mines [ Sangeet] If I open the Plus Minus bracket, then it will be the mode of Total Sam, so what is the important point that I should keep the mode of Total Sam in advance, if it is very big then overflow condition can come to you, I will come out of Total Sam only then keep it on mode. If I take it then whatever my final total will be, it will be the total. Understand that when I look for and leave, the date will be set, then a small number will come in every loop, I will keep doing every mode, I will keep doing mods. Okay, so this is an important point. I will do the same with J. I am not even talking about P in J. I never play with P backwards. As I have discussed in the previous question, when I move J forward, when I prefix I move forward with us, this is what I do, I move ahead with you only by taking the mode, as you must have seen, I have completely understood now let's open this equation. Okay, so we open this equation. Now I have one thing in total, I am a director, so I have two things, now I will take these two things completely to the right side and both of them will be stored in the map right in my map and I will take these things forward. I will take it and find it in the map. I have discussed it in the previous question, so what do I do? I have taken it So what will you get Open, everything is fine, now this thing I have to check and this is the number, I will modify it by P, I will get a number N, is it from both, I have to check in the map, it is total, there is just a small problem there, which was the previous question which I asked earlier. Question has been raised, there is a thing to think negative in it, do you know that behind this lace, it is moving forward, which is moving forward like this, it is becoming this mode always when you are in any element. Will you stay, this thing which is behind is becoming a mode behind, isn't the thing which I had discussed important here ok How will be the resulting number, this thing which I had discussed here, is n't it, we are in every loop in the early stage. In every hydration in the loop, we will keep doing grind mode, we will keep doing mode, then the total which we will be resulting in, will also be given PC lace, that too will be given PC lace, okay here is five, okay now I am here Total So the difference between these two which is negative, the difference between these two will also be less than P. This is it, I told you that it has become negative here, so what if it is negative, then it will also be less than P. What I will do is J mines total Okay, it will always be positive, whatever this thing is, I will put you period in it, so it will become a positive anti, okay, that's why I did period. Now let's find the solution for this. Why do we in the for loop? Now let's see its solution. People have not explained this. You will have to understand it yourself but here I have explained to you why this is happening. Why am I doing this? I am doing just this and some more. Don't have to do it now, let's do it directly, okay, then let's start, I am not explaining the complete example in this, now you can do it yourself by taking the example, if you do not understand then let me know in the comment. I will make an updated video of it. Now, what I have initialized here in the map court, you will understand well, what will I do in it, I will check the do in it, what will I do in it, I will check the expression that I told. You have it, I will check it and the value will be my date, it will be my index, why the index, because what I have here, the size of all, I mean, you will see that I have kept it by saying here, so that is mine. Size of will have to be calculated, so I am storing the index in the value, so my prefsum, which is the initial element, has zero behind it, meaning there is nothing in the elements behind it, there are no elements, so again we call it zero. So, its location is mines van and I am keeping the location of the first element as mines van and I put OK, what to do is my total sum is equal to you total sub is out and that zero went to mode with PK. Meaning, the whole of the error is divisible by p, so the minimum size is all, what will be the zero? There is no one, we do not have to remove anything, we have to give this equal, you give zero, return zero is fine, we just have to make small changes and this is the lead code. This is a famous problem. Consider this prefix as a topic. It is asked a lot. Okay, now what do I have to check in the map? I call it 'check' in the name of the variable. call it 'check' in the name of the variable. call it 'check' in the name of the variable. What is it that I have to check here? What is my J here? But that's my prefix that's my perfect and like full and time plus b which I said that I will bed because this piece was added because if this whole becomes negative now look at the total here look at this total here But what do we have to do, we have come out here, now I have to check, okay now here I know that this can be negative and this can be negative which will be a negative number so I have also added plus to my Want to find if this is found, now if this is found, then this is what I have got, this is my current location, if this is found, MP of check, then there must be some index found, otherwise this index will be stored in MP of check, so from there If it is done till today then it should be smallest so the answer is equal you minimum of answer earned I - MP of equal you minimum of answer earned I - MP of equal you minimum of answer earned I - MP of check and here I will update MP of prefix us it was above I and not after every item if it is found Whatever is there, we have to update it. I have to put one more check while returning it to you. Okay, okay, I have it, submit it, let's see how it is done. It has been submitted. You must have understood it. If not, then look again.
Make Sum Divisible by P
make-sum-divisible-by-p
Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty**) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array. Return _the length of the smallest subarray that you need to remove, or_ `-1` _if it's impossible_. A **subarray** is defined as a contiguous block of elements in the array. **Example 1:** **Input:** nums = \[3,1,4,2\], p = 6 **Output:** 1 **Explanation:** The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray \[4\], and the sum of the remaining elements is 6, which is divisible by 6. **Example 2:** **Input:** nums = \[6,3,5,2\], p = 9 **Output:** 2 **Explanation:** We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray \[5,2\], leaving us with \[6,3\] with sum 9. **Example 3:** **Input:** nums = \[1,2,3\], p = 3 **Output:** 0 **Explanation:** Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 109` * `1 <= p <= 109`
null
null
Medium
null
1,679
alright guys welcome back to make challenge 2022 the default so max number of k sub pairs we are giving an integer array numbers 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 operation you can perform on array so for example one we have one two three four k equal to five we have here one plus four is equal to five so we remove one and four from the array and now we have just this array two plus three is also equal to five so we have two numbers one plus four and two plus three so the output is two okay for the example two we have three one three four three and k equal to six three plus three is equal to six so we have one operation and here we have this number one four and three we cannot make any sum any true sum with this numbers equal to six so the output is just one okay to solve this problem let's do it with a binary search to make things more fun let's make our lives equal to zero and writes equal to the length of numbers minus one and we use also a counter now while our left is smaller than the right let's make mid equal to just the numbers of l plus numbers of error and let's check if our midi equal to okay if it is so let's make one's required to counter plus one and let's update the left by one okay let's supply plus one and the rise by minus one okay l if our mid is bigger than k in this case let's update the writer and else let's update the left okay let's make our code so beautiful finally let's return our counter yep let's run the code i hope it work the time complexity is analog to n because we are sourced at the right let's run good again type of mistake and it's some bits yeah it's work so i hope this video was useful for you i'll see you soon hopefully
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
528
hey everybody this is Larry this is 2/5 tear to chew in the coach and let's 2/5 tear to chew in the coach and let's 2/5 tear to chew in the coach and let's get started hit the like button hit the subscribe button let me know what you think random pick with weight giving it a way of a weight W a positive integers where weight W sub I is the rate of index I write a function pick index which random effects an index in proportion to its way okay I guess that's what it's kind of hard to ought to check that's the home is just a random character but so the first thing I would say is given that women Python there is actual Python my library that does this not gonna get into it because you know you're probably watching this video not so that if we're like Larry tell me which library of in Python to use for this very specific form right but yeah let's kind of think about it I think that's a couple of clever ways to do this there's actually something call so core best of all sampling that you can play around with so then actually you could get it done or one space I would have to put to be honest I would have to prove fair from scratch I have vague ideas of it but I'm not gonna do that now definitely you know leave a link below do your Google research Wikipedia learn about that and play around that idea I think it's a very cool idea and you could prove it on your spare time - it's actually not that spare time - it's actually not that spare time - it's actually not that difficult per se in theory but that's it I'm just going to do it probably one of the ways that I would do it and the idea is just well forget wait let's calculate the prefix sum and then roll a number between 0 to the some maybe some minus 1 but and then just kind of you could do a binary search to see which a rate that you get into because if you look at the prefix um it's gonna be monotonically increasing and then we have a number you have to find the root the bucket in which that number is on that number is the first bucket that is there's some the prefix sum is smaller than just random number right okay let's go like that does that kind of make sense because but idea behind this is that okay the idea is that I set you up some weight okay well just boy is useless but let's just say random numbers or not random numbers but like random - Larry random numbers but like random - Larry random numbers but like random - Larry generated numbers something like this right not given that random enough but then now you do the prefix um do you want now you pick a random number I mean I guess technically does it say well prefix some between zero and dirty one and I doubt that will allow you to kind of figure it out where which bucket to fall into so in this case this actually matches up with this because fum and the 31 is kind of implicit you don't need to actually create that prefix some that way but the idea is that okay how many numbers are between two adjacent numbers right well the numbers between two adjacent numbers by default because we're prefix sum is the rate that we're giving and then out so then in that case and then now you take the sum of the entire away which is actually just the last number because it is a prefix um that's the definition of prefix um so then that means that one or the first away will give you one over the sum we just went over 31 the Delta here would be 5 over 31 10 over 31 and so forth right so that's kind of the idea of how you do it and as you can tell because it is a prefix um with positive numbers it's going to be monotonically increasing which means we can binary search so let's do that so let's initialize this weightless so yeah so that's just to our self that prefix that you call W so we name this W in great soft are prefixed our apparent rate plus self dot prefix the last element so did they say what this is doing is just takes last element and then adds it to the current element just a way of writing prefix I'm not a big to you and then pick index so is it just like pick a random one okay and then uh oh that's also good I guess the sum is you go to yeah we good I just want this to be a little bit more explicit though again this is a very obvious thing in that word and prefix um sometimes the entire way just last element right now let's pick a random number from zero to self that song no don't remember how to do random in Python so let me look it up anthem very quickly I think it just random dog ran or something random dog ran didn't all right then take a cup of random function so that when you age okay yeah I think this is good I could be wall and all five one okay I'm just leaving the syntax right now for random here's what I'm reading in cage what we did with me and again this is what I was talking about you can do random that choice of random touch without literally the answer with two of to rate the cumulative rates are again prefix sums but I mean you know that gives the point of no but if you do it this way but I me a little bit I mean you should especially for an interview you should do this but of course on a competitive programming then maybe you just use two random that choice and that's fine but yeah so I'm I think when a brain should be okay so let's just say number is you maybe okay and then now let's binary search so that's just how I write it but feel free to you know why did your own way so to and if so basically what do we one what this is the prefix some let's say we find eight well we want it to be six so basically if we're in the middle and we want to find eight then this actually just means that if this is it just a smaller then what does this mean that means that yeah all the numbers before are smaller so we actually just want this side given that this is smaller so that means that head has to would move to the middle so okay so if self dot prefix MIT is greater than or equal to number then we move head to me else now let's not say given another one that's right here and this is bigger well then we know that cannot be 16 and we wanted to the left so now we want to tell to be men hmm it's me double-checking that men hmm it's me double-checking that men hmm it's me double-checking that this is correct it's a little bit off because this will never converge what we want because the tail is just saying this but then because we never moved to here so if head and tail is equal to one so then we have to add one here so that we double check okay and then now we should be okay with returning head as doing index once that's happens that's let's put in some test cases okay No that's right I mean I still I don't way we have to fix it but oh I guess this could actually let's see if this is and then we'll give you one no okay maybe I mean it's quite it not ok let's debug this real quick because it goes from wall and to that this would never terminate right yeah binary search off by once a tricky so we have to make sure that uh that were okay that's what may give us a time limit exceeded which is what I've viewed but that means that it's just well it's just that if this is the case ten that doesn't seem very random there now this is returning the biggest thing in either case what is that what is what am i printing with number well what am i grand amine with number you presume oh this is - that doesn't seem why hmm I guess this never goes to zero because of the past one but two dozen mackenz inside so we test one of two it's not meant to be inclusive that's what I'm trying to think well that's why we do tell us a bit of meth I still worry because they definitely should not be worried elements in the second input justice I know it should because it's they were okay but the civil number doesn't there should be just minus 1 but it's toshin it's now reducing one no that's not true oh I'm doing something funky so now again you get to see Larry debug binary search which is always one of my weaknesses because I get these rid off by one cases as I'm oh so okay so now he's trying to find a number between 0 to 4 not inclusive it finds there's the too comfortable that's on test lips really need to label my debugging is less confusing okay so for four it was a one so it should be just gives me a see well assume it is to improve isn't prefix of two should be yeah the number is 3 or the prefix this is bigger did I get the signs well probably put it back saying yeah it's okay so if this prefix know that say we wrote a 17 then we want to move to set here right now that's why it should be right anyway let's say we rewrote it three and we see it too we should move ahead to - except for that should move ahead to - except for that should move ahead to - except for that this is not true because if this is a 2 then this should be true which means tail should be too and yet somehow we return now how can we never pick a tail then am I missing something but two is the last element right so if two prefixes today did I really actually just get to sign one yeah I did cuz I but I keep on saying is that is just me being silly then and somehow for these kind of problems you really have to think about what you're asking and I you know I said it a few times out loud and you're watching the video you might be like Larry what are you they were and you said the explanation cuz I remember saying like if it's 18 10 this is bigger than this number which is this number is bigger than this number okay I don't know what that's okay as far as we eventually right okay this looks excuse me this has recorded live so we might have might not head it out that out but uh excuse me but yeah okay so the thing with this form is that it is a little bit random so we don't you can't really tell how this is gonna be true even though we did you know get it you find you but it does look like it has you know distributions in a good way and that and you know in that like you get a mix of both which is not good enough for randomness and this one for example is that true - is there any bias mmm it's hard to say right I mean expected answers just whatever we okay so I'm gonna submit this but the poem is that so the problem with these things is that it is hard to test for random things that gives you randomness and for that reason it because it's very easy to get buyers so definitely use a random library to do the things that you want to do during sampling and shuffling and all that stuff because you're very likely to get it wrong in a library at least you're in the same bar everyone else so because it's very hard to get it exactly why there might be some viruses like you know off by ones or something like that we would mean that's our numbers just never get picked I wonder and I to be honest I'm not super confident this one but it seems like at these four this one or the numbers to get picked or able to get picked I mean it takes a little bit of luck cuz but 0 2 &amp; 3 so you know that goes from zero 2 &amp; 3 so you know that goes from zero 2 &amp; 3 so you know that goes from zero and it could pick a four so it knows that you could do the entire range so that's how it gets me a little bit more confidence I know for example maybe we could do something like this and then you it should be all fours I mean you might still again get unlucky obviously but you know probabilistically way so anyway so yeah that's all I have for this problem for interviewing the first thing I would mention maybe just like hey this was in the real world I would definitely use a library because randomness is hard in on an in or a on a competitive program in contest I would just do it way specifically like I'll just use this library without really thinking about it and be like a next problem but yeah that's what I have with this one hope you enjoy me watching debugging turns out so yeah so just be careful my lesson here is just be careful with the signs but I hope that binary search is hard right for me especially and even at this point actually wasn't a binary search for is just me sing out loud I'm even saying out loud I was saying the right things out loud but my I converted to the wrong code right but I think the thing that I would say is that I actually got order plus one and stuff correctly and the reason how I do it I would like to focus on that because as I mentioned before there's a lot of focus is up for binary search with memorizing these patterns and like look if this is this do this and there's this pattern for it right and it's so cool and then you have to memorize every and for me it's just I don't have enough brain cells anymore I'm getting old I don't I can remember all this stuff so for me is about first point to Boeing a binary search and being like okay let's say head and tail let's say middle of this right and for me I don't do invariant and figure it out we're like okay let's take it let's say we vote a number and it's 10 if its 10th we want decide on this side or this side inclusive or exclusive and everything right and for me I wanted to keep their invariant that the tail is exclusive and from that it leads to this where you know the tail is exclusive right so we move it to mail when it's not possible to be here so we want this side for example and then that means that here will never converge because that's just already let's go so the middle has to be a plus 1 so that in theory both head and tail can move you know freely the entire range and then from that also because in that case head would never be go to tail so then we do this head plus 1 as you go to tear and then at the way n I did head in theory sometimes they could be head plus 1 depending on what you do it but again it all goes by the question of asking yourself okay you know I have this visualization I'm checking the number in the middle or whatever it is in the middle is it on the left sound in the right side and you bind every search and you do it divide and conquer and you do recursively quite equal and that's how you do a binary search anyway it's an okay problem it's a known problem so it's okay Fred I hope you enjoyed I hope you liked it hope you enjoyed watching me struggle and the like button to subscribe boy now see ya later bye
Random Pick with Weight
swapping-nodes-in-a-linked-list
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index. You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`. * For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`). **Example 1:** **Input** \[ "Solution ", "pickIndex "\] \[\[\[1\]\],\[\]\] **Output** \[null,0\] **Explanation** Solution solution = new Solution(\[1\]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. **Example 2:** **Input** \[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\] \[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\] **Output** \[null,1,1,1,1,0\] **Explanation** Solution solution = new Solution(\[1, 3\]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: \[null,1,1,1,1,0\] \[null,1,1,1,1,1\] \[null,1,1,1,0,0\] \[null,1,1,1,0,1\] \[null,1,0,1,0,0\] ...... and so on. **Constraints:** * `1 <= w.length <= 104` * `1 <= w[i] <= 105` * `pickIndex` will be called at most `104` times.
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
Linked List,Two Pointers
Medium
19,24,25
476
back to helgi karina and today we are back with another very interesting problem on lead code which is the number complement now if you see that this problem has been tagged as an easy problem and i do agree with it because it has a very easy and a very simple kind of a solution along with it so why i want to touch this problem is because it kind of this problem kind of covers a very basic and very important uh you know few of the concepts related to bitwise operations which would be very useful when you go on and touch some of the very hard problems uh related to bitwise operations so let's start going through this problem so uh it says that the complement of an integer is an integer which you get when you flip all the zeros to ones and all the ones to zeros and its binary representation so here it gives an example where you know the binary representation of 5 is 101 and the complement that you get after converting once to zeros and zeros to one is basically zero one zero which is basically the binary representation of two so uh you know the decimal number which was input is five and the complement binary representation is you know uh one zero which is like the binary representation of the decimal number two so you have been given a basically a decimal number you have to find its number complement so let's see how we can do it so we are going to discuss two possible solution uh for this problem uh let's view the first one so in the first solution like we are going to do exactly what the problem statements say that is first we are going to convert the number to its uh you know binary representation then we will replace all the ones with zeros and zeros with ones in this binary representation and then we are going to convert back the binary representation to uh decimal representation that is if we take the prior example we will first convert 5 into 1 0 1 and in the next step you know we are going to replace its zeros with once and once zeros that's when we are going to get 0 1 0 and then you know we are going to convert back that 0 1 0 into a decimal representation which is 2 so let's see how let's take some examples and let's see how we can do this so let's take a few of the examples and see how first of all we can convert a decimal number into its binary representation so let's start with 5 so how we do it is basically you know we will continuously keep on dividing it by 2 and you know keep on saving its remainder so we divide 5 by 2 we get 2 remainder is 1 then we again divide two by two uh you know remainder is uh zero and you know again we divide one by two uh you know remainder is one so we see over here the you know binary representation is uh one zero and 1 so 1 0 1 let's try another number let's say 9 ah so 9 again we divide by 2 we get 4 over here remainder is 1 then again we divide 4 by 2 we get 2 over here remainder is 0 then again you know this and yeah so we get like 1 0 1 over here right so you know we just keep the remainders in reverse order and we put it over here one goes here zero goes here again zero goes here and one goes here so yeah this is how we convert the numbers into their you know binary representation now the next ask was that we can we do uh like you see the step two it was basically replacing all the zeros with ones and ones with zeros so let's do it one by one so for five uh we had we got like one zero one so when we convert once to zeros and zeros to one we get zero one zero and similarly for nine uh you know we got one zero one and we convert once to zeros and zeros to one we get like 0 1 0 right so basically this is kind of the what we have got till now is basically a binary representation of complement of these numbers right which were originally given to us so we move to the third step which is basically converting the binary representations back to the decimal representations so how do we do the you know reverse thing that is conversion of binary to decimal we kind of maintain the indexes of the individual binary digits like this is two this is one this is zero and then similarly this is three two one zero so then we kind of multiply by the powers of the two so uh 2 raised to the power 2 multiplied by 0 that is you know 2 raised to the power index of 2 and then multiplied by you know the digit present over here plus you know 2 raised to the power 1 multiplied by the digit present over here and then similarly you know 2 raised to power 0 multiplied by the digit present over here which is 0 so this takes us to you know 0 plus 2 plus 0 which is again equivalent to 2 so what we get from this is like the complement of 5 is 2 basically for what we did was first we tried to find the binary representation of 5 which was 101 then we you know just uh you know converted once to 0's to 1 which is like you know uh 0 1 0 and then what we did was we just converted back 0 1 0 back to its decimal format by multiplying by the index powers of 2 so 2 raised to power 2 into 0 plus 2 raised to the power 1 into 1 plus 2 raised to the power 0 into 0 which takes us to 2 now similarly let's try it for 9 in the similar way we are going to do is 2 raised to the power 3 multiplied by 0 plus 2 raised to the power 2 multiplied by 1 plus 2 raised to power 1 multiplied by 1 plus 2 raised to the power 0 multiplied by 0 which takes us to 0 plus 4 plus 2 plus 0 which is like 6 and like basically 6 will be our answer for 9's complement so it's exactly the same way we can you know we did it for uh you know five we can do it for nine and similarly we can do it for any other number so basically this is one uh possible solution we can opt for we can easily code the solution all we need to you know we just need to follow this simple algorithm to you know solve this problem but before we jump into the you know coding the solution uh i would like to discuss another possible solution another one tricky solution but which is much easier to quote now uh before we jump into this solution uh let's discuss about another very important uh you know concept and bitwise operation which is zor so uh what zor says is that let's say we want to find the zor of two numbers which is let's say five and nine uh how we find the zor is basically uh you know we represent it by their uh you know binary representation like we already saw that the binary representation of five is one zero one and we saw that the binary representation of 9 is basically uh 1 0 1 so how we find the zoro of it is basically uh whenever the two digits that we see you know over and above each other uh which are same we put 0 over there and whenever we see 2 digits which are like different we put 1 over there so if we see like 1 and 1 they are same so we put 0 over here 0 and 0 these are also same we put 0 over here and 0 and 1 these are different so we put 1 over here right so this is how we calculate the zor and then again like we did before we can easily convert it into you know decimal format right so what we are going to do is 2 raise to the power 3 multiplied by 1 plus 2 raised to power 2 multiplied by 1 plus 2 raised to the power 1 multiplied by 0 plus 2 raised to the power 0 multiplied by 0 which takes us to 8 plus 4 plus 0 which is like 8 plus 4 is equal to 12 so basically 0 of 5 and 9 becomes 12 so this is how we uh we find zoro of two numbers now there is one very interesting property about zoro is that whenever we take the zor of any of the digits with one right the it automatically you know that reverses the digit like if we take 0 of 1 with 1 we are going to get 0 but and if we take 0 of 1 with 0 we are going to get 1 over here so if you see it maps 1 to 0 and it maps 0 to 1 so if we have a binary representation of a number right and we take 0 of it with all the ones right so what it should do is basically reverse all those digits like uh we take zoro one with one it gives us one zero with one it gives us uh basically uh one and we take one with one it will give us uh you know zero so basically what it is doing is that if we do a zor of a number with all the ones we are going to get our desired complement of that number basically because one has the property that whenever you take a saw of one with any other digit it will always give you the reverse of that digit so basically we can utilize this property to find the zoro of the number so let's look at this algorithm how we can do this is basically find the number of digits in the given number find the number s is equal to 2 raised to the power x minus 1 now why we talk about 2 raise to power x minus 1 uh let's say you know 5 has had like three digits in three binary digits with it so 2 raised to the power 3 minus 1 uh which takes us to uh you know 2 raised to the power 3 is 8 minus 1 which is 7 so we get 7 over here right and what is 7 what is the binary representation of 7 it is one and again one so basically it is one which is the which is basically the combination of ones we need for uh you know finding the complement in case of a three digit number three digit binary number basically so that's why what we are going to do is that we are going to find a number which is 2 raised to power x minus 1. uh then what we are going to do is basically find s or n where s is the number 2 raised to power x minus 1 and you know and basically n was the original number given to you so basically what we need to do is find 5s or 7 which will gives give us 2 which is the you know intended answer for us now let's take a look at the code for this solution so in the solution over here we are just going to represent the three steps that we just discussed in the form of a code so uh the first step was basically counting the number of binary digits that are there in the number so we already saw like when we were converting uh you know 5 and 9 into the corresponding binary representation we continuously kept on dividing them by two and you know maintaining the remainder so what we need to do over here we will just we don't need the remainders for us what we just need is basically the digit count so uh we'll keep on dividing the number by two and you know incrementing the digit count by uh one and till the point the number doesn't reach zero so uh yeah we'll keep on doing that and at the end of the day uh you know the ditch variable is going to have the number of binary digits that are there in the number so in case of five after you know running till uh this point we are going to have you know this value equivalent to uh three so now the next step was finding 2 raised to the power x minus 1 so uh for that what we are going to do is that basically you know we are going to do a math dot power of 2 comma digit minus 1 uh which is going to give us the you know the required number with which we should take the zor of the given number so in case of uh you know 5 what we what will happen is that digit count is 3 so 2 raised to the power 3 which gives us 8 minus 1 is 7 so you know uh math dot power minus 1 over here is going to give us 7 and then we are going to take our number with this number so 5 0 7 so this will return us you know two as the answer which is uh which we can see over here so basically yeah this is basically an accepted solution on lead code for this problem and thanks for watching this video thank you
Number Complement
number-complement
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **Example 1:** **Input:** num = 5 **Output:** 2 **Explanation:** The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. **Example 2:** **Input:** num = 1 **Output:** 0 **Explanation:** The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. **Constraints:** * `1 <= num < 231` **Note:** This question is the same as 1009: [https://leetcode.com/problems/complement-of-base-10-integer/](https://leetcode.com/problems/complement-of-base-10-integer/)
null
Bit Manipulation
Easy
null
232
hi guys welcome back to the channel eat cod and sleep and today's Le code problem will be Implement Q using stack so let us see what are the companies ask this question here and we can see all the Fang companies have asked this question so this is a very important question we need to solve here and we need to understand it okay so let us quickly dive into the problem here so uh as we can see here the problem statement is so Implement a first in first out fif Q using only two stacks the implemented Q should support all the functions of a normal Q okay so we need to implement a que using two stacks here okay so it should also support all the functionalities of Q here okay so now what so what are all the functionalities we need to implement here we need to implement the push functionality pop functionality Peak functionality and the empty functionality here so these are the functions and we need to implement here so let us quickly check how we can Implement uh Q using two stacks here okay so uh as a question says we need we require two stacks here so I will init I will initially initialize my stacks in the here and in the Constructor so the class attributes have two stacks here right so the class attributes are two stacks here so and the Constructor has the initialization of the attributes here right so I will be initializing the two stacks here in this the Constructor in this Constructor so coming to the push functionality so the two stacks are now let us see let us why we why so what is the first stack and second stack here the first stack will be the main stack here okay that will be the main stack and the second stack will be the auxiliary stack okay that will be using for many purposes okay and this is a S1 is a main stack and S2 is a auxiliary stack okay so let us quickly implement the push function here so before pushing uh so before pushing so let us visualize what is a q here okay A Q is a data structure which stores the which stores a different types of data right so uh so we can add elements from so in a q data structure it has two openings okay first uh from the first and from the last okay so whatever the element we need to push we will be pushing it from the last year and whatever the element we will be uh so if we consider this as starting and this as an ending so whatever the element we need to push it from the last year okay so if at all we need to push six year we need to push it from the uh last here so this is the functionality of Q here okay so this is the functionality of q data structure and whatever the uh element we need to pop it out so we need whenever we need to remove one element from Q we will be removing from the starting here so from starting we will be removing and from last we will be pushing it so this is the functionalities of Stack here okay functionalities of Q here so let us visualize what is stack here what are the functionalities of Stack so whatever the so it will in stack there will be only one opening here okay it will be from the last okay so whatever the element we need to push we'll be pushing it from the last only and whatever the element we need to remove we'll be removing it from last only okay so whatever the element we need to remove and whatever the element we need to push it will be removed from last only right so there is as there is only one opening so we need to implement these Q function using two stacks here okay so we need to implement Q data structure using two data stres that are Stacks here okay so now let us quickly uh see how we can Implement push function here so what is push function in Q here uh push function is pushing the element from the last so uh in the Q also we are we will be pushing the element from the last and in the stack also you'll be pushing it from the last one right so the push functionality will be same for stack and Q here so I'll be pushing my elements into my main stack here okay that will be S1 so I will directly push into my S1 main stack here so now let us quickly understand what is how we can Implement pop function here so now to implement pop function so in q in Q data sector what is pop we can what is pop the remove function right so in at what from where we can remove the element from the starting right but in Q where we can remove from the last right so as so for removing the first element in the Q data structure we'll be uh removing directly uh this ring right so but removing one element in the stack data structure we need to remove 6 5 4 3 2 1 right so we need to remove all the elements from the stack right to remove the first element of the stack right so but in the queue uh we can only we can directly remove it from the first opening right so uh by using Stacks how we can implement the pop function here so here what I will do is I'll be transferring my all the elements to my auxilary stack here okay so uh I'll be transferring my all the elements from uh from my main function to main stack to auxilary stack so my auxilary stack looks like in this way right so now from my auxiliary stat whatever the element I pop it out it will be the first element of the main stack right so now we can pop it out the first element so in this way I'll be implementing my pop function right so now let us quickly observe the code here so what am I doing I'm first of all transferring all the elements from main function to auxilary function right auxilary stack so this is the fun this is the while loop for transferring the transferring all elements from Main to auxilary here and whatever the last element will be the last element in the auxilary stack that will be the first element right so I'll be popping out and I'll be storing it in a variable right now after doing this operation what I need to do I need to again transfer my all elements from my auxilary stack to main stack here so now I'll be transferring all the auxilary elements to the main stack so I'll be again transferring my so this is a while loop for transferring all the elements from auxilary to main stack here so this is and at last I'll will be returning a here which is the starting element right so in this way I'll be applying the pop operation so and Peak operation is also same as Pop operation but here we will be removing it from the data structure but we will be just getting the uh getting the last element right getting the last element here so in the pop also what we are doing we are we were transferring so in Q what will be the peak here that will be the starting element right so for getting St for getting the starting element in stack what we need to do we need to transfer it to auxilary and whatever the last element of auxiliary that will be the starting element of main right so in this way we can get the starting element of Stack right so the same functionality of Po we'll be transferring all the main elements to auxilary and from auxilary we need to find the peak here so in STI in stack what will be the peak that will be the last element right so it will be the last element which will be the first element of Q here right and after finding the peak we need to transfer all the auxilary elements to main stack so I'll be transferring all the auxilary elements to main stack here so this is how I'll be performing the peak operation here and the last thing is empty operation empty functional so what is empty whether we need to check our Q is empty or not in Q data what is empty whether it has elements or it has no elements so in stack also we have same kind of data s like that is main stack right so we'll check whether our main stack is empty or not right so same functional so whether it is empty then it will return true if it is empty whether it is not empty then it will return false right same and coming to the time complexities of these functionalities so it will so for stack it will be obviously uh big of one constant space right constant time complexity right big of one only for pushing the element into stack so well so for pushing the element into the tack it will be like from last we will be pushing it right so it will be big of only right and for popping it out we need to transfer all the elements from M to auxilary right so this while loop uh this while loop takes big of and operation right so the pop functionality time complexity will be big of n here okay and for Peak also it will be big of n only right as we are transferring all the elements to from Main to auxilary right so this is also will be big of n operation only and at last for checking m stack uh that will be uh constant time complexity only right so for checking whether our Q is empty or not uh we need only big off one operation right so and the space complexity of this problem is and as we are using two stacks here so it will be 2 into big of N and so we can take it to Big offen only right so the space complexity will be big offen and overall space time complexity will be big often here okay so this is how we'll be solving this problem here uh like implementing Q data structure using two stacks here and thank you for watching this video And subscribe to the channel and thank you
Implement Queue using Stacks
implement-queue-using-stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: * `void push(int x)` Pushes element x to the back of the queue. * `int pop()` Removes the element from the front of the queue and returns it. * `int peek()` Returns the element at the front of the queue. * `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. **Example 1:** **Input** \[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 1, 1, false\] **Explanation** MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: \[1\] myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is \[2\] myQueue.empty(); // return false **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. * All the calls to `pop` and `peek` are valid. **Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
null
Stack,Design,Queue
Easy
225
1,624
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is largest substring between two equal characters so in this question we given a string s we have to return the length of the longest substring between two equal characters excluding the two characters if there is no such substring we have to return minus one as output and by definition a substring is a continuous sequence of characters within a string now let's take these three examples and see how we can solve this question so in this example there are two characters a and a this is at zero and this is at one and there is no substring between them so Zer is the output here in this case you can see a is appearing here and a is appearing at the last index so first index is at zero second index is at three and there are two characters in between so you return two as the output so how are you getting two is Right index three minus left index 0 - 1 is equal to 2 so answer is 2 index 0 - 1 is equal to 2 so answer is 2 index 0 - 1 is equal to 2 so answer is 2 and in this case there is no common characters so we return minus one as the output according to the conditions now let's take this example and see how we are getting the output so if You observe these three examples you finding for the leftmost index and the rightmost index of a common character so we need to keep track of the left and right index and then find the characters between them so to keep track of the characters between them I'm using a hashmap to fill the hash map I'm iterating through the input string from left to right and let me create the hashmap so I is initially pointing at the zero index we check if that character is present inside the map or not no it's not present so add it as the character and add its index is zero Now we move I further so inside the values we're going to keep adding the leftmost index of the character and as you find a match so I will be the rightmost index and you have the leftmost index in the map and then you'll find the difference between them I also create a variable Max and set it to minus one which will be our output because there might be multiple occurrences of leftmost and rightmost indexes we have to find the longest distance because we need to return the maximum length of the substring between the two matching characters we check if B is present inside the map no so add B and add its index is one now we move I further I is equal to 2 we check if it is present inside the map yes so get its leftmost index and calculate the length is equal to like I said right minus left minus 1 so right is 2 I is 2 left is 0 minus 1 so you get one as the output and update it with Max is minus one and update the current max out of them one is Max so this is the max subring now move I further now I is here I is equal to 3 check if the character is present inside the map yes it is present and this is the leftmost index so calculate the distance between them right is equal to I 3 and left is equal to the value present inside the map which is 0o and minus one so you get two and update it with Max is current Max comma length so you compare it with two current Max is two now move I further I is pointing at 4 check if it is present inside the map yes it is present so calculate the distance right is equal to 4 and left is the value in the map so 1 - 1 = 2 and the value in the map so 1 - 1 = 2 and the value in the map so 1 - 1 = 2 and update the max 2A 2 max is 2 now move I further I is equal to 5 check if the value at I which is B is present inside the map yes it's present get its value and calculate the distance so right is five and left is 1 and 1 so 5 - 2 is 3 five and left is 1 and 1 so 5 - 2 is 3 five and left is 1 and 1 so 5 - 2 is 3 and update the current Max 3 and two will be compared and Max is three now I is at six check if the character at I is present inside the map yes it is present so get its left index and calculate the distance right is 6 - 0 - 1 is equal to distance right is 6 - 0 - 1 is equal to distance right is 6 - 0 - 1 is equal to 5 so length is equal to 5 and update it with current Max is 3A 5 which is 5 and move I further and I is 7 which is greater than the length of the strings so we end the iteration as it goes out of bounds and whatever is present inside the max variable which is five will be returned as output so these are the five characters and this is the left index and this is the right and the substring length is five so that is the output now let's Implement these steps in a Java program so this is the input given to us let's take the second example so s is equal to a b c a and we have to return a integer as the output so first I start with creating the map and then I create a variable Max which is equal to minus1 and then we iterate through the string from starting index till the end so we start from so right pointer is pointing here we extract that character CH is equal to a we check if it is present inside the map no it's not present so this will be skipped and this will be executed we're putting that character at right is a so add it as key and add its index which is right to zero as its value now move right to the next index we extract the character at right CH is equal to B we check if it is present inside the map no so this will be executed add that character B and set its index as the value now move with the right pointer extract the character at right is C so CS C check if it is present inside the map no it's not present so El block will be executed again add the character at right is C and set its value as right is pointing at two which is the leftmost index of C until now which is the first occurrence that is the leftmost index of C now move right further character at right is a so CH is a check if it is present inside the map yes a is present inside the map get its left pointer from the value so map. get of character at right character right at CH so get its left most so this is left now we calculate the distance that is right - left - 1 right distance that is right - left - 1 right distance that is right - left - 1 right is equal to 3 left is equal to 0 and - 1 is equal to 3 left is equal to 0 and - 1 is equal to 3 left is equal to 0 and - 1 so 3 - 1 is 2 and current max value is so 3 - 1 is 2 and current max value is so 3 - 1 is 2 and current max value is so max of -1a 2 so max will be updated so max of -1a 2 so max will be updated so max of -1a 2 so max will be updated to two and in the next iteration right is out of bounds so we end the iteration because right is equal to four so right is four and length is four this condition will fail and we come out of the for Loop and whatever is present inside Max contains two as the answer so two will be returned as the answer which is expected here so the time complexity of this approach is O of n where n is the length of the input string has given to us and the space complexity is also of n because we're using a hashmap to solve this question that's it guys thank you for watching and I'll see you in the next video
Largest Substring Between Two Equal Characters
clone-binary-tree-with-random-pointer
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
133,138,1634
1,763
hey guys so welcome back to another video in this video we are going to see a problem called longest nice substring given that a string s is nice if for every letter of the alphabet that contains that s contains it appears both in upper and lower case so for example a b is nice because capital a and small a appear and capital b and small b appear so however a b and capital a is not because the letter b appears and there's no the capital letter in the string yes so for example in this given string a b they need not the alphabets a and b are unique and uh as per the given condition we need to have both of their uppercase letters in the given string and they need not be in the consecutive order for example a and capital a need not be in the consecutive order so which makes this problem kind of a little bit more complicated so in this problem we are going to use recursion to solve it let's see how we can do it so this is the given string and our logic is going to be something like so first let's mark the indices 0 one two three four five and six so our logic is going to be something like so whenever we see an invalid alphabet we are going to divide the string into two and we are going to check if the to the left of the string and the right of the strings if we can find any valid formations and we are going to return the maximum of them so for example in this string we can see that so we create a set for each and every letter in the given string so that set is going to be looking like this and we have all the characters we put all the characters into the set and we check if they're valid a character is valid if we have both its upper and lower case letters for example in y we have both of its upper and lower case letters in the set so the string so the character y is valid so we kind of going to run a for loop on the string first so y as you can see y is valid and then we move to a and a we have both the upper and lower case a's uh so it's kind of also valid and then now we move to is it but the thing with is it is that we only have its lowercase letter and we do not have its uppercase letter in the set so it's not valid so we are going to divide this string into two parts and it's gonna look something like this so for example the string has a y a is it a cavalry a and y and we're going to divide this string at is it and we're going to divide it into two the string the substring to the left off is it and the substring to the right of is it and we are going to do this recursively again and again so the substring to the left of z is going to be capital y and substring s1 is going to be capital y and small a and the set we're going to create another set for this again so the set is going to contain y and a so again the sub the substring to the right opposite is going to have small s2 is going to be having solid a capital a and y small one and the set for this is going to be small a capital a and small y so and then we are going to run for loop on both of these we're going to do that process recursively and our base case is going to be if the string goes less than two strings then we are going to return an empty string so it doesn't make sense so if it goes less than two strings they cannot be a it cannot be a nice string so we're gonna run a for loop on this string y a and y we have we do not have both uppercase and lowercase letter wise in the set so we're gonna divide the string into two and the string towards the left of y it's gonna contain just an empty string and swing towards the uh right of why it's gonna contain only a so again it's less than uh the length of the string is less than two so it's we're just gonna return uh an empty string these blue strings are just gonna be returning t in empty strings and uh here we check for we again run the for loop in the string and for example in a we have both lower and uppercase letters ea and again capital a we have both upper and lowercase letters and again for the small a we have both upper and lower case letters so these are valid characters so we then move to y and for y we do not have the upper and lower case letter y so we are going to divide the string into two sub strings again the string to the left of substring to the left of y which is this and substituting to the right of y which is an empty string gain so it's going to be string s one is going to be equals to equal to uh a capital a and the set for this is going to be equal to small a and capital a and string to the right of s2 is going to be containing just an empty string so we don't need to do anything for that and yeah this string aaa we're going to recursively run the loop and all these cases this and this are just going to return empty strings to the recursion above it and this special string which is actually a valid string it's going to run the for loop on this again and a we have both capital a and small a for that and again for this a we have capital and small a and again for the same we have both the capital and small letters so it's a valid string so once we find this valid string we're going to return the string if the forward loop completes we're just going to return the string or if we have another valid if we had another valid string here for example small b and capital b here we're just going to compare both of them and return the length of the maximum string so in this case we're going to return a and a to its recursion above it and this is again going to return aaa to the recursion above it and so we finally get the answer which is molly capital a and small a just answer so this is the idea behind it so let's see how we can code this up so first i'm going to be creating the recursive call function it's going to be called dfs and it's going to be taking one parameter and it's called string and we but we're going to be creating our hash set it's going to be the set of our current string and we're going to be creating our base case if the length of our string is less than two then it makes no sense to further proceed so we're just going to be returning an empty string and now we are going to be looking to our string for ein range oops of length of our string if not of string of i dot if this is going to be checking if our current alphabet is valid in hash set and string of i dot upper in hash set then or we are going to be dividing the string into two parts string one is going to be the dfs call recursive call of current string to the left of our invalid character and string 2 is going to be the recursive call of the current string but to the right of our in our character and we are going to be returning the string with the maximum length uh we're going to be returning string to if lenovo two is greater than one off string one else you can defeat any string one and if our string is entirely valid you're just going to be returning the string and this return the dfs call of s so this must work so i'm going to be submitting it now so this works so thank you for watching this video make sure to subscribe and check the links in the description thank you for watching
Longest Nice Substring
all-valid-triplets-that-can-represent-a-country
A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not. Given a string `s`, return _the longest **substring** of `s` that is **nice**. If there are multiple, return the substring of the **earliest** occurrence. If there are none, return an empty string_. **Example 1:** **Input:** s = "YazaAay " **Output:** "aAa " **Explanation: ** "aAa " is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear. "aAa " is the longest nice substring. **Example 2:** **Input:** s = "Bb " **Output:** "Bb " **Explanation:** "Bb " is a nice string because both 'B' and 'b' appear. The whole string is a substring. **Example 3:** **Input:** s = "c " **Output:** " " **Explanation:** There are no nice substrings. **Constraints:** * `1 <= s.length <= 100` * `s` consists of uppercase and lowercase English letters.
null
Database
Easy
null
1,802
hello guys welcome back today we are going to understand to delete your question okay so let's see the today question so today we have given 1802 uh maximum value at a given index we have given in a bounded array right so let's continue to understand this question right so this is a lead code 1802 question so it is saying that you have given three positive integers that is n uh index and maximum okay and you want to construct an array that is called nums right and it is a zero index array means one day array that satisfies the following conditions right the first it is saying that nums dot length is equal to n another it is saying that nums at I is a positive inches where I is greater than or equal to 0 to n and absolute value of num at I minus naught I plus 1 is less than equal to 1. now it is saying that I should be greater than equal to 0 answer to less than equal to n minus 1. next sum of all the elements of nums does not exceed maximum and finally it is saying that Mouse at index is maximized okay these things we have given so what we have to do we have to return the nums at index of the Constructor array right and note that we have to Absolute x equals to equal x if x is greater than what 0 and -1 minus X okay -1 minus X okay -1 minus X okay so let's suppose we have given a n equal to 4 right and another we have given index equal to 2 and Maxum we have given is 6 Okay so now we have to reconstruct an array right and so how will construct the array right depends on this value right so if let's suppose we have ah n equal to 4 right means 4 is a length light what is a length as you can see here n dot announced dot length is equal to N means length of array we have given in where in here right n equal to 4 means when we are going to construct an array so there should be index 0 comma index 1 comma index 2 comma index 3 right so these elements we have to fill in the nums and this is nothing but our nums right now what we have to do now we have to construct in such a way that the maximum should be 6 right so nums at I is a positive integers right and we have to take absolute value num minus none plus one should be less than equal to 1 right now it is also saying that the sum of all the elements of the num does not exceed maximum right so from the maximum it should not be maximum value so to do that if we construct a value let's suppose I'll start with 1 okay then we can take 2 and then we get 1. so if it an index 2 has a two value right we have given this is given right index 2 right index equal to 2 we have given right so if you consider that nums at 2 now is what look if you go if you do the sum it will become what there is no array that satisfy the condition right that satisfies the condition and so we have to construct the error like this one two one right because this is the only one array that satisfies our all the conditions right so if n equal to 4 if we'll take index 2 is there right if you do the maximum of this one so it will come 6 right so this all conditions can be satisfied right so here if we'll take nums at what to so this will become what three why because we have to take the sum right we have to take the sum okay and 2 is the maximums at 2 is the maximum nums at here right you can say maximum value we can say okay and that's why this is uh the value we have given right so 0 1 2 is equal to it is a 3 value it is coming right but if we talk about 2 what is this 2 is the maximums at 2 right this is the Max num at 2. right that we can see that's why we have to return these two okay so this is the output okay so in this way you can try this example too right and you can make it okay so actually it is saying that num at 3 and num n equal to three six Behavior index equal to one game a maximum is 10 right so you have to construct in that way only let's suppose we have given n equal to 6 index we have given is 1 and maximum we have given is or 10 okay so if we will write uh sorry array so arrays would be have length what six zero one to 2 3 4 and the last element is fifth add index fifth zero to fifth now you have to fill this nums array nums right so you have to fill in such a way let's suppose I'll start with one just for understanding one then we'll take uh one again okay and two so one two is four we'll take two right one two and four or we can say four and three that suppose I am taking three okay one two and three is seven and will take what if I'll take four it will become what seven for eleven okay so I'll take uh um three and take three and zero let's suppose just for understanding you can take any other value okay and then at index here 1 we have to take what value right so it is coming 3 okay so you have to take initially three value and then you have to construct like this okay so you at that time you will get three just for understanding leave it so take time and uh so do the solution of example two okay so this question has been asked in uh Oracle and Microsoft okay let's understand the solution what solution is saying and how we will going to implement this right so As We Know ah this conditions we have given ok so let us start with the example that we have given in the problem statement that we are going to refer through this figure okay so there are several ways to make nums at two okay the maximum as we are going to see first two example we are going to see is let's suppose once we want uh larger nums at 2 that we are talking about here and it will become what is 3 right and the sum of the array will certainly be the greater than the maximum right because 1 2 and 2 is what 5 right and this one becomes 6 okay so two to four one will take what one and one so this total sum become six right so when we take this value 1 2 and 1 right so in this case what will happen maximum 1 2 and 2 4 and this is one and this will be one five so this is also true right and here what we are getting 4 okay value now let's suppose we are taking here 3 at this Index right one two three we will take here right and we come to so that time 3 and 3 is 6 now we have two so this will become what eight right and it is more than max value right more than max value is eight right and that is not good right because here what we are getting uh three six we will get here right but the total sum will convert total sum will come 8 and that is more than the max value right so this way we have to understand and then we will implement the uh function right let's suppose uh we are going to use greedy or binary uh search right so the first our ins intuition should be like our objective is to maximize the nums at the given Index right so nums to maximize the nums at index the nums at the given index while uh ensuring that the sum the array does not exceed maximum so we can try using greedy algorithm right and in order to maximum the maximize the numbers at index we need to ensure all the other values as small as possible Right so however we cannot take the other values to be uh you can say smaller right and we will refer the two given rules in this problem that the difference between the adjacent number cannot be greater than one right and nums at I must be positive okay means that we are talking out here this will not work because if we'll make the difference between these numbers so this will not work right so you have to take like this only like if you will talk about one two difference is one two right difference is 0 2 1 right difference is one means it should not be greater than what one so it is saying that if I'll take a ah let's suppose nums at I is let's suppose 2 so it is saying that nums at uh I plus 1 should be either 3 or one okay either three or we should take one okay it should not be other than value because if the difference is coming it will take this minus this or this minus this it should not be greater than one okay next rule is saying that if nums at value num let's say nums at I should be must be greater than 0 right positive value so these two conditions we have to follow so the last two example that we have seen right here these two right this were working and as you see the difference between the adjacent numbers are coming what right but uh in the example of the right side this one okay what happening here if we are taking difference between nums at 3 and nums at 4 that is greater than 1 right but in this example if the first number is coming equals right the first number is coming equals and which is not allowed okay here those two example is coming equals right so that is not correct so in this way this is also not allowed this example is also not allowed but we are referring this one and this is also not allowed right so only this type of example will work cut it because both adjacent value is coming what 1 difference would be what it should not be cannot be greater than one right it cannot be greater than one this should be take care of and the difference the next two values should not be equal right if it is equal means what ah this is also not right this is also not allowed got it now let's suppose we are here okay so hence we need to ensure that nums at I satisfy these conditions as well means this will not work and this will not work okay this will not work this will work right based on these two condition right if the difference is not greater than this one right and another nums at I should not be greater than zero I should not be 0 right it should be must be positive number right so it must be positive not zero yeah must be positive as you write right like this so therefore the straightforward approach is uh after setting the value of the nums at index here are the numbers to its left decrease one by one from the right to the left until they reach one similarly the numbers to the Its Right decreases one by one from the left to right until they reach one rich one right see the so this way means it is saying this these are number given right these numbers are given okay so the very straightforward approach after you set these values right let the numbers to its left decrease one by one so from here we are going to decrease one by one okay it is saying like this similarly the numbers to its right decrease one by one from the left to right okay from right decrease one by one from the left to right until we are going until there is one okay so these two approach we can follow either this way or this way right until we reach so left side it will number should be decreased right this way we can ensure that the total sum of the array is minimized without validating the rule because if will decrease we will decrease by 1 right if we'll increase will increase by one right so we need to calculate the sum of the array which is purely mathematical problem right so let's uh take the number of left of nums at index nums of index okay as an example right there will be an arithmetic sequence to its left right and possibly our consecutive numbers of ones s is numps at the given index is less than the number of element to the left right so we need to determine the length of the arithmetic sequence based on the relative size of the index and value right so the next value that its relative consecutive value will come from what index plus 1 right and if we'll do the minus it should be 1. right absolute value of 1 you can say this will always compose positive so once we have determined the length of the arithmetic sequence we can calculate the sum of the sequence using the automatic formula right and this sum will come Y how like a of 1 plus a of n Dot N by 2. okay so this arithmetic sequence formula we will use we are af1 and a of n is the first and the last term of the sequence where n is the sequence class sequence right so let's suppose we are going to take here okay so what I told the formula so I am taking the sum as uh a of 1 Plus a of n and we will multiply with what n by 2. here a A1 and a n are the first and the last term of the sequence and N is the length of the sequence right let's suppose we are started from here to here okay so it is saying that if the value here is less than equal to index right it means in addition to the arithmetic sequence from value to 1 there will be a continuous sequence of One S with the index minus Value Plus 1. right the sum we are talking about like ah there will be index side minus value and plus 1. if this will come right it means what means where value is less than equal to index and that's why here it is come value and there it is coming Index this way you are talking about because we are just adding one value here right so one value is here like this we are setting for all these values right so the sum of all the elements right on the index of the left including uh nums index is made by two parts the first part is you can say 0 1 2 3 right and then it will convert it will sorry it will go continuously like this and then it will start with what this part value minus 1 value minus 2 value and then value right like this and which is Value Plus 1 into value like if you implement this one though this part so this part will be convert Value Plus 1 into value by 2. right like this it will be gone so the sum of the sequence will become what if we'll do the sum if you going to find the sum it will be convert index minus value Plus 1. and which is it is consists of all the one value right now this index minus Value Plus 1 is the sum of your values right otherwise it means there is only one automatic sequence on the left side of the index with the first item Wing value and the last item value minus Index right so first item will become what value and another will become what value minus index so this is your first value and the zero second value so this time the sum of arithmetic value will become what this is your value minus this year you can say value minus index and then we can take what value and then we'll take value minus 1 like this right so this all depends on your things right either will take value minus index that we can see down then value minus 1 and third we can take what value three things we can take in first we'll take minus then we'll take What minus 1 and then we'll take value and then if we'll do the sum right and this will become what Value Plus value minus index this value and then we will multiply index plus 1 by 2. right based on this formula means I can if I go into right here so first is what we have value then what we have will do plus value minus index right and now n is and we know that what we have n is index plus 1 by 2. that we are talking about here hey so these are the approach that we will follow okay in this ah part similarly let's suppose we have ah in the right side we have nums at index is actually exactly the same we need to determine the length of the elementary sequence and the length of the continuous array with the one right as you can see here one based on the relative size n minus index and value right so this is your n minus 1 and this your value right similarly if the value is less than or equal to n minus Index right n minus index that we are talking about right it means that um the sub array of the length will become what n minus index minus value this will become sub errorism right because it consists of all the value of one is addition to the arithmetic sequence value to 1. we have taken value and we'll take till what one so from here to here if you are taking means this all is consist of 1 s okay the sum of all the element of the index right including nums at index is made of the two part the first arithmetic sequence that we can say is starting with the value then value minus 1 and it will come similarly to like this okay so here if we'll do the calculation right this calculation is nothing but what it is saying that ah if you do the sum right it will do the sum right this will become what this will become Value Plus 1 we can take Value Plus One into value by 2. right because this is the thing we have if we'll do the sum of the length this will be convert we have taken Index this one then we will take what minus value Plus 1. this is your some of the sequence okay and this was a sum of arithmetic as some of the arithmetic sequence okay and this order connected with 1s and this is actually less than what n minus index minus value it is less than okay just that the sum value is coming so in the otherwise there is only one arithmetic sequence on the right side of the index right with the first item being value and the last item being value minus n minus value minus n plus 1 plus Index right as you can see here value minus n plus 1 plus Index right and so this is going to be index n minus 1 right so if we'll do the sum right the sum should be what Value Plus value minus n plus one Plus index this will become the sum and you have to Define divided by 2. right because if we are going to divide means we have to multiply what we can take n minus index right n minus index C that part we have to multiply here now you have seen everything this detail thinks rise so we don't need to forget that we have added the actual value at the given index twice so we need to subtract the final value by Sum right now we have seen that we how to calculate the array sum at a given a specific value right so the question is how do we maximize our value so we can use binary search to find the maximum value that meets the criteria first we Define a search range from left to right and that we are going to ensure that the maximum value that falls within this range next we will perform binary search within the range like for each boundary value mid that divides a current search space in the half and we try whether the nums at the given index is mid right if it is Miss that is feasible value that ensure the sum of the array does not exceed maximum right so if it is valid we continue the search for the larger mid in the right side right half of the interval so if it is not feasible it means that mid is too large so we need to search for a small value in the left half of the interval and if this way we can means we can say in this way we can have the search interval at each step and we will find the maximum mid that emit the criteria in the logarithmic time it means there are many uh problems right there are many problems you can say ah that you can perform the binary search and you can find the Optimal Solutions right you can check out the split array uh Lots on maximum distance to gas station Coco eating banana capacity to ship package within the days and divide chocolate type many problems and you can go through that okay now we are going to see the algorithm right and we will try to implement this one so first we need to define the a function that will take you can say index and value and we will calculate the maximum sum of the given value that is called num right we will initialize Left Right space and we'll set a left is equal to one is the max minimum a possible set right equal to Max for its maximum possible value now we'll check left is left should be less than right till that we will get the middle index of the search space and we'll find our mid so left plus right plus 1 by 2 that is you can already have the knowledge of magnetic search we'll check if the get sum is less than the maximum right if so it means num at index is mid is a valid num and we can go for the right half by setting left equal to Mid it means the mid is too large and we have the nums right so we shall go for the left half and we'll search the space and we'll set the right equal to Mid minus ones and we will return once the binary search ends so what we have to do actually here right uh that we will talk about later we will take left right and we'll in the while loop we'll take while is less than right you know the binary search right so we'll make a while loop and we will find our mid and we'll check the get sum is less than the maximum will ah assign left equal to Mid and otherwise write equal to Mid and will return left right so this is the binary search things that you can go through and you'll check coming back to the get sum we have index we have been value we have been and we have given right we will take account right and we'll check value is greater than index we'll find our count how we'll find the count Value Plus value minus index into index plus 1 by 2. count will find how Value Plus 1 into value by 2 or plus ah index minus Value Plus 1 right similarly this is the ah from left to ah right to left right now we'll go with the value is greater than n minus Index right so we'll take Value Plus value minus n plus 1 plus index and we'll take n minus index that we have seen previously right and similarly for this one will take Value Plus 1 into value by 2 and we'll do plus n minus index minus value and will return value minus this one because we have already added value is time right so we'll return our value so finally it will return the max value right maximum sum it will return so that's all for today and if you like this video please hit subscribe this channel so you will get more understanding more videos like this little let's little lengthy videos so don't worry for this take some time pause this video and watch multiple times okay coming back to the time complexity we have given a log of Max sum and uh because uh we know that searching a space will take o log Max sum and this step is coming from what binary search right and we know that each calculation will take off one time so that's why we will take log of the sum but the space will take off one because uh binary search get function will take o of n space we are not taking any stress basis and that's for all today so thank you for watching this video guys if you hit if you like this video please hit subscribe this channel so we will go get motivated like this thank you
Maximum Value at a Given Index in a Bounded Array
number-of-students-unable-to-eat-lunch
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of all the elements of `nums` does not exceed `maxSum`. * `nums[index]` is **maximized**. Return `nums[index]` _of the constructed array_. Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise. **Example 1:** **Input:** n = 4, index = 2, maxSum = 6 **Output:** 2 **Explanation:** nums = \[1,2,**2**,1\] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums\[2\] == 3, so 2 is the maximum nums\[2\]. **Example 2:** **Input:** n = 6, index = 1, maxSum = 10 **Output:** 3 **Constraints:** * `1 <= n <= maxSum <= 109` * `0 <= index < n`
Simulate the given in the statement Calculate those who will eat instead of those who will not.
Array,Stack,Queue,Simulation
Easy
2195
1,286
Hello guys welcome back devotion in this video will see the editor for combination problem system August challenge and incredible third node to solve this problem solve latest video problem statement in this problem Thursday subscribe this Video not here in this Video give the giver function Function The Combination Length Function Is The Next 9 Combinations From News Room Latest Example In Order To Get Better Understanding Well In This Case First Wear Given Constructor Which Will All Set For Treating Acidity This Combination Length Know The Function Is The Next 100 Years In The Next Generation In Lexicographical Length Combination Subscribe In The Northern Porn Picture Verification Combination The Question Is Giving Combination But I Will Be Solving Using Hubras For Example Subscribe Channel Subscribe How To Find The Springs Having Combination Length Of Only Give In This Capacity 200 Grams ABC They Can Have Combination ABCD Will Be The Three Combination Subha Possible From Distic President Graphically Subscribe To Dr. Reddy Labs' President Graphically Subscribe To Dr. Reddy Labs' President Graphically Subscribe To Dr. Reddy Labs' Combination Lexicography Indian They Are Not Against Any Thing Will Start From This Point Widening This Point To Tweet Queer Recovering Wishes For Everyone Day you will see the point at a point into a string and have detected at this point into a string then will be going through in this non veg dish function Kaulav 1.21 BSE The non veg dish function Kaulav 1.21 BSE The non veg dish function Kaulav 1.21 BSE The Video then subscribe to The Amazing Pointed to be written and they will update this Point to the point for this point to the return of the problem examples tu latest new look at how to solve this problem we love e request to generate combination soir giver string abc length equal in the total combination you must for every character will have two options Seervi subscribe possible combinations of strength from this abc watering allegation length of the combination length combination randhir wa ko subscribe zur acids pe ki aditya ne cd vanity van abc of this will be possible combinations from this will speak all the combination switch Of length to presence to read somewhere in order to process and next nonviolent no matter how to solve watching this green line will win the character of birth subscribe The Amazing Green Color subscribe our Channel and subscribe the se this 220 will go to also know what we Can improve 10 20 or exclude this be let us swim proof Buddy 8V Can include desi and one foreign improved desi ghee in the distinctive which will be amazed to see some decisions of the three and receive notifications combination of all will not be the best option will be explored Simply Subscribe Indian Length Will Be Back To The Best Option A Day Will Not See The Hidden The Channel And subscribe The One That String Quest Only For Recording Studio But Acted SBNS2 DC Sources Of Your Interests Of Land In no way back from this is back from this question for this is not including a e don't know the character we can do subscribe will be there will be no the best option for not doing so will only be not been looted combination liquid to back to 9 Will Not Be Seen From This End Subscribe Toe Hue Land Is From All Possible Combinations Soft Dough Possible Combination Switch Is He Is Totke Strings Idea Of Interest Does So The Interested Springs Raw Length Combination Land Which Was Requested To Know The Thing Which They Should Remember is the lexicographical Dr. Hind is the trick so you can servi provide all the string in see watering director subscribe like this is this what is this production will be in order to retain simple subscribe combination veer question how to victimized solution in this case Which can see that they are just interested in the combination length of the string ok so in this is pair including this and including this also din they can stop here and lotus in her but no what is placid in this a win again they want to See The Scene In Order To Get This Is Not As Well Shree They Are Not Tree To Its Length Is Required In The Top And They Can Not Give This Will Be The Mystery Solved This Very Good Which Will Give You That Sonth Ul Fitr Time Complexity While even after you upload voltage change the voice kids time complexity can go to and raw to the point and because the length of the string and the combination can land both also in this world will be equated with and a butterfly positive vibration they can Improve the time will be running in a better time compare to they don't reply 2 optimization ok no latest look at the next technique which by using waste masking before going to bed masking approach latest weekly revised it's who 737's latest from where given string it b C &amp; F 420 Will only be used for b C &amp; F 420 Will only be used for b C &amp; F 420 Will only be used for string values ​​for example Will be string values ​​for example Will be string values ​​for example Will be having only those who believe values ​​from having only those who believe values ​​from having only those who believe values ​​from plant B C D Will have all is well because of the corresponding values ​​of this values ​​of this values ​​of this A B C D Will not have anything because all is Well wishes will give you know how to improve the way they can take off but are to be valued for the latest Thursday morning no one will just subscribe to the Page if you liked The Video then subscribe to the Apne CD Sanseri Understand How They Can Use This Witmarsh on this given string in order to get new subsequent spring so how many true combinations are possible if you have endless stream death will have total number of bitcoin combination apps and display 100 this is very simple to understand what we can give example for subscription For total number of nations will be two to two 9 from this length combination length equal to how many subscribe combination string from total length of total strings Bluetooth 382 huge crystal clear ludhianvi three subsequent springs which will be having length equal to fennel Distic ABCD Water This Mask Range Value Pure Mask Will Be Ranges From All 0.2 All One Mask Will Be Ranges From All 0.2 All One Mask Will Be Ranges From All 0.2 All One Side Open 10th december Combination Request You Too So Will Take All Two Spring Combination Morning Is That 210 Do Or 21 2013 Near And Dear Ones Who Were Taking All The COMBINATION 2ND YEAR IN JUST MORE THAN 120 SUBSCRIBE LIKE SUBSCRIBE AND WAVE COMBINATION WILL FIND THE ENGLISH HOW 2010 WILL CHECK THE LENGTH OF THE STRING WITH AND COMBINATION LANDSORE LUTYENS ZONE PRESIDENT WILL NOT MATCH NOMINAL FEE FOR LIPS DISTRICT WILL GIVE YOU WILL NOT MAKE INTO SOME Will Not Distract Subscribe Know What Is The Story In Hindi Stories With Values ​​Path But As You Can See Stories With Values ​​Path But As You Can See Stories With Values ​​Path But As You Can See The Question Is That We Need Not Guarantee Key Elements In Water In Delhi Yet Kept In Short Doctor Saw In The Previous Cases Will Be Easy CM BC When all the elements in set and you 100 inspiration in map and set is people is maintaining all elements in half basically a balance total number of the nation and everyone can we take time to time complexity and see the question is that we can withdraw all This Creation Combination Veer Vikram Channel And Not Storing These Values ​​Will Not Channel And Not Storing These Values ​​Will Not Channel And Not Storing These Values ​​Will Not Complete Process Will Not Present In All Possible Springs Advisor Deposit From Your Length Of The String And G To 250 No You Know That You Next Function Will Only Be Beautiful Sea Train Times So Ifin Generate All Possible Strings Within Time For This Will Be To The Point And Wish You Very-Very Be To The Point And Wish You Very-Very Be To The Point And Wish You Very-Very Happy Know Your Next Functions Only For All Times You Are Interested In The Top Ten Lexicographical To Spend Some Time To Generate Just Give Answers For Doing What We can do it is the function to generate new song Video Subscribe Very Fast Solution Adhura Clement And Latest New Look At The Code Of Baroda Process Which Have Explained You Dice Code For Tracking Where Given String In The Name Of Directors And Or Combination Subscribe Points 1202 The first no this is the cockroach 10 Back to Example and Subscribe Our Thursday Subscribe Position in Obscene Vid * Desh 2002 19 This is basically did not in * Desh 2002 19 This is basically did not in * Desh 2002 19 This is basically did not in position not loose and combination length its do subscribe strings in the result will be reduced to 100 years Later this is the on Thursday during the current character adding a to the results string and will be making connectivity call boy doing to the worst position and observe decreasing the length ok nuvve including 800 x 480 width country will remove The Current Position Will Be The Character subscribe The Video then subscribe to The Amazing 2018 Widening And They Will Make This Point To The Missions Next Suhaag Next Will Take Care Of 23 Near The Worst Thing Which Left Soi This Point Is Point Into Your Valid String Danveer Will return to avoid all the combinations subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Difference subscribe Which is nothing but the pointer in the previous switch taken upon interview point 2018 in this case will be appointed TO THE BEGINNING OF THE MAP OF NINTH CLASS TRACTOR COMBINATION INTERVIEW PASS DISTRICT AND DISCRIMINATION AND AVOID YOU TO THE KNOW WERE ALL POSSIBLE COMBINATIONS COMBINATION WE WILL IMPROVE THE POSITION OF THE WINNER COMBINATION SET OK OTHERWISE WILL NOT BE INCLUDED IN THIS Case it can not performing this operation for all the combination will be having all the graphical user name the author of the point to the first combination to do the first operation point subscribe to this point and they will be updating this point to Point To Will Be Written In This Post And Subscribe Will Give This Point Is Point To The Subscribe To And When Will Return Forms Otherwise Will Return To Saudi Operation Sara Gyan Weve The Time Complexity In This Case Was To The Point Log In For Maintaining all elements in ascending order in all possible combinations Subscribe button More You can improve the time complexity of approach Will be coming soon as possible Like Share and Subscribe Thank You
Iterator for Combination
constrained-subsequence-sum
Design the `CombinationIterator` class: * `CombinationIterator(string characters, int combinationLength)` Initializes the object with a string `characters` of **sorted distinct** lowercase English letters and a number `combinationLength` as arguments. * `next()` Returns the next combination of length `combinationLength` in **lexicographical order**. * `hasNext()` Returns `true` if and only if there exists a next combination. **Example 1:** **Input** \[ "CombinationIterator ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\] \[\[ "abc ", 2\], \[\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, "ab ", true, "ac ", true, "bc ", false\] **Explanation** CombinationIterator itr = new CombinationIterator( "abc ", 2); itr.next(); // return "ab " itr.hasNext(); // return True itr.next(); // return "ac " itr.hasNext(); // return True itr.next(); // return "bc " itr.hasNext(); // return False **Constraints:** * `1 <= combinationLength <= characters.length <= 15` * All the characters of `characters` are **unique**. * At most `104` calls will be made to `next` and `hasNext`. * It is guaranteed that all calls of the function `next` are valid.
Use dynamic programming. Let dp[i] be the solution for the prefix of the array that ends at index i, if the element at index i is in the subsequence. dp[i] = nums[i] + max(0, dp[i-k], dp[i-k+1], ..., dp[i-1]) Use a heap with the sliding window technique to optimize the dp.
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
Hard
null
1,235
Hi gas welcome and welcome back to my channel so today our problem is maximum profit in job scheduling so what have you given us in this problem statement here we have given you a n jobs here we have given you a start time like this Time has been given and a profit end has been given. Okay, what you have to do is to schedule the job here so that you can get maximum profit. In this way, you have to schedule the job. Okay, so what is the return and pay here? Here you have to give maximum profit and also keep in mind that no two jobs should overlap with each other. If you are taking two jobs and are supposed to schedule both, then you have to see that both of them Do not come in an interval. It is okay if one of your jobs ends at one point, then you can take another job at that point from where it starts. Okay, then this is your problem, so do this first. Through the example, let us understand what exactly is our problem and how can we solve it. Okay, so look here, I have taken all three examples, so let us understand each example first. Okay, so look here, what have I given you? Here, you have been given a start time, an in time and a profit end. Okay, this means that this is the job, this is the start time, this is on the index, this means that this is this van, this is the time. What is the start time of a job and what is its ending time? 3. Okay then there is a job which is starting on 2 and what is its ending time is 4. Okay then one of your jobs is starting on 3 and on 5. What is happening in D? Then what is yours? Is it starting at three and where is it ending at six? Okay, so if you take this, you will make profit 50 from here, you will make 10 from here, you will make 40 from here. Okay, so you have to see how you will do the job schedule here so that you can make maximum profit. Okay, then see what you will do here, people like this, from van to third, you don't have to take anyone in between. You can take it from three, starting point from here you can take it, okay so everything here we have taken 50 I, now this one is you and four there is one in between also your 24 so are you from here If you want to take it, then you are looking here, is it 50, is it 10 here, would you prefer 50, otherwise we have taken 50 from here, okay, after that it is starting from 3 because this is a van, we have taken it from 1 to 3. So, we cannot take the four from you right because the timings are overlapping, so we will not take this one from here, so after this, if you are starting two jobs on three, one will give 40 profit and the other will give 70, then now to whom? If you want to take it is obvious that if you want to take the one worth 70 rupees, then what will you do from here, if you buy the one for 70 rupees, then what will be your total profit here, it will be 50 + 70 50 + 70 50 + 70 = 120, okay this is what you will get. So, = 120, okay this is what you will get. So, = 120, okay this is what you will get. So, what do you have to do in this way? You don't have to show how you are doing, this is the maximum profit. We just have to show this. Okay, this is our maximum profit. Okay, so let's look at the gate example and understand the problem. We will see what the approach can be then what is your van tu three four five six then yours 35 10 6 35 10 I think I did something wrong is n't van tu three five 1 2 3 6 3 5 10 6 9 this is Your starting time and A in time are ok and what will you do here you will make 20 profit, from here you will make 20, perfect from here, 100 from here, 70 from here, 60 from here. Okay, so you have a job, it is starting on a van, you suggest. You take this, you take 13, you take one and three, here you are getting 10 profit, then what is yours, starting from you, here this is also giving you 20 and going up to five. So why would we do this here because five is going till here, so it is possible that someone may come in between, here too we are getting 20, so now let's take this one, okay then after three. We can pick anyone. After three, we can also pick with three. So here is our three and 10. Okay, there is 3 and 10. Here if we do 100 then we can pick any between three and 10. If we don't have to do right, then between three and 10, if we take this, if we take 100, then what will happen, it will give 10 + 100, take 100, then what will happen, it will give 10 + 100, take 100, then what will happen, it will give 10 + 100, which is your 110. Okay, meanwhile, we come to know that there are two more jobs, four and six. How much will it give here from six and nine, will it give a total of 132, so why will we pick this one, otherwise we will do 130, so that we can do three to one, three to note, three to four to six. It is till, taken from four to six, we then took six to nine, it is giving 70, how much will be your total, it will be 150, right, 150 is your answer, so what is your problem here, this was your problem here. What is the problem? What do we need? Okay, now how can we solve it? So, no, we can solve this problem through 01 map set. How can we do that? Look here, it depends on you, what is your choice? You want to take it, you do n't want to add it to the job, you do n't have a schedule, what do you have to do, you have to rule it, so what will you do now, look at us, there is a job here, it is okay. And it is your choice, here the choice is whether we take this or not, what do we want to get, we want to see the profit, so our choice is here, whether we take this or not. Zero van is being built here, the same thing happens in the next step, right, we have two choices, one you take it, one you don't take it, okay, it is there too, now when you pick a job. What do you have to keep in mind in that condition, here you have been given the condition that whatever job you pick next, it should not overlap, we just have to keep it in mind, right, so we always have to keep this in mind when we Let's take a job. The suggestion here is that we have taken this job, okay, we have taken this job, so we have to keep in mind that between van and three, that is, look at three, from three starting point, you can take any job which starts from three. See what is happening, we don't want any job between this, okay if we take this then the second job should not be between this interval, we cannot take that, so when we pick, we will keep this in mind. If we keep this then what will we have to do to take care of this, here we will have to see which is in its in time this is three which is not its load mount will come out why will we come out lower bound why because we will see lower What happens in bond, any numbers, just greater number or equal number, it is okay, if someone is starting from three or just from three, then this will be our easy one, it means just the job after that, if you want to tick, then this is this. Lower bond, now if you give it a nickel, then you have to get it by nickel, so what will you do, the first choice will be that which will be its load boundary, what is its index of these three, now you can start it from the index, like right, what is it in this case? What will be its loan limit? If it is three times, then the job is starting from three. Look right here, it is starting from three times, so when it is assumed that we have taken this job, then we have taken this job from van to three can table. Now we will see that where is this just greater number, we can take it, then this lower bond will give you this nickel, then you will have the choice whether we take it or not, okay, so in this way, when you pick someone, then It will be your responsibility to fill this condition completely and to ensure that there is no overlapping, you have to go to the load bound and from there you have to pick up the job. Okay, now after going there you will decide which one you have to pick. Or not to do, we will do whatever gives maximum. If we do not pick, will we get maximum profit? If we get it, we will take only that. Okay, so this is what happens in our 01 map set, this will be there and when you do not pick, then you What would you suggest, if you don't pick in this index then we can see the next one from this index, we can see the next one, otherwise these two conditions will become ours, so what do I do, I show you the code, I explain it through the code once. What have we done here, we have given start time, we have given in time, we have given profit, we have given these three things, we are here and we have found your N job, what have we done here, let us create a vector. You have taken, you have made a D vector so that what we can do is insert it, what is the starting time, what is the in time of a job and what is the profit, we have written all three together here, like here there is also an index, this will be yours, second. This one will remain on the index, otherwise this one will remain here, so how can you store it, now what will you do, starting time in time profit 20, then what can you do here, you will insert five, you will insert 20, do this and insert You can do it together, meaning you don't have to do it again and again, we will store it together, we have done it, so what will be required for this, we will need 2D factor so that in this job name vector, we will insert all of them here, start time in time. Profit has been made, now what will we do, we will sort this, the job is fine so that what we get, look here, whatever sort you will do here, it will be done according to the starting time, it is fine for you and we will also sort the starting time here. Why will we shorten this so that we can know how to make our load easy to mount? What should be easy? See how the lower mount is found. This lower mount can be called kind of. You are doing it in binary search. Okay, in binary search we have to What do we do if it remains sorted? We have to find a number just greater than any number. I will find it, so what will we do? We will do it on the basis of the starting number only. Why will we do it because look here when you had the suggestion that If you pick a job, then after picking it is your time, we have to see according to it, whose red boundary will be there, then whose red boundary will be there, you will see the starting time, what will be the starting time of any job, so if you see the starting time, then you You are always dealing with the starting time but you are looking at the value, lower bonds are coming out of it, but you are dealing with the starting time only, so here, what we have done here is that we have sorted the starting time only. There is no need to start the time, okay, we have sorted it here and inserted it here along with the starting time, what will we do, here a record is just a function, find, we have called it first. Geo index has been inserted, this is the job, we have inserted all the three here, that is the one with starting time and M which is the size of ours, it is ok, we will come here when what will happen to us, I &gt;= N will happen. So we will make the what will happen to us, I &gt;= N will happen. So we will make the what will happen to us, I &gt;= N will happen. So we will make the return zero, our base condition is okay, now if we pay us any index, what do we do with it, we pick whatever you pick, okay, so in that condition, we have to keep in mind that the ending time. Find the index of the load bond of which we are fine, so what will you do in this way, you will find the index, what happens now, whatever is added, you do it, whose fining you are doing, you have to do it, so we are in If you are doing time, then whatever is the second element of any index, that is our in time, right here in second, first you do start time and then you are doing in time, hence you will give that value here and begin here. You are doing mines, start the mine so that you can get the index, which index can you pick, after picking the next one, you have two choices here, whether to pick or not, if you pick any index, you will see the profit. So where are you inserting the profit on this index, if it is on second next then you will get job I2, then you will call find now plus you are doing find index because you have selected this I, so you will have to see it in the condition. That we should not take any interval in between, take it with index, what is its load bound, in time, so here you have index people, then job people, start time, end people, okay, this is done for pick, when you will not pick. What will you do then what will you do then you will see from the next type i+1 people go start time n and i+1 people go start time n and i+1 people go start time n and in both of these you see the maximum, what will be your maximum profit here, okay this is done but it will give you early, so what can we do? We will memorize it, there will be N index, so how far can the index go here, it can go till N, so here we have taken DP, we have sliced ​​it from vector end -1 and sliced ​​it from vector end -1 and sliced ​​it from vector end -1 and all the functions are here. I have also inserted it in the find. It is okay here, so what will you do with yours first? If I &lt;= N so what will you do with yours first? If I &lt;= N so what will you do with yours first? If I &lt;= N then we will return zero. Here it is okay, it will be yours, otherwise you will turn zero only, that is why you attend zero here. First of all, you should check whether you have already searched for the particular index. Do not search again and again. Right here, if you have already done so, then we will give you the DP ID. What will we do with the process? We will do this and we will store the value here in DP, okay, so what will happen to you, this will be submitted, so I hope you have understood, if you liked the video, then please like, share and subscribe, thank you.
Maximum Profit in Job Scheduling
maximum-profit-in-job-scheduling
We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`. You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`. **Example 1:** **Input:** startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\] **Output:** 120 **Explanation:** The subset chosen is the first and fourth job. Time range \[1-3\]+\[3-6\] , we get profit of 120 = 50 + 70. **Example 2:** **Input:** startTime = \[1,2,3,4,6\], endTime = \[3,5,10,6,9\], profit = \[20,20,100,70,60\] **Output:** 150 **Explanation:** The subset chosen is the first, fourth and fifth job. Profit obtained 150 = 20 + 70 + 60. **Example 3:** **Input:** startTime = \[1,1,1\], endTime = \[2,3,4\], profit = \[5,6,4\] **Output:** 6 **Constraints:** * `1 <= startTime.length == endTime.length == profit.length <= 5 * 104` * `1 <= startTime[i] < endTime[i] <= 109` * `1 <= profit[i] <= 104`
null
null
Hard
null
506
hello everybody and welcome back to the DC AC channel where we saw at least for this series lead code questions to kind of prepare for technical interviews and just learn programming software Shan's non-patent learn to think I guess I hope non-patent learn to think I guess I hope non-patent learn to think I guess I hope all right let's jump to another question relative Frank's sounds interesting okay so the question is called 5:06 relative so the question is called 5:06 relative so the question is called 5:06 relative ranks given scores of an athlete's find their relative ranks and the people with the top three highest scores will be awarded medals gold medal silver medal bronze medal so basically given an athlete's find the relative ranks and the people with the top three high scores will be awarded medals example one if we have this input our output should be basically this one has the highest score relatively to the other one so it gets too cold won the gold medal this one has the second highest score silver medal third highest score bronze medal this one is on the fourth position this one is on the fifth position let's see the explanation the first three athletes got the top three highest scores so they got god-metal silver scores so they got god-metal silver scores so they got god-metal silver medal and bronze medal for the left for the remaining two athletes you just need to output their relative ranks according to this course and there are some additional notes we know that n is a positive integer and won't exceed 10000 so we know that we wouldn't get any more than 10,000 athletes but I'm kind than 10,000 athletes but I'm kind than 10,000 athletes but I'm kind assuming we could be getting 0 athletes as well so we have to account for that and all the scores of athletes are current guaranteed to be unique so we know we wouldn't be having to worry about any lubrication scores so how do we handle that I think I will be ordering so basically get these names sorted so I will always know the next person that gets another place on the board and to achieve this we are going to be sorting or in noms list after sorting the list we basically know that our athletes are now ordered and I think it was reverse through in reverse order or in descending order and now we need to actually map them to the actual result of noms so how do we do that let's just say we copy a array this would be our output to OB nums dot copy and after that we know that for example we have all that leads here that are sorted and for example and you can see I actually did some programming before him but I was actually not really focused on the exact definition of this task so I had to redo it anyway let's imagine our athletes heads these positions six one two so in other at least with the highest score so with these ones and actually I wanna order them a bit differently so we know something like this so you can I have some diversity and in this case we know that this athlete should get the highest score in our array they are ordered as such and one so we can be going through our array we could be getting the highest basically let's go over our array for our soda terrain or sorted or highest ranked in noms sorted okay so for each one of those hmm we could be going like this or we could be getting the very first three of them and I want to do this beforehand because it will be easier afterwards let's get for example four score in our output which is a copy array we know that if this score is equal to nums sorted zero it should be awarded with output and score should be equal to gold-medal else if our score is equal to the second one in our sorted ranking this one should be called sewer metal and also it is core otherwise is in the third position it will be awarded with bronze medal and just to kind of see that this works I want to just quickly test that what are we getting we're just gonna leave those three and yeah we're just going to test it like this uninvent sorry this is all indented a bit too much I guess okay oh well I guess we'll be getting an index and we are enumerated so we know exactly where we are and we can basically save things this way and if you guys haven't seen the narrate function before it's a very useful function it will basically go over through each of these guys but it will also count indices so you can actually say stuff using the indices if you need to and in this case we definitely need to and as you can see there were silver gold and bronze medal exactly as we hoped to have them awarded what else do we need and I'm actually not going to be doing it this way or yeah I'm just gonna hard-coded maybe or yeah I'm just gonna hard-coded maybe or yeah I'm just gonna hard-coded maybe we can make it a bit better like after afterwards if the lengths our numbs is zero we will just return an empty list and we know this needs to be done because for example if you didn't we just have empty amount of athletes here we would be well we're actually returning the same thing so I just forget about it I think we're actually good even like this let's just test it so if this was some empty lists we should be getting a copy out of an empty list here we wouldn't real iterate and we get the output okay so these are the first three and after we are done with those first three I would actually I just wanted to test this for example we have an array and I want to basically pop the first element a couple of times and I want to see what our array how our array looks like at the end and as you can see we actually popped some elements from the array from the very beginning so we're actually gonna be doing this either we are going to be doing this like that or I'm going through let's see so we know that our elements here have different order and for each of those we need to find them so wait they are ordered now right and we know that this one will get the fourth position but we also need to find it so what can we do we actually we can go over to the for each rank over our sorted nums but we will be starting from the third one until the end why do we start from the third one because from the four form because the first three we already took care of and for each of those we are going for score again index score in enumerate and in this case we are using nums because if we were enumerated over and we you see why and I say that because now we are looking that if our score well our rank and the rain could be four here right if our rank for I'm sorry if our actually no it's actually a score again but this core also has I a rank and the rank would be accounted as let's start as a rank that would be set to be zero four and or even three we know that we have given three ranks already and we are updating our rank and we are on the fourth rank we know that the score here is two and the rank is four so we need to find the one that has the score of tool and assign it the rank for right and if we do this in our very first array then we run into the problem that we are basically creating values that we are looking for afterwards so it is better to have a basically a third array where you can be doing this substitution right this one would be five to put it here in this case we don't really see anything wrong this one of course would be silver gold and bronze but there would be definitely overlaps if we were using our initial array so it is better to have this copied array which would also be the output array so we are going over each score in our sorted array starting from the point after those medals and we know the rank that has to be assigned and now we are looking for a score in the original array and we know if the score well score sorted or ranked score input or initial so we know that if the score ranked is equal to the score initial we can actually substitute this rank or basically the value that was in our output array and this would be our output on the position of index and this would be then our rank and the rank would be also a string so looking at this we are basically assigning ranks we are counting for the ranks and of course we can actually do a continue in this case because after we find the rank we know there are no duplicating ranks we can actually break this and after we are done with this basically score out for our ranks we can go to the next one and actually since here we are yeah since we are actually done with searching in our initial array we can actually you know go to the next ranked integer we can actually break this loop and just go over to the next one and quickly I really just want to test it out see if that works the way it was intended and let's say for example we have 1 &amp; 2 we have them for example we have 1 &amp; 2 we have them for example we have 1 &amp; 2 we have them ordered like this hopefully we didn't write anything in the output array like we didn't mess up the values but I don't think we did yeah so as you can see this is the first place gold medal the second place your medal third place is the bronze medal and then of course this one is the next one to go on the fourth place in the fifth place and how are they ranked the forefront the fifth place well we know that we actually already assigned those three places the very first three places got to Scientology for this one which is here this is correct we were taking it from our sorted array we know it's a - so the score rank score is - it's a - so the score rank score is - it's a - so the score rank score is - the rank itself was basically four because it's the fourth ranked position and here we are looking for where in our anniversary can we find the tool that we are looking forward to put our score rank basically for and we are seeing that it is found on the index position of one so we can use this index position of one and update our output array and basically this is it one once we find this element we don't have to go over to the next one and like we you know we don't really need to search over to through the whole array so you actually break the algorithm basically this loop and we go over to the next element is one it's it gets the rank five because it's got updated twice basically now and we are looking for a five I'm sorry we are looking for a one in this array when we see it's on the index zero so we can use the zero index and put the rank five there yeah so this is basically our algorithm it's a bit kind of it's not the best I think I wouldn't really see any way to do it in one line but I think at least we will get a version that is working and I was actually not that easy I really think I thought it was a way easier algorithm at the beginning and maybe I'm still overlooking something but yeah it was still an interesting algorithm and you can definitely see like you can definitely do solutions for example just having a rank like a fixed rank and just going over the whole list of contestants and just finding the biggest one and always assigning the next rank and the next rank but I don't think well actually no I don't think this would have been a better solution sorting definitely helped and I think you can actually do more magic with the sorted array as is I just don't have it in my head right now I should definitely start making those videos so the beginning of the day are not at the very end but anyway that's for me I hope you guys learned something and I hope it was educational definitely try this algorithm yourself I think it's not as easy as it looks like probably like just watching once you start thinking about it you see that it's tricky to get a hold of all the ending at the hold of the values positions and I like their relevance in the whole idea and actually not mess up swapping values that are essentially needed for later and stuff like that so yeah it was a good time coding this algorithm I hope you found that useful if you are new to the channel maybe consider subscribing it will definitely help me a lot I just hit my head a subscriber go and this sounds like amazing to me already but I'm already looking towards the next goal which would be 20 subscribers so if you could help you with that would be awesome but also thanks to everybody that subscribe although most of you are kind of like friends or family but it doesn't really matter thanks it to everybody and yes see you next time
Relative Ranks
relative-ranks
You are given an integer array `score` of size `n`, where `score[i]` is the score of the `ith` athlete in a competition. All the scores are guaranteed to be **unique**. The athletes are **placed** based on their scores, where the `1st` place athlete has the highest score, the `2nd` place athlete has the `2nd` highest score, and so on. The placement of each athlete determines their rank: * The `1st` place athlete's rank is `"Gold Medal "`. * The `2nd` place athlete's rank is `"Silver Medal "`. * The `3rd` place athlete's rank is `"Bronze Medal "`. * For the `4th` place to the `nth` place athlete, their rank is their placement number (i.e., the `xth` place athlete's rank is `"x "`). Return an array `answer` of size `n` where `answer[i]` is the **rank** of the `ith` athlete. **Example 1:** **Input:** score = \[5,4,3,2,1\] **Output:** \[ "Gold Medal ", "Silver Medal ", "Bronze Medal ", "4 ", "5 "\] **Explanation:** The placements are \[1st, 2nd, 3rd, 4th, 5th\]. **Example 2:** **Input:** score = \[10,3,8,9,4\] **Output:** \[ "Gold Medal ", "5 ", "Bronze Medal ", "Silver Medal ", "4 "\] **Explanation:** The placements are \[1st, 5th, 3rd, 2nd, 4th\]. **Constraints:** * `n == score.length` * `1 <= n <= 104` * `0 <= score[i] <= 106` * All the values in `score` are **unique**.
null
Array,Sorting,Heap (Priority Queue)
Easy
null
1,015
Hello hello friends welcome to my YouTube channel subscribe subscribe to [ subscribe to [ subscribe to 210 cigarette gutkha tujhe 30th september ko hua tha loot lo woh to desh bech open na small different or divisible by that the looters created the earth under the British regional enter end Exit age no Sachin treatment for oo Ajay will be the same This is quite simple but only up to provide 2001 Then which fast food you need Number one team in this matter Number two again Subscribe Its length in number one So we will go from Karte's side and we will go back to whatever description is on the last day, whatever is its length, then we will check on that side when I go to Delhi, we will give it a number, the number is to be set, this channel is subscribe, simple subscribe and our There is no pass number, then if we go to the second one, then Descendent that Meghnad is okay, then we have not added 5151, so now we quote 21 times in China also that the truck, it will never be divisible by two and If you add then you will not be free, then it is not a force, but it is not complete, neither by doing this, there is no such number which can ever happen and same to store 5, if I have time written in it, 50 would come in Anil Hanslas. Someone joins from there, this is the role, it happens with one, then with two, okay, the last line number should be one and the favorite is simple, the class number should be five or should, so we will go with this check, then the first question is simple. We will take that we will increase towards the length, in this, if we get that number, we will not get one number, and if we will not get the number, if we would have taken 5 more inches, then if the guest is more than that length, then do that. Humble request towards that. After implementing tow, we will use it to see how we can optimize it and if what we have done by coding and in many places, we book tickets in Tehsil Aliganj or use Ticket and Sita, then we will decide how we can correct it. If we can, then first of all it is simple that if I see this, it is divisible by two or if it is white on Thursday, then actually what do we want 250 then it should not be if this is right there, brother, we have returned. Have done something, appointed this number, now we have simple again subscribed to the same number, so how can we do this by subscribing to the one and a half inch plus top number, now we are on this number till one, now how long will we continue until that Number is nothing, mind is that a that truck campaign will simple check that number is this number what job we saw so there that number is number plus app will remove one ego here number * remove one ego here number * remove one ego here number * on time ink tank plus one so what will we do now When we got the stick number, now if I get it, then you because I thought that it is necessary that your input poking of these points 1420 then the starting number can come out because when we install okay, still the number is coming off. If it is then same starting same time is ok time limit now one property some number now if it takes time while going there then it took 10 time then how can we use it then we can do whatever we can appoint if it was If we can do it to optimize, then whatever number I have, it is important to remove its notification number, now the city magistrate is directly completed, but if we can get pass 20% in this, then let's do it again and search. If you do n't do it, then it can be another and now we come with another approach, we teach with the help of demand, support comes to us, if we subscribe, we will do it, now we have done it to those who subscribe to our channel, like and subscribe. So then subscribe point two plus channel, subscribe 61 loot and fry for 15 minutes. Then I shifted to us, I came to the trailer, one fit, we had 700, then 366, so we offered the loudest or 21. This proves that when If we had done it then our length would have been shorter, now this is ours and that is very less because earlier we had seen that we always do that which of these is cheating, this is SIM, if we go to the bottom then Mika this Space complexity is like, whatever length is there then subscribe this way so that will be our number. Now we will check on the same that which number is A Picture in A plus one is how is it divisible or not Jhal that if is if which Also we saw the number, it comes to zero, then it is ok, we will return, whatever the situation, when the calculator came to the minute, we commented the calendar, ok, so what we were deciding here while I am in trouble was that if this When the number comes to zero then it is okay to request us and every time we increase the length of this then I have oh I will just keep mixing but now we had said here that we start this 15652 So that we can check the feel maximum to them now in the school or again to log in again now don't do it again first you have to take meanwhile assigned that whatever hit will be equal to the same after all now we just have to type That if whatever we now index number is if it is that we will set one whenever we do the middle then if it is not then you are trapped in this fact - make it then if it is not then you are trapped in this fact - make it then if it is not then you are trapped in this fact - make it 110 otherwise you close every number whenever we go above Stay, we will give the best adv1 by asking that you want, you have muted the volume, don't repeat it again, you can also arrest that this increase has happened, I kept fast in the valley, I did not get robbed, so hey, similar, I have to do something, so we are here. This is what we need, till then we submit. From now on, if we exceed the time limit and according to the address, the tip is that the first SIM was very simple because we only had two , then I told the children, this happens. Or no, it is not available and if it is 125, then we are the first one here, you subscribe, thank you will give to someone, how to do it while subscribe and subscribe my channel subscribe to.
Smallest Integer Divisible by K
smallest-integer-divisible-by-k
Given a positive integer `k`, you need to find the **length** of the **smallest** positive integer `n` such that `n` is divisible by `k`, and `n` only contains the digit `1`. Return _the **length** of_ `n`. If there is no such `n`, return -1. **Note:** `n` may not fit in a 64-bit signed integer. **Example 1:** **Input:** k = 1 **Output:** 1 **Explanation:** The smallest answer is n = 1, which has length 1. **Example 2:** **Input:** k = 2 **Output:** -1 **Explanation:** There is no such positive integer n divisible by 2. **Example 3:** **Input:** k = 3 **Output:** 3 **Explanation:** The smallest answer is n = 111, which has length 3. **Constraints:** * `1 <= k <= 105`
null
null
Medium
null
1,774
so hello everyone in this video i will be explaining the problem closest desert cost so this problem is not that difficult but it can be a little bit confusing uh because of this part lower one so anyway let's briefly discuss the problem so what the problem is saying that you have to make a desert and for a desert you have to buy a base and a topping okay so you have been given base costs uh that is in this vector and topping cost that is in this vector okay and you have been given a target that your purchase should be closed closest to this target okay so upper in the purchasing part i can buy uh i have to just definitely buy one base okay and uh and then i have to buy toppings and for each topping there are only two in quantity so i have to buy zero one or none of each topping and then i have to such that the cost is nearest okay so since the constraints in this video are pretty low it's it suggests me that i can generate all types of combinations of purchase and then from all these combination i will choose the one whose difference to from target is the least okay so what the idea is going to be that i will generate all sorts of costs that are possible using any given data and then i will uh store it and then i will take the one which is closest to the target so my first uh the first part to solve this problem is going to be i will make an ordered set unordered underscore set and costs so what this will store is the all possible costs that are possible and i will make a int difference is equal to 1 e9 so this difference will store the minimum difference that is possible from target for any particular cost that for any particular purchase combination so now what i am going to do is that i am going to make an amount is equal to 0 variable then what i will do is that i will traverse from so since i have to choose only one base cost base so i will just traverse through my just let me rename this to bc and bc because it's very long name so entire is equal to 0 i less than bc dot size i plus so i'm choosing uh basically i'll be choosing my base co bases one by one so to calculate further calculate all the combinations i will write a function called solve so in solve i will be passing my topping cost dc and amount for that particular base cost will be amount plus bci comma what 0 is the index of the topping cost it will start from 0 and target okay so now what i will do is that i will make this function void it will be a recursive function to solve vector and ampersand dc comma int amount comma int index comma into ampersand target okay so since it is going to since i am going to generate all sorts of combination uh this will be a recursive so a recursive has two parts base condition and choices okay so choices so just one second let me close so what the base condition is going to be so the base condition is going to be basically if index is greater than equal to tc dot size so that if that is the base condition if i write uh if i arrive at the base condition i will do something so i will what i will do is that i will explain so my choices what can be my choices so my choices can be solved so i can choose not to buy any toppings so that will result in amount being same and index will increase by one comma target another choice can be that i can buy one topping of that particular type so what will that uh from that what uh my amount will increase by one so tc index my like my amount will become increased by tc index price and again my third choice can be control c ctrl v uh into two just a second into two so these are my all possible choices and then i will return so what is my base condition is going to be so after making all these choices i will reach i will cross or the toppings topping vector and once my toppings factor i have processed all the topping prices all the combinations what i will do is that i will store the amount that i have arrived at into my costs unordered set so cos dot insert amount and i will also update my difference that how close is my amount to the target so that will be difference is equal to minimum of difference comma absolute of what amount minus target so this is the part and now once i have completed all generated all the combinations so what i'm going to do is that if costs dot count what target minus difference is equal to true so for example just imagine that uh for example the target is 10 okay the target is 10 and the minimum difference that is possible from generating all sorts of combination is one okay so in that case if one is the com one is the like difference then there can be two possibilities that there is some cost of 9 available or 11 okay so in this case i will prefer to return 9 because that is the lower one and it has been given in the problem that if there are multiple costs that are at the same distance from target then return the lower one so that is what i am doing if so in this case i will return what target minus difference and if that is not uh that 9 doesn't exist then 11 must exist so in that case i will return target plus difference so that's the problem let's check for any syntax errors so it is fine and now let's submit it so it's accepted so you know this problem is simple initially i was thinking that the target other my possible cost combination can't be above the what the target so that led to my wrong submission in my first attempt but you know you should think about recursion and you should not be afraid because since the constraints are very less you can go exponential it will be 3 raised to n into m into 3 h 2 and time complexity so if the problem is super clear please consider subscribing this channel and thank you and have a nice day
Closest Dessert Cost
add-two-polynomials-represented-as-linked-lists
You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert: * There must be **exactly one** ice cream base. * You can add **one or more** types of topping or have no toppings at all. * There are **at most two** of **each type** of topping. You are given three inputs: * `baseCosts`, an integer array of length `n`, where each `baseCosts[i]` represents the price of the `ith` ice cream base flavor. * `toppingCosts`, an integer array of length `m`, where each `toppingCosts[i]` is the price of **one** of the `ith` topping. * `target`, an integer representing your target price for dessert. You want to make a dessert with a total cost as close to `target` as possible. Return _the closest possible cost of the dessert to_ `target`. If there are multiple, return _the **lower** one._ **Example 1:** **Input:** baseCosts = \[1,7\], toppingCosts = \[3,4\], target = 10 **Output:** 10 **Explanation:** Consider the following combination (all 0-indexed): - Choose base 1: cost 7 - Take 1 of topping 0: cost 1 x 3 = 3 - Take 0 of topping 1: cost 0 x 4 = 0 Total: 7 + 3 + 0 = 10. **Example 2:** **Input:** baseCosts = \[2,3\], toppingCosts = \[4,5,100\], target = 18 **Output:** 17 **Explanation:** Consider the following combination (all 0-indexed): - Choose base 1: cost 3 - Take 1 of topping 0: cost 1 x 4 = 4 - Take 2 of topping 1: cost 2 x 5 = 10 - Take 0 of topping 2: cost 0 x 100 = 0 Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18. **Example 3:** **Input:** baseCosts = \[3,10\], toppingCosts = \[2,5\], target = 9 **Output:** 8 **Explanation:** It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost. **Constraints:** * `n == baseCosts.length` * `m == toppingCosts.length` * `1 <= n, m <= 10` * `1 <= baseCosts[i], toppingCosts[i] <= 104` * `1 <= target <= 104`
Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head.
Linked List,Math,Two Pointers
Medium
2,21,445
17
hey everybody this is larry this is day nine of the lego daily challenge hit the like button the subscribe button join me on discord let me know what you're thinking and what you're feeling and all that good stuff uh happy mother's day for those of you uh in the country that celebrated i guess um to all your mothers out there and stuff like that and yeah uh and if yeah just a quick re-log update and if yeah just a quick re-log update and if yeah just a quick re-log update as i usually well maybe not usually but i try to do from time to time uh the contest yesterday was kind of a disaster in how they ran it um but you know uh these things happen don't get too stressful about it uh take it as free problems and just you know it is what it is you know um sometimes it's just something like silly and people you know make a minor change and it does it all the time it doesn't have to be something structural like there are definitely times where like i don't know some it could be even something as silly as like the front end changing like a minor thing so that it makes two requests instead of one request and then now every and then and the thing with these things is that some and i'm not saying that's the case that happened here but then now uh you okay double the request is obviously bad but even then it actually because certain people were seeing uh there's these like runaway effects where you know latency goes up so then people click on re-spam that refresh so people click on re-spam that refresh so people click on re-spam that refresh so now that extra request now leads to like ridiculous about requests right so sometimes these things are hard to kind of uh happen and yeah maybe they'll learn from it we'll figure it out it'll be it would be very interesting to see if there's a post-mortem um but yeah these things post-mortem um but yeah these things post-mortem um but yeah these things just happens it is what it is people kind of take all these things for granted but uh yeah anyway let's look at today's problem letter combinations of a phone number okay i mean this reminds me of the picture that we just had on that contest that didn't or hopefully it doesn't count because i started very late but uh yeah i don't know why they don't i think they should make these accessible in general and what i mean by that is they should make it like not an image they should like have a way to describe this without it being an image um but it is what it is i suppose for now uh and especially since it's very easy to miss just like looking at this and maybe if you're on a weird or just different platform or maybe browser sometimes there's a lot of inconsistencies but okay but let's say okay let's actually read the problem given numbers two to nine we saw all the possible letter combinations that could return um okay so a two could be an abc okay uh so now we have to type this oh even though you know uh yeah okay so we have just have to do a lookup and then we do a brute force uh one at a time this should be pretty straightforward in that regards um at least in terms of understanding right it's just brute force it's easy to uh you know what brute force means so a is equal to abc and now we're just doing the like annoying thing uh i feel like in other contexts they usually give you this mapping but maybe i'm wrong on that one um oops also like if this was during a contest i'll be a little bit sad only because you know this is like i don't know maybe we should like should this be a thing that i already have ready i don't think so but that would be like wasting so much time typing and also like if i have a typo this would be a really silly thing to uh to have to debug right so yeah okay i think this is right abc e f g h i j k l m n o p q r s t u v w x y and z okay now i know my abcs okay uh yeah so then now it is just recursion right um yeah so then now we have a recursion we have an index mapping to the number of the digits and then the current uh array maybe just cut um and yeah and then now we do we want to request in a serial digit and then we start with an empty array and that should be good and then and we also have a i'm not for these pro i mean i know that sometimes i like to especially on tree like problems i like to keep things like women state and then recursion based on that and then you know combine them together it is cleaner but there is a lot of overhead especially when you're dealing with linear e type things and you're creating a lot of objects so that's why i'm not going to do it here uh and also maybe i'm just a little bit lazy but yeah um if index is equal to n then we appen this and then we return does this have to be sorted in any way or just in any order or in any order okay i mean that i think we'll be keeping it sorted anyway but um but yeah for c in lookup of digits of index um we do a recursion on index plus one uh let's say current we want to append c and then current.pop of course technically speaking if you want to do micro optimization we should um we should have a fixed length away and then just keep on modifying your w a little bit cleaner but uh but yeah that looks good for that one there's empty and we can even play around with more for these problems i also feel like they should have sevens and nines because and even eights just because like i feel like this isn't supposed to be a trick or like maybe not particularly to notice that this is four letters and eight has three letters right so i think that would have been good to test um i am getting a wrong answer here huh so that's good that we're getting a wrong answer i suppose oh i just thought that's out of the way and what are we getting wrong on how ow huh okay so that the wrong answer is actually unrelated in the sense that it is doing with huh because i'm doing an empty string instead of this i'm just trying to think how i want to do it i guess it's okay to just shortcut it right does this yeah can i change the base case of that i mean this is gonna be the same if we just put like a length of current as you go to one or something like that so i'm just gonna do it this way it's about the same all right let's give it a submit hopefully this is good on the first try i feel like i've been sloppy lately um cool 760 769 day streak during recursion um this is going to be exponential um only because that's the size of the output so you can't really do much faster um in terms of space same thing it's going to be three to the n or four to the n or some you know like uh something like that technically fall to the end as opposed because you want to do the upper belt but that's like the lower band right so uh so yeah can we do better than that um let's see yeah i did the same thing except i added the thing here i probably noticed the i mean they give it to you in the input so yeah and actually it's a little bit whatever but okay um cool that's all i have for this one let me know what you think hit the like button hit the subscribe button join me on discord hope you all have a great week this is going to be my last i should have done this during the vlog but this is going to be my last video in new york for a couple of weeks so i'll see you soon and my setup will be a little bit different uh yeah as i usually say stay good stay healthy to good mental health i'll see you later and take care bye
Letter Combinations of a Phone Number
letter-combinations-of-a-phone-number
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. **Example 1:** **Input:** digits = "23 " **Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\] **Example 2:** **Input:** digits = " " **Output:** \[\] **Example 3:** **Input:** digits = "2 " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `0 <= digits.length <= 4` * `digits[i]` is a digit in the range `['2', '9']`.
null
Hash Table,String,Backtracking
Medium
22,39,401
1,639
easy question another hard question you're kidding probably another dp question okay up to a thousand words each string is a thousand as well it's definitely dp but what would this sub problem be i guess would be on the target word so dp of i could be i guess a number of ways to get prefix target um 0 to i and then what would the transition be so when i add a new i don't think i can do it like that let's say for example i have the entire dp ray is 0 let's get rid of this i go through the first column of the matrix how do i deal with duplicates is a duplicate if i see an a i would have to go through all possible a's within the target string and see what the previous value is uh so i see the b here when c and a go through all possible values of a in the target string and add what the number before that was so this a i try to add some the number before that but there is none so i just add one so that's a base case that's why this is two and then i see an a here i'm trying to add a one from the previous one hmm no that doesn't work i have to keep two copies because this b came from the same row this is the previous this is from the previous column and then i make a new copy when i see a b i want to add to the new copy the previous value i came from b so that will be an a here and i'll be one and then when i see an a here i want to add to this a the previous value which is this one and that's zero so that remains zero and this one i want to add the previous value but this is the first letter so which means i actually just want add one right so that's so this is new updated dp array i replace the old one with the updated and then i create a new copy i've made a new copy so now i can go on to the next column is cbc uh the only relevant values here x is actually just a b so i go through all possible b's in my target string there's b and i add on the previous value so one plus a two i'll be three so that's saying that there are three ways to get the string a b from the first three columns of this matrix and is that true well we have a b that's one way you have a b that's two ways you have a b that's three ways so now let's replace the old dp array with the new and make a copy of the new one like so then we can move on to the last column we have aba so i see an a for the first one here it's the first letter so all i have to do is increment that to b3 for this a i want to add the previous one which is three i see a b this b i can add two to this b so this is five and for this a now c and a again so then for the first a i want to increment that to be four and for the other a i can add the previous ones which is going to be six so four five six and there's six ways to do that's correct let's try the different example this one seems good so apparently the 16 ways to get abba and we'll just try do it a little quicker this time so that my dp area is going to be zero initially i have two copies so just be a two for the first column then replace the new old with the new and then within i see i have a b here so this will be a two and then i have an a so this increments by 1 have a b here so that means this is an hour 4. i see another a's and this is 4. that makes sense because four different ways to get an a b so f a b that's one if a b that's another one a b that's one you have a b that's another one so there's four different ways okay and place that copy the third column we have an a here so increment this by one um f of b or make sure this is now an eight and this is now a four see another b so then i have to do that again it's now 12 and this is now an eight and then i see an a so this increments by one and this a increments by zero and then i update the old one and make a copy i'm not to the last column now so i have a b this b here i want to add 6 to this b so we have 12 plus 6 which is 18 so that's f plus 3 so of i guess so let's make this i for this one i add um c to eight okay that's getting out of hand sir so this one would be um 18 which and this one would be 8 plus c which is 12 plus 8 so i get 20. i see an a here so then this would be zero plus eight that's going to be eight and another a so this is going to be 16 and then i'm going to see another b so i add to these ones 18 plus 6 which is 24 and then i have 20 plus c which is going to be 32 but that's 16 and that's the answer so that kind of works out the only thing left to do is um optimize it just a little bit so one thing you kind of notice is that there's only lowercase english letters so actually i could keep track how many a0 how many b's there are so what we can do is actually break this down a little bit so that we have an alphabet a b c p e dot how many a's do we have in the first column there are two how many b's there are two and the rest is zero and that's the first iteration okay and then for the second column i do the same and i see there's two a's and two b's okay good and for the third column i see there's two a's to be so it'll be the same like this and for the fourth columns two a's two b's so it looks like this as well so what i have is a vector of arrays of size 26 and each one denotes the frequency of a letter so they have something like this and then for the target array what you can have is 26 vectors a b c d e where each letter here denotes a vector and these vectors would be for a how what positions well there are in the target string so this will be zero and one and three i think zero one two three for the b here what positions there are um well i have one and two so each one is a vector and so this vector this column is a vector and i think i have to return the answer uh modulo something 10 to the power of 9 plus 7 and i think i can take the modulus as i go along so let's first make this array so let's um do for int i is equal to zero i less than words dot size squares i or into j is equal to zero j less than words i dot size source j and create a vector called frequency a vector of vectors of int called frequency and how many vectors are there's going to be words dot size vectors each one is a vector of 26 characters initialized zero frequency so what we actually do is um actually swap these nested arrays so that we have a g j going from word zero dot size because all the words are the same length then do this in the inner array so this is essentially now going through each of the columns one by one so if i do words at i j i'm going through the columns then i could say the frequency at this word of um this column and this column is given by j were frequency of words i j minus a so since it's in ascii i just turn it into a range from 0 to 25 and just do a plus on this to increase the frequency now that i have that i can make a vector of vectors called position um how many vectors should there be 26 should be 26 vectors empty filled with empty vectors i just want to go through the target word and i want to do position um at this word so target i minus a dot pushback this position i so i'm recording the positions of the letters found within the target and then let's create our dp array called current and previous i guess vector of int so we have a previous of target.size and we'll initialize the of target.size and we'll initialize the of target.size and we'll initialize the zero and also the current the same way and then i go through each of the columns one by one so now i'm going for the first column which means i go through all letters of the first array within frequencies wait this is wrong this frequency is a number of columns so this should be target.size so this should be target.size so this should be target.size this one this can also be target.size this one this can also be target.size this one this can also be target.size it's the same thing actually go through all the letters go through each of the letters and for each of the letters go through each of the positions within target string which is given by position of l for end p in position of l if p is equal to zero just do the current at i at p plus uh no not plus equals to the frequency which is given by uh frequency of this columns this letter else the current at the position plus equals to current p minus one the previous position times the frequency at i well cool so once i've filled out the current um it should be previous actually i'll make the previous equal the current and then at the end return the current at the last value which is target dot size -1 um i kind of went out drinking yesterday so my brain is not working at all i thought yeah this confused me a little bit so you have the same like the words in target but the words within words may not have the same length as target there may be a lot more columns than i realized that all strings and words have the same length so this actually should be uh words zero dot size it should be words zero size not target size should be uh words zero size okay so that's working um let's try this aba so this one's the big one hopefully we get 16. okay cool um let's do the modulus thing so it's working so i actually want to type def long as an ll and then for the dp values they could get pretty large so see this is ll actually i could just do here current p is equal to is modulus equals to mod and that here i could say what mod is so it's const static and mod is equal to one e nine plus seven i should have um actually gone through and checked what the time complexity of this is i think it's good enough because words zero dot size is up to a thousand so you have a thousand times twenty six times a thousand potentially but uh most likely less so it's um n squared times twenty cool let's uh give that a go awesome that's fantastic hard question on the first go yes i'm on a roll i don't know but this one took about an hour and 20 minutes but yeah thanks for watching like and subscribe and i'll see you in the next video and don't forget to keep eating the code
Number of Ways to Form a Target String Given a Dictionary
friendly-movies-streamed-last-month
You are given a list of strings of the **same length** `words` and a string `target`. Your task is to form `target` using the given `words` under the following rules: * `target` should be formed from left to right. * To form the `ith` character (**0-indexed**) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`. * Once you use the `kth` character of the `jth` string of `words`, you **can no longer** use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string. * Repeat the process until you form the string `target`. **Notice** that you can use **multiple characters** from the **same string** in `words` provided the conditions above are met. Return _the number of ways to form `target` from `words`_. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** words = \[ "acca ", "bbbb ", "caca "\], target = "aba " **Output:** 6 **Explanation:** There are 6 ways to form target. "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "acca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "caca ") **Example 2:** **Input:** words = \[ "abba ", "baab "\], target = "bab " **Output:** 4 **Explanation:** There are 4 ways to form target. "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 2 ( "abba ") "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 3 ( "baab ") "bab " -> index 0 ( "baab "), index 2 ( "baab "), index 3 ( "baab ") "bab " -> index 1 ( "abba "), index 2 ( "baab "), index 3 ( "baab ") **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 1000` * All strings in `words` have the same length. * `1 <= target.length <= 1000` * `words[i]` and `target` contain only lowercase English letters.
null
Database
Easy
null
7
foreign so today we are going to talk about this problem it is called a reverse integer so let us in the description so given a signed uh 32-bit integer x i written x signed uh 32-bit integer x i written x signed uh 32-bit integer x i written x with its TZ reversed okay if reversing X causes the value to go outside the sine 32-bit integer range the range is minus 32-bit integer range the range is minus 32-bit integer range the range is minus 2 power 31 to 2 power 31 minus 1 then written 0 okay otherwise just show the Reversed integer okay assume the environment does not allow you to store 64 integers signed or unsigned 64-bit 64 integers signed or unsigned 64-bit 64 integers signed or unsigned 64-bit integers okay example they are given X is one two three output is three to One X is minus one two three output is minus three to one okay for 120 receiving 21 okay so and constants are minus 2 power 31 to 2 power 31 minus 1 okay so these are the constant they have given now let us try to write the code okay so you just need to handle this case which is nothing but out of bound okay if it is going out upon we just need to return zero otherwise it's just a reversing normal thing okay so let us try to do that uh it is an integer we need to integrate it in integer right so what we are going to be doing just create a double okay we can call that as answer initially it can be zero then we can simply run a program or while loop which will do the reversing part for us okay we'll check for X not equals to 0 and then we are going to be doing two things first uh basically three things first we will be getting digit okay which is the last digit here okay we can easily get that by doing X modulus 10 okay X modulus 10 naught hundred okay then we got the last digit now what we are going to be doing we are going to be adding that into answer so answer equals to okay and that is equals to answer into 10 okay that is okay let's put the brackets there then plus the digit which we have got and the last thing which we are going to be doing is dividing that X by 10 so that we can get the new number every time okay so suppose the value is one two three it's initially it is X is one two three we go we went into this we got the last digit as three in this case when we divide this one to three by ten we'll get the modulus we get three okay so 3 is in this so 3 starting it is 0 so it gets to add directly here then we are dividing that number by 10 so it becomes only 12 okay so now digit is having 3 in this now again when we run the loop we'll be getting 2 this time okay so 3 is already present in answer so it becomes 30 plus 2 gets added so it becomes 32. okay then again it gets and the X becomes one okay so for one also it happens like this and it's get reversed like this okay so I hope that was that part now we just need to return that which is will do tap casting integer and will I get an answer from here okay so one condition we are going to be checking is here only that it goes out of one suppose the number is very close to this range okay to power 31 something okay so in that if we just multiplied that number by 10 okay so that this is the part where it can go out of bound correct so we need to handle this answer case okay so we just need to check that if answer is greater than equals to integer Dot Mini max value okay if it gets out of max value of integer or answer can go below okay minimum value so dot min underscore value which is new written 0 in this case okay so that is the part okay I think this will handle all the cases let us try to run the code okay so it's working fine for this output okay try to submit the code here it's working fine yes okay so that's it for this video I hope you got it's a pretty simple question uh try to uh do it okay that's it for this video foreign
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
1,450
What will this suggestion do or going to the question number of student wing Shiromani female homework on prime time student now we started listening to Ek Cup Suji Hai because of this and end student is front time subscribe this recipe and subscribe our channel Do that if we look at the second example, this one, in this dream 181 means I am doing it, there were bigger festivals than this, hello because Vansh how seventh class result 2017 fluid will do 0.5 inches from the seventh thrill, result 2017 fluid will do 0.5 inches from the seventh thrill, result 2017 fluid will do 0.5 inches from the seventh thrill, then we will take two that I am dot science. Side not aborted now our time fibroid thank you this is written in pune for every time e main wait of your call fragrancet kar denge india join kar denge song hai aur sanao kya kar rahe ho that we see actually started before or after And after that turn on the setting and let's see if it is coming right, then from here onwards it is a very simple question, the dark mobile.
Number of Students Doing Homework at a Given Time
delete-leaves-with-a-given-value
Given two integer arrays `startTime` and `endTime` and given an integer `queryTime`. The `ith` student started doing their homework at the time `startTime[i]` and finished it at time `endTime[i]`. Return _the number of students_ doing their homework at time `queryTime`. More formally, return the number of students where `queryTime` lays in the interval `[startTime[i], endTime[i]]` inclusive. **Example 1:** **Input:** startTime = \[1,2,3\], endTime = \[3,2,7\], queryTime = 4 **Output:** 1 **Explanation:** We have 3 students where: The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4. The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4. The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4. **Example 2:** **Input:** startTime = \[4\], endTime = \[4\], queryTime = 4 **Output:** 1 **Explanation:** The only student was doing their homework at the queryTime. **Constraints:** * `startTime.length == endTime.length` * `1 <= startTime.length <= 100` * `1 <= startTime[i] <= endTime[i] <= 1000` * `1 <= queryTime <= 1000`
Use the DFS to reconstruct the tree such that no leaf node is equal to the target. If the leaf node is equal to the target, return an empty object instead.
Tree,Depth-First Search,Binary Tree
Medium
null
373
Hello everyone welcome to my channel, a very easy question, actually it is a very standard question, this type of question always comes in hip and it is a standard question, this is fine, find pairs with smallest sons is fine and Google asked this question. The most important thing is science, I told that if it is standard, then the standard solution which is absolutely hip, first we will create it, we will optimize it is okay and this will be the first discourse and where will it come from, as you will get it, okay, so the most basic approach. What will happen to this, Brute understood, did it in one go, said that you will pick one number from here, if you pick one number from here, then it is ok, do the same as mother takes, this is one, if you pick from here, then 12 sorry 727476727476 Picked up all of them from one and picked up the top minimum one, out of which one, four, one, six is ​​the which one, four, one, six is ​​the which one, four, one, six is ​​the minimum. Look in front of both, what is the sum of one, three, its time, five, its time, plus the smallest. If you pick up one then brat force is very simple right key what will I do two people have to run loop on two i = 0 two people have to run loop on two i = 0 two people have to run loop on two i = 0 i &lt; mm m say the name of all one is the length ok i &lt; mm m say the name of all one is the length ok i &lt; mm m say the name of all one is the length ok i plus this is very simple one more The loop will run that Namaskar name for each eye is only taken out at 2:00. Okay, only taken out at 2:00. Okay, only taken out at 2:00. Okay, see how I will put it in such a way that what was the even. Okay, so now they will be sorted in the ending order like this, the smallest band will be at the top. So when I will put it all in, then on priority I will pick up the top elements, what will be the top elements, which will be my minimum because I am putting it in mini hit, if everyone is okay, then I will give the whole sequence, whatever sequence I am getting, I will get all the elements. I have put all the possibilities in Preetiko, okay, so now this is a very dirty solution actually because I have put all the possible legs in the minimum hip and picked up the top minimum elements and returned them. Okay, so the smallest one is that. I will take out whatever I want, select the elements and put them in my result, six, so this is a very dirty solution, okay, we can butter it a little bit and the butter that I am going to do is the solution, okay that. I also understand you and in this playlist of mine in Hip's playlist, I have asked some such questions in the beginning from which he would have learned the method and now I am going to repeat the method from Revise RBI. Okay, so let's take a small example. Later we will come to this problem, what is the example of 321876? Okay, it has been said in the question that let's take mother. It has been said in the question that brother, take out the top three smallest elements and show us the top three smallest elements. So, there is a way that you can sort them and what are the ones with simple toxins? You will get 123, okay, but the standard method, minimum is required, okay, what did I do Now I am not telling you whether I have to take only I or max only, okay, probably you must have seen my video which I have told you this thing, first of all I came three, I put three, okay here, after that came two, I put two, look at me, how many elements are needed, three elements are needed, not just three minutes, then the size of the hit is more than three, honey. I won't give it's more than three, no, there is a forest here, I gave it to the forest, now which one is here, I do n't know yet, but when I came here, let's go, I gave it to the forest, but you can see which one is there. Mine should have been 3 i.e. the which one is there. Mine should have been 3 i.e. the which one is there. Mine should have been 3 i.e. the size of the hit should not have been more than three, so now I just have to remove one element each, so you think for yourself, what I told you is that you want minimum elements, so which one would you like to remove, it is easy. Which one would you like to remove from you which is a big element i.e. will you remove the larger element i.e. will you remove the larger element i.e. will you remove the larger element? No, it is obvious that you would like to remove only one larger element. Right, this means that if you guys take only Max, then what will happen from Max Hip or in the top? There will be a larger element and you can remove it easily, okay, so what do we do again, let's run it, okay, first came three, then you, now sense, you are small, then you will come down, 3 will go up, then one is small, one A. Will go to the bottom, then you, then three, after that comes 8, now as they come, science comes, the biggest one, here comes the butt, look how much the size of the hip has become, it has become that of a Greater Dane, so what will I do to everyone, I will pop the one who is on the top. So I popped this 8, okay till now it's clear, made it from then on, then seven came here, okay, so what did I do, give science grater to 7, size became three, so popped the seven, then six is ​​six, also top. But it will remain because the is ​​six, also top. But it will remain because the is ​​six, also top. But it will remain because the biggest element is our maxi and science size, which is &gt; K, so I size, which is &gt; K, so I size, which is &gt; K, so I popped it. Okay, now let's agree that I have one more element, there is also a zero here. So I would have come to zero and put zero, now this riff would have been successful, at the bottom, zero would have been A, then it was made, then you come, then three comes, this race becomes successful, B itself is fine, then I saw the truth of good hip&gt; Yes, so let I saw the truth of good hip&gt; Yes, so let I saw the truth of good hip&gt; Yes, so let us top the one above, okay so look at the cake, now I have processed all the elements, now what do I have to do by blindfolding, I have to process all the elements in the hip, reverse it, what should I do? Will go to zero one, these are my top three minimum elements, so notice me, maximum, how much was the size of your hip, if it was only K + 1, then how much was the size of your hip, if it was only K + 1, then how much was the size of your hip, if it was only K + 1, then only its size would be approx. If we talk about its size, then it will be closed approximately. Okay and think about its time complexity, I sense, what am I doing, I am pushing some element, how much is the hip operation, the logo is off, the size of the hip is the size of the logo is off, it will seem okay in the operation, so this is a butter approach. And I will apply the Se approach in this problem now, you can apply the butt style now, I repeat once again with the current problem, so let's solve the Se problem one day with these standard techniques, okay and this is actually Brat force is the method because look at this, pay attention now, what will we do like mother take I, mine is here, yes, mine is here, okay, so what did I do, one comma tu, and its which is even, one plus tu kya. There will be 3, right, I have given it to you, see which will be the priority, what do you have to find in the question, minimum, whose minimum is even, then what will I take, I will take max hip, okay, and as soon as the size of my hip becomes bigger than K, I will pop it. I will give the element with the largest one. Okay, so the one whose sum is the largest will be on the top, then I will delete it, easily, it is empty right now, so what did I do, the sum of both is three and by not doing one comma, I will also index it. Can I put the index? If I put the index then what will happen? Index number zero is the index of one and index number is zero number. Okay, now you can also put the value, there is no problem, okay till here it is clear, remove the one after that. Given again where A went one comma four is right but if I index them further then the biggest one at the top will be even five, here A went index which is index I meaning zero and here index J means One is ok, this is also added, after this it is bigger then ok next to which is bigger then what are the elements 1 is 6 what is the sum of both 7 is science this is an even bigger element so 7 here is one I index I, what is zero, what is index J, what is you, this is also added, after this, let's move ahead, we will apply the method immediately, see, it is okay, he will love others, okay, so I am trying all the trees, so from root four, this Where am I and J 7 coma are you okay so what did I do Nine is the biggest time so he will be on the top Look at the size of butt hip He is greater than that Date is 3 So I have to delete someone So Now, which one will I delete which is the biggest element because it has been asked in the question that I have to remove the minimum sum, then I have to delete the biggest element, then I will easily pop the proper band, so I have popped it, okay? It has popped, it will definitely not happen in the future, it is fine till now, it is going well, now we will move it forward again, J will go to G, mine will go here, what is the sum of both, brother, first write down 7 and this is four elements. If the time of both is 11, then 11 has been added here. What is the i8 index? What is the index and what is the brother-in-law index? what is the brother-in-law index? what is the brother-in-law index? Science is 11. The biggest time is the obese, he will be on the top but give a greater butt size, if it is done then the hip will pop, then it will pop. This will happen on its own, this top only got popped, I removed it, okay, now let's move ahead because the maximum time is whatever will be in this top because I am popping plus the maximum right here on the maxi, so the biggest in the top. If the one is even, then it definitely does not have it and both of them are 13, so again here we have 13 and what is the index, you are and its index is zero. Okay, so 132 again give the greater and the size is done and popped it on top. The one next to the big one is ok 114 and what is its sum 15 so what has come brother you are here I will pop the top guy this is gone again now here comes here what is this big one 17 ok which To process the player's way, you will have to put a loop on the two, which I showed you above. If I can get this one from the look on the two in all the legs, then it will be off M, cross M, then it will be okay, but now inside the loop on Har Par. What are you doing every time, here you are also doing push and pop, so what is the point of pushing? People, of the size of the hip, how much maximum will be given, okay, so now the question comes that friend, is this time complexity acceptable? Will it be accepted in the lead code or not? The answer is no but if you make a little slide improvement in it then it can be accepted. Look, now I will tell you how, then see if you make a little improvement and you will get the answer yourself. Look, pay attention to this. So you know, I will have to write because I have to process all the pairs. Okay, so okay, I have applied two formulas here, I have removed everything, Namas plus one, sorry, till now it is clear, now look, only three things can happen, earlier brother. Why is it my priority, what is its size, it is of Lee Dene, if I am of Lee Dene, then it is an obvious thing, you do not have to put any meaning, right, so what will you do now PK = PK dot top Which is the first element of the element in it? It will be even, it's okay if it's greater than my current time, okay look, I'm repeating it again, there's a small one mixed at 1:00, so I have to small one mixed at 1:00, so I have to small one mixed at 1:00, so I have to put this one, so what will I do first, I'll push the current one P K dot post which I have just got a small one, okay, the band which is in the top of the priority, look here, I go back to this example, okay, on 7th, the band which is in the top of priority here, the new band which has come now is even. Let's take his society, it is 13, okay and remember which index number was that index number, it was one, okay, now you think for yourself, when this 13 will come here, he will see that the guy at the top is smaller than me. Okay, I am small myself so will I put it as obese so no I am obviously but am I like which element was taken from the number one, 7 was taken okay and which element was taken from the name was six okay now think for yourself, let's take mother then Brother, this will be even bigger, so this will also come to the top, then it itself will become the top, as soon as I get a bigger sum, then I will increase I again, that is, I can break the loop on the K one, how can I break it? The two reasons are that brother, as soon as I saw that I was like my J was here and I was here then I came which element is the name of the name is 7 that is right plus j3 who is in the time of both 13 so Obviously brother is younger than the top element, so anyway he will come on top, then he will become the top later, okay, so I will not put this one, right, after this, when we move ahead, we will get a guy bigger than six, not bigger than this. If you get only Banda, you will get eight or you will get none, then all of them will also be big, when yours was big, then after this, when it will be added to eight, then what will happen if you get 15, this will be even bigger with you, so go ahead and know that J. There is no point in going further, right? Take K back here and make i bigger. Now explore i. Here you simply break it. Break it. Okay, after that it will start again from i0, otherwise it will move forward again. It will start from zero, that's what I wanted to say, do it small, otherwise your solution will be accepted, now it is very important to know the root four solution also, explain it to you by stressing it well, okay and what I told you in priority, three things store. There will be sum and index i index, so it is an obvious thing, what will be put in the priority, okay now it is an obvious thing, earlier how we used to define normal priority, eat vector of and vector of eat is defined like this, PK is fine but what about here? This will be all on one, that is, look, I will define it, there will be a separate interior and I am late for both of these, okay, you define it directly, without any other compiler, that is only the max is distributed, so this is actually my max hip and If I had to make only mean then I would make P vector of P which is then greater and P but science here we also want maxi so our definition will be exactly the same right and look you should understand why max hip It is ok so that as soon as my hip size becomes that of a Greater Dane, I will remove him, it is a big time and has a big value because I want smaller sons, so I would like him to be on the top or I can delete him. Dun and Max come to Kispay at the stop, Max stays in the hip, okay so let's code it quickly and yes, time conflict here, you must have understood that it will be less than this, right, how is this my worst, isn't it, people are off. Okay, I am processing it completely but I am not processing it here, as I know that I will break it internally, I also told you the example here right, so let's code it quickly. And let's see if brute force is accepted or not then let's quickly solve our brute force. I always repeat that never ignore brute force. Brute forces are very important especially for interviews. So just start. Let's do what I told you in the beginning that I write in the beginning that what is I on the off eat, time, then there will be a foot of income entry, then there will be index, okay, I have defined P and let me define the priority. Priority is this. What would happen to me, but it would be very clear to me till now, Forint J = size L, if you want to give it then anyway, you don't have to push it, right? We will push P K R, first what is the time and after that what is I, comma J, it is okay. And if the sum is greater or equal to yours then I am going to check it and not pick top first i.e. the not pick top first i.e. the not pick top first i.e. the element which is on the top of the sum, if it is greater than my current sum then now I can pop it. I will pop that PK road that brother, you are a big element, so pop it and push it is absolutely clear till this point, comma JCO is clear and if it is not so, then it means the sum of the banda at the top is that. If Smaller goes to America then break it is clear from INLD till now, okay so it is a very simple code, simply what we did is we processed all the pairs and added them. Now my simple vector will have only elements of vector, don't ask for more elements than this. If I am doing this, then I will put all those K elements in my result until the priority key is empty, then I will remove it from it and you time = PK top, it is very simple result dot push underscoreback, I don't want to add index to it. If you have to enter the value, then I know that the first banda name was taken from one, so the name will be of one and the second banda name will be ok, then after submitting, we will see that brother, we can pass this on bread also. No time compressed, pass all these test cases, which date is the case, indeed yes, they have solved this question, using is going to come today in which I will also tell about its optical, which will be made of mini hips, sorry, it will be made from hip only, but we will optimize it further. Will take without processing h and every pairs okay to come if there is any doubt comment area video thank you
Find K Pairs with Smallest Sums
find-k-pairs-with-smallest-sums
You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`. Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_. **Example 1:** **Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3 **Output:** \[\[1,2\],\[1,4\],\[1,6\]\] **Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\] **Example 2:** **Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2 **Output:** \[\[1,1\],\[1,1\]\] **Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\] **Example 3:** **Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3 **Output:** \[\[1,3\],\[2,3\]\] **Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\] **Constraints:** * `1 <= nums1.length, nums2.length <= 105` * `-109 <= nums1[i], nums2[i] <= 109` * `nums1` and `nums2` both are sorted in **ascending order**. * `1 <= k <= 104`
null
Array,Heap (Priority Queue)
Medium
378,719,2150
347
Yes, hello, I am one of the developer children, Gary Ni. The problem to be solved today is number 347 kp quant elements. A pure number array is given, and an integer k is given. Sort the elements that appear a lot, cut them as much as the top k pop k, and retan them. What is the order? It doesn't matter. 1233 This arrangement and k are given. It appears 3 times, this appears 2 times, and 3 appears once. kkok It is 123 that heats the order of most encounters, etc. Among them, only this first element needs to be returned like this. Let's solve it. In order to store how many times a number appears, I will declare an object called Pat and store the information here. By using the arc position method of the mouse array, if the corresponding item of Mr. is found, it will be added because it has appeared once. If it didn't come out, it came out for the first time, so we set this to 1. Then, we store the number of times each number appears in the hash. And now we can create an answer array to perform the answer lolita. Well, I'll always use it. So, I'll save it as a series of the corresponding number of the answer series and how many times that number appears. The ceiling is completed. Next, I'll sort the answer bears using the sort function in the order of the most frequent occurrences. Because of this, it is sorted in order of wedding order. And since there is no need to listen as under this kk, I will cut it by inserting kale using the splice method. If rk join 5 and this encoder array is 3, only 2 elements will remain through the Berni method. The array in the upper level is currently in an array of two, and what I want is the number that appears the most, so I use my palm number and return it like this. However, since this has been used as a key up to this point, I put a string in it, so I wrap it in a number function. 4 The test case has been cleared. Let's submit it. 4 You can see that it has passed normally. This problem also has a 20-session tab, so it would be good to try solving it in a different way. That's This problem also has a 20-session tab, so it would be good to try solving it in a different way. That's all for today's video. If the video was helpful, Please click like and subscribe once. Thank you.
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
119
welcome back everyone to another video here in the uncle YouTube channel today we're taking a look at problem 119 askal's Triangle 2. now this one is going to be very similar to the first one except slightly different this time around we're going to be given some row index and we want to go ahead and return that actual row of the Pascal's triangle based on the Zero index so once again what the Pascal triangle looks like is it's going to be the sum of the two numbers directly above it like we see here so the first one is one we have one and we have one plus one here is equal to two and one plus two plus one is equal to three and one plus three is equal to four three plus three is equal to six three plus one is equal to four so on and so forth as we go down the array let's go ahead and take a look at the examples and compute some things and then go ahead and go back and figure out how we can do this so for example number one we're given the index equal to three so the first index is going to be equal to just one the second index is going to be equal to one the second index is equal to one two one finally the third index is equal to one three one but now we'll go ahead and return one three one that's how the first example breaks down let's take a look at the second one for example two we're just given index equal to zero again this one's obviously pretty easy this is just going to return one that's a pretty silly one let's take a look at the last example in the last example of given index equal to one still pretty trivial so index zero is equal to one and index one is equal to one we return one just like that let's go ahead and take a look at the constraints and try to figure out how we can solve this as quickly as possible so on this one the only constraint that they give us is zero is less than equal to row index is less than equal to 33. obviously this just means that the greatest number of rows we're going to compute is 33 this also means that once we get down to the 33rd row these are going to be pretty large numbers so we might run into some issues with sizes of integers things like that so what to worry about that it also means if we're trying to compute all of these at once or over and over again it might be a little bit slow so that means that there must be a faster away which we'll talk about in a second so once again the goal of this problem is to generate a given row of a Pascal's triangle at a given index and then return that specific row that the problem was looking for like I was saying before there's two possible ways to solve this problem the first one includes generating the entire Pascal's triangle all the way up to the row that we're looking for we've already done this and you can still do it relatively quick and beat a good portion of the runtimes on the platform however there's actually a mathematical equation that we can use to calculate any row that we want to find we can use this equation to quickly calculate all the indexes of the rows we're looking for in a single Loop without having to store the entire Pascal's triangle up to that point and then return the specific index let's go ahead and take a look at the pseudo code for this problem and the example walkthrough for hopping over the lead code so for the pseudo code we're going to start out by saying let result equal a new list this is we're going to store the actual row then we need to go ahead and add 1 to the index 0 of a result this is because this is obviously our base case the top one is always going to be equal to one then we want to go ahead and loop from 1 to the row index plus one so obviously here if it's only going to be zero we're already at one we're just going to go and return that list but if there's anything bigger than zero we'll start calculating but now obviously we'll calculate the next index of row and then add that calculated index to the row and once this Loop is over we'll go ahead and return that result list so this is a little bit cryptic so let's go ahead and dive into our example so we can figure out what this mythical calculation is so our example again will once again be looking for index equal to three so like I said we'll go ahead and start out with a list equal to an empty list the last for the loop will be equal to index plus 1 which is equal to four obviously and the current value will be equal to one now we want to set index 0 of the list to the current value which is equal to one so now our list is equal to one our last is still equal to four our value is still equal to one obviously now we start our Loop for I equal one our list is equal to one our last is still equal to four values always total equal to one we want to recalculate our value so a value will be equal to Value times last minus I but this is going to be equal to one times four minus 1 which is equal to three and if you go back and look the second index or I guess the first index of the third row is definitely equal to three so now we still need a little bit of calculation so now we're going to say about equal to Val divided by I which is going to be equal to 3 divided by one so now we have our vowel so we're going to go and add value to list but now I equal to 2 our list is now equal to one three our last is total of four obviously and our vowel is equal to three once again we go ahead and calculate Val so Val is equal to valid times last minus I this is going to be equal to 3 times 4 minus two which is either three times two but we also need to say Val is equal to Val divided by I this is going to be six divided by 2 which is equal to three now go ahead and add value to list again for I equal to three our list equal to one three our last is equal to four and our Val is equal to three once again Val is equal to valid times last minus I so this is equal to three times four minus three which is equal to 3 times 1 which is all obviously three no need about equal to Val divided by I which is equal to three divided by three is equal to one we add the value to list now I equal to four our list is equal to one three one our last is equal to four our Val is equal to one now I is not smaller than last this means that the loop ends let me go ahead and return that list we created nope it's as simple as that one single calculation can literally determine any single row that we want let's go ahead and hop overly code and take a look at how we code this here in leak code we're going to go ahead and start out with our new result arraylist so list integer result is equal to a new arraylist obviously we need this so we can actually go ahead and store the entire row and we need a long previous equal to one like I was saying earlier this could be a pretty large number so we want to make sure we have enough space to actually store this we're going to go ahead and set results dot add previous as an integer again this is our basically our base case so no matter what the first index or zeroth index is always going to be equal to one then we're going to Charter for Loop 4 and I equal to 1 I is less than or equal to row index and I plus I'm going to say long current is equal to previous times row index minus I plus 1 divided by I this is basically those two steps that we did previously merged into one then we're gonna go ahead and set a result.add that current as an INT then result.add that current as an INT then result.add that current as an INT then we need to go ahead and set our previous value equal to the current value so we can go ahead and calculate the next value and we'll Loop through until we've gone all the indexes in that row then we want to go ahead and return result so this one I feel like I probably typo this equation somehow so let's go ahead and give it a spin and see if I talk about anything would you look at that actually got it right in the first try that's pretty lucky but this is a zero millisecond runtime which would be to 100 the other option if you do go ahead and create the entire Pascal's triangle it's like one millisecond it beats like 50 or 60 or something like that so this one is really faster but anyway as always if you guys did find some value on this or you just enjoyed please leave a like comment subscribe everything helps out here in the YouTube journey and as always this has been Ethan encoder hope you all have a great day and I'll see you in the next video
Pascal's Triangle II
pascals-triangle-ii
Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** rowIndex = 3 **Output:** \[1,3,3,1\] **Example 2:** **Input:** rowIndex = 0 **Output:** \[1\] **Example 3:** **Input:** rowIndex = 1 **Output:** \[1,1\] **Constraints:** * `0 <= rowIndex <= 33` **Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space?
null
Array,Dynamic Programming
Easy
118,2324
701
Jhaal Hello Hi Guys Welcome to Kodiasar Today's question is insert into binary search tree in this question also Aryan root node of binary search tree and value to be interested in the trees were buried under root mode of the best ifton shown it is a rented a new Value did not exist in the original BSP noticed that when combined multiple well as for the information available on the subject each of the information you can write any form for example disposition tree this for 21 30 to insert values ​​in node this is Not 10 insert values ​​in node this is Not 10 insert values ​​in node this is Not 10 minutes nod ki vinod we can notice reduce the tree after getting this all handed over sp leaders not violet the principles of mystery birthday for multiple ways of interesting history for example so insult phase not be left elements of smaller and elements of the This website brigade team saw in multiple values ​​of uncertainty note subah can write any one way or in multiple values ​​of uncertainty note subah can write any one way or in nine reliable questions knowledge took it upon this question can not be given up B.Ed up B.Ed up B.Ed person in this post I will not know weather divine Divya Incident And 3000 233 Of The Best Known For Win32 Nobody Will Go To Website The Right Side Not Being Undertaken And Person Responsible From State Bank Account Incident Route Noida And Greater Than There Route Not Any Way Consider This Lesson 7 Days In The Middle Of The left side of the world we move from moving from 7th form of value that now Louis Vuitton method of inserting value and will an English joint with flute counter with the left address office 7 suggestions will approach question no let's get another example a thousand bastes pipe And 1217 Dimple Yadav 39 Is To Deposit Will Be E Will Be Equating Four Values ​​In E Will Be Equating Four Values ​​In E Will Be Equating Four Values ​​In Route Notes Element Input Balance Input Value 90 Countries End Druts And Vinod Import Adhikari Route Not Immediately Informed That You Will Be E Will Be Inserted In Difficulty Value This Day Root Not Nor Will Move To Left Direction Listen And Roots Vikrampur Not Give Check The Weather In Food Value Is Loot Notes Value And Read And Not Believe In This Case Which Can See Hidden Truth Not Valid Notes Will Have The Year Printed On That Now No Root Note Value Hai Begum Ban Norms Unchanged At Unkindness Value In Food Value Is Dresses Note Value And Less Drut Note Value Hidden Truth Not Value Develop And Attain Liberation Otherwise Development In Right Direction Vacancy Date Meaningless Meaning Is Coalition Soe Develop And Only Right Side of the one note but vacancy dot right side one not a good citizen al morning to will form root mode of value three length belt joint increase ride point and off the front reduce one note suggestion will do the question no this app and dresses 123 right Side you Bhigvan first notice banat notes and will return this and Vitamin C Root of the Tarzan The Swadeshi thought will solve question no Let's look at record of this question Sunao Vinod Left for insulting value investing Divyavani Tasty ways to traverse through the best EE Review of Prabuddha Elements of Tasty Suno Let's Do You Travel and Travels Give the Respective Were Traveling in a Tree and Deaths Were to Difficult A Function to That Developed Function Name the Help of the Return of the Day Jai Hind Fauj Entry Date Par Date to Return Also root of entry sudhir typist free notes of will it be the case that is root double do internal soft but will happen i will have what will happen rabbit letter shifted to find a correct position for certificate position of the new value 233 snow and currently They Are The Truth Not Support Se Example This And Contributes For Insulting Hindu Is 500ml Set First Shift Value Been Selected Value In Hindi Roots Value A Little Jaati Roots Value Than What Will Not Be In Contact With Mills And Insulting Value Will Be A Company Will B Incident Draw Iqbal reborn left side to the root left and wins it and party value2 that boat will look 319 pallu is not less than the roots value david value in that case what do we call the half divine acid of the best all the right side to the root right Value And Now When We Met Modi Calls Dirty Politics Loopholes And The Also But Will Do Vitamin C Root Of The Final Tree Nor Will It Be Know What Will Happen On To Initially I Worked For This Root Not Inserting Value Is Pipe First Will Come In This Function End Check Enable You To Insert This Visible And Not Being Under Root Value Inserting Value Is Not Present Value Swift We Go To Right Side No This End Children And New Root End Children Victims 799th Urs Again Will See Divine Kant Is This Roots Elegant 798 Check Divinely Live In Discussing A Its Correct Know What Will U Will Make A Call On This Website And Widening Vacancy Date Of Birth Left Side Has Left Side Is This Left Side Basnal Morning Encounter Null Butt Will do it well and internal what will oo will first form of new note that bill not pass time that film its time and so its value get also slice 250 to insert new job note value that atal turn on this time a pointer see turn off But have done this entry was only till there is digital seven next9news for the new node 510 returns and vitamin this address and decided to 5-wicket win in the address and decided to 5-wicket win in the address and decided to 5-wicket win in the times when the president will dare devil torch light bill gates or roots left development this country function Was Called From Hair Helper Happiness Times Valuable Gifts To Roots Left End Vitamin C Root Of The A Pre So Dishaon Bhi Has Incentive Aluminum Industry Animal Function What Do You Simply Write This Address At The Red The Simply Write This Address At The Red The Simply Write This Address At The Red The Function Root Value Of This Questions and Answers Jai Hind Main India Mein Help Ki Suraj Which D Code Is Running And I Got The Video Thank You To
Insert into a Binary Search Tree
insert-into-a-binary-search-tree
You are given the `root` node of a binary search tree (BST) and a `value` to insert into the tree. Return _the root node of the BST after the insertion_. It is **guaranteed** that the new value does not exist in the original BST. **Notice** that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return **any of them**. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[4,2,7,1,3,5\] **Explanation:** Another accepted tree is: **Example 2:** **Input:** root = \[40,20,60,10,30,50,70\], val = 25 **Output:** \[40,20,60,10,30,50,70,null,null,25\] **Example 3:** **Input:** root = \[4,2,7,1,3,null,null,null,null,null,null\], val = 5 **Output:** \[4,2,7,1,3,5\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-108 <= Node.val <= 108` * All the values `Node.val` are **unique**. * `-108 <= val <= 108` * It's **guaranteed** that `val` does not exist in the original BST.
null
null
Medium
null
399
hello everyone welcome to date 30th of april challenge today is the last day of the month and after solving today's question all of us will get the april batch this will be the 12th batch over the last one year and yes we have solved each and every question from past 365 days without fail my name is sanchez to introduce myself i am working a software developer for at adobe and here i present day 671 of daily lead good problem the question that we have in today's evaluate division so here they have provided us with few equations their values and followed by queries what do we need to evaluate these queries using the values that are present as part of equation and the values array that we have so i'll be walking you through this example as well as the algorithm to go about it by the presentation so let's quickly hop on to it lead code 399 evaluate division it's a medium level question on lead good and i also feel the same also in case if you have any doubt understanding this question or if you want to ask anything from me in general please feel free to ping on the telegram group or the discord server of coding decoded both the links are mentioned in the description so do check them out so let's take the same example that are specified in the question and also remember by analyzing these equations and values together consider them as a single unit what does this mean let me just walk you through that so here it the first entry in the equation represents a comma by b that simply means a by b evaluates to 2 and the second entry is b comma c so that means b by c evaluates to 3. so consider these equations and values as an atomic entity do not consider them as separate values separate data what we need to identify the value of a comma c that simply means a by c the next one is b by a followed by a by e followed by a followed by x so this is a wonderful example because it covers all the possibility of test cases that we can have and let's talk about the algorithm how are we going to arrive at these values using the data that we have in the question now let's try and understand the queries part so if you carefully look at the first query what do we need to evaluate what is the value of a by c and how that can be done so let's walk through the equations and the values that we just analyzed uh we have a by b as 2 b by c r 3 so what we can do we can simply multiply these two values up and what do we get a by b into b by c so b and b in denominator gets concerned with b in numerator and the value left is a by c so what that value would be it would be equal to 2 into 3 so you can figure out that using multiplication across these values something can be figured out and that this equates to 6. now comes the question how can we actually process this information so that we reach the required queries that can be done using graph how let's walk through the same example so what we are going to do we are going to build a graph how are we going to build this graph let's go step by step the first entry that we see is a comma b and the value happens to be two so we'll build a graph starting from a and it goes up till b with the value of two so let's write two here so consider this as an entity where that signifies that a by b happens to be value 2 pretty straight forward along with this we'll also store another value in our graph that would be b by happens to be 1 by 2. so using this information you can reverse the denominator with numerator and the value that we get will get updated to 1 by 2 instead of 2 so these two equations are exactly the same so we are also going to store this information in our graph so b by a represents 1 by 2 so this information you're also going to store in the graph pretty straightforward so at each entry there are two values stored the first one is the character or string and the second one happens to be the value so again it would be of type string comma double so let's represent it over like this so each entry each connection or each edge is represented by the starting node which would be again of type string and uh the value would be a map of string comma double because string will represent the node up till which the connection goes and the double value represents the value part that we derived from the values r a let's proceed ahead next we see is b comma c so let's do the same thing again so b by c happens to be three so again a new connection will be established and here it would be equal to b by c happens to be three so we'll store this information again in the graph so right now we have three nodes a by b is 2 a b by a happens to be 1 by 2 and b by c happens to be 3 along with this we'll also store an information that c by b happens to be 1 by 3 so this also makes sense to us now comes the question how are we gonna find out the queries part so let's get started let me just highlight all the uh nodes that we have built in the graph so these are the four nodes and let's get started with solving the queries let me just change the color of pen the first equation that we see is a by c so what we can do we can start the dfs traversal or the vfs traverses anything of your choice what is the starting node happens to be a that means uh we will look out for a node in our adjacency matrix or the graph so the first can and we can go on by traversing in this graph via dfs reversal or the bfs reversal so the first node that we see is b so uh the value here is two so let's store this value too and for let's proceed ahead now from b there are two options the first part is from b to a since a is already visited we will not go on to that path again the other path that we have is from b to c and the value here is three so let's proceed towards that path and what we are going to do we will multiply this value from the previous value that we have traversed so far the previous value that we traverse this 2 so 2 into 3 gives us 6 and what do you see here you see that this happens to be our terminal node for the query a comma c therefore we will avoid the process and return whatever product we have identified so far while traversing starting from the a node up till the c node and the value becomes c the final answer becomes 6 as 6 is the answer that we found we will simply return the value for a comma c as six so this we are done with this equation the rest of the equations are really simple here it's b comma a b comma the direct connection over here you will simply return one by two then you will go for a comma e you can see that by when you traverse in the dfs fashion starting from a node and you keep on searching in this graph you will never witness e node therefore what you should do you should break the dfs once the traversal is done all the traversals are done and you'll simply return -1 in those cases so answer here return -1 in those cases so answer here return -1 in those cases so answer here becomes -1 next in an interesting case becomes -1 next in an interesting case becomes -1 next in an interesting case and that says a comma a when you whenever you see that the target value happens to be equal to your source value you should check whether this source value is present in your graph or not if it is present then you simply return 1 in those cases this case is an exclusive case that we have to handle out of the regular dfs operation now let us look for the last case where we have x comma x again the values happens to be same for the source and the target however x is not part of our graph as a result of which we'll simply say minus 1 for this particular query so these are the four cases that we discussed and let's quickly walk through the coding section and i'll exactly follow the same steps as i have just talked here so the first thing that i have done here is to build the graph using the equations and the values array that i have so let's walk through the build graph helper method and then we will look out for the rest of the algo so build graph is really simple you create a graph of type uh the key happens to be string as i talked in the presentation the value happens to be again a map of type string comma double where this signifies the target uh this signifies the value that we extract from the values array so let's write it in a better form this is my source or start comma map will have end comma value now let's start the iteration so you reverse over the equations that we have you extract the starting element you extract the ending element you extract the value element you add it into the graph one connection would be starting from start up till end and the value would be val that the connection would be from end up till start and the value here would be one by val rather than the val because you have reversed or swapped end with start once you are done with this you simply return this graph back to the caller method and let's go back to the caller method now what i have done here i have created the answer array that is a return type double because the question itself tells us to do then we go ahead and start reversing over the queries that we have and also i have created a visited set for the dfs reversal which will be needed so what do i check whether my source which is query dot get r0 is index happens to be equal to my target value if that is the case then i go ahead and check whether my graph contains the source or not if it does constrain contain then i can simply say that the answer for this part would be 1 and i increment the value of i so consider this as i plus and in case my graph doesn't contain the source that simply means you cannot find that value in your graph you simply done minus 1 in those cases and this is it i have incremented the value of i so this is an important corner case which people often tend to miss out and once i'm done with this what do i invoke the dfs method for the cases where my source is not equal to my target i invoke the dfs method and whatever value is returned from the dfs helper method i simply set it to my answer and i proceed ahead with the next reversal in the end i simply return the answer now the problem reduces to writing this dfs method appropriately so the first parameter signifies the source the second parameter signifies the terminal node followed by graph and the visited array that we have created or set that we have created so in case my graph doesn't contain my start what do i simply return minus 1 in those cases in case my graph contains start and uh this that at that particular node i can see that there is an edge up till the end so what do i simply return the corresponding value there moving ahead i simply update my start node to visited set and then uh what have i done i have iterated over all the entries of or all the connections that i have starting from the start node and i check whether the uh key the terminal node was visit was part of the visited set of or not if it is not part of the visited set then i invoke the dfs reversal on that and in case the value returned from that dfs traversal happens to be not equal to minus 1 that means the path does exist so i multiply my current value with entry dot get value and return it to the caller method if this condition is never met that means by the dfs reversal the value returned was minus 1 and in those cases the path doesn't exist either as a result of which we have simply returned minus 1 in those cases signifying the dfs was not met successfully so let's try this up accept it with this we have successfully completed all the questions of the monthly challenge april 2022 and this is our 12th batch without fail we started our journey from may uh 2021 and today at 30th april we have solved all the questions over the entire year starting from may uh till today and we have in total got 12 badges so if you remember this video i'll be glad and there's another announcement that i would like to make that is i'm going live today and the agenda for this live session would be let's celebrate the achievement uh this is our 12th batch 365 days without fail it's a big achievement in itself apart from this i'll be giving away a surprise amazon gift card to one of the daily contributors of coding decoded github repo who have solved along with me all the questions and submitted solutions over there for the month of march 2022 last but not the least i'll be going over your doubts in a lie in this live session so i'm pretty excited about it and i hope you guys will be able to find time to join in and i'm looking forward to seeing all of you there
Evaluate Division
evaluate-division
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable. You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`. Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`. **Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction. **Example 1:** **Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\] **Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\] **Explanation:** Given: _a / b = 2.0_, _b / c = 3.0_ queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_ return: \[6.0, 0.5, -1.0, 1.0, -1.0 \] **Example 2:** **Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\] **Output:** \[3.75000,0.40000,5.00000,0.20000\] **Example 3:** **Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\] **Output:** \[0.50000,2.00000,-1.00000,-1.00000\] **Constraints:** * `1 <= equations.length <= 20` * `equations[i].length == 2` * `1 <= Ai.length, Bi.length <= 5` * `values.length == equations.length` * `0.0 < values[i] <= 20.0` * `1 <= queries.length <= 20` * `queries[i].length == 2` * `1 <= Cj.length, Dj.length <= 5` * `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
Do you recognize this as a graph problem?
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
Medium
null
1,442
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my daughter's I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screen cats of the contest how did you do let me know you do hit the like button either subscribe button and here we go yeah cue to count triplets that can form to a way that you go XO given an array of integers oh okay oh yeah so this one well I feel a little off maybe all the sniffles in the beginning as well but this one I was I think I spent some time trying to figure out whether I can do better than n cube so n is 300 right which and cube is 27 million which is really cutting it close but then it took and I was thinking about how to do it and I end up doing with C++ because I thought that n cube with C++ because I thought that n cube with C++ because I thought that n cube at the time I don't n cube would be 27 million which is cutting it close I think for the lead code for enqueue maybe you could get away with it but it depends on how strict or not strict maybe two test cases will be and I just wasn't confident about that particular piece and now I'm in this moment I'm thinking about well can I do better than n cube you know and I was like yeah maybe not let's do C++ so that I know if maybe not let's do C++ so that I know if maybe not let's do C++ so that I know if there's ever a one time thing that I could you know then I could just it wouldn't be like it wouldn't factor in as much if that's an intended solution so yeah so now I'm just setting up their way I would say so the reason why I took 10 minutes on this problem I think is actually because I did it with prefixed um I so you definitely can't do a prefix um and in the explanations later you I explained why he fixed some works but looking back right now looking at my and I you kind of see me hinting at trying to do this but I was just really worried about off by once that I didn't really think it through in retrospect I should have did what I am doing here where I didn't really need the prefixed time I could just calculate on the fly but I just wasn't doing it quite right so now you see me doing perfect some looking back I probably spent five minutes about this because I was doing it with perfect sum which is correct but I was not necessary what I would did before with her into a like calculating just honest dreaming basis it's not as you don't put in an additional full loop you're probably okay and that's why I was a cute too and I made it more difficult than it needed to be because I think actually I think I just to be honest I think I've washed it a little bit as well man totally given if it doesn't seem like it because that led to me just I don't know like I feel that guy was not optimal in this problem and I here and now just I want to double check that I J and K oh yeah and I spent a silly amount time on well this one it's okay I think I was just thinking about what I won which you know I at this point I spent way too much time on this but I Shep don't I the other thing is that I should have known better here is that so actually I think I mostly got to yeah mostly got to index while but like I knew what to look for but the promise that if you're really good at bitwise operations then you notice what I'm doing wrong and usually I'm better about this but again today maybe it's just one of those days where a little bit silly so I went and I was like okay that's way that right so let's put this out but the short answer is well okay see if you could spot the bug immediately let's say there's no off by once so see if you can spot the bug leave a comment below if you spot the bug before I actually do it before I actually fix it right up but yeah I was like okay maybe there's enough fine one which that one actually I was like okay it's still not right and now it is about 10 minutes and I end up spending at least three more minutes on this silliness but I think if I just not did prefix um just would be much faster problem here I printed I was like wow this is a lot of stuff and I had to mentally just figure out where the indices I spent it there's a lot of time wasted on this one I think if I had been able to submit as that when I did then this would have been an okay problem for me I mean like the prom it's okay it's just I would have considered it that I did okay but this debugging was painful and yeah see if you can spot the bunt because I took me a while so maybe that's like a fun challenge at home and in a fun way this debug statement actually does not help I know like that doesn't make sense well it does by omission maybe so if you're if you caught it before I fixed it mad props to you because I really took a while what the answer is that the D cooperation has higher precedence than the bitwise operations so yeah and now I'm able to be like okay at least it is more correct I might have enough fire one pair this is more correct and now I'm able to use my debug code to be like okay where am i off zero to one that should at least be a two so I've have enough by one there I also recommend in general just printing our stuff because yeah you have to learn how debug not every contest not every interview is going to go 100% and every interview is going to go 100% and every interview is going to go 100% and you want to prepare you in those cases that you know if you do well we know if I want to Stephanie a place where well things happen and I hear I'm looking the constraint again because I'm like just making sure that I didn't miss read it but I think I don't know I wasn't focusing on my energy because that doesn't make sense of the output yeah looking and then the antis looks good so I submit and that was a hard problem for me you to count trips that can triplets that can form two arrays of ecoegg so yeah so this is prefix sums I took a while because for some reason I yeah I thought that and cube it's a little bit too slow maybe but it's actually not n cube strictly it's n choose 3 which cuts down it's about like six times faster or something like that wealthy so that's why I initially turned into C++ I was like oh maybe I needed to into C++ I was like oh maybe I needed to into C++ I was like oh maybe I needed to be the fast loops but it turned out not to be necessary and I think after that though even when I was convinced I was just a little bit off by one in certain places in Alvin I think to think that I had a little needed murder fine was that this would work properly because I worried that I would XO a number with itself and obviously you can't or you can do it but when you do it you get zero instead of that's what I was scared of but actually end up being pretty straightforward and end up taking ten minutes on this problem but it was sharp and faster but the idea is that it took actually explained it all I mean stuff just what I did so the in this one you can note that the big key to no solving this form is noticing that well let's say you have some except I X or X a PI sub I plus 1 X or I sub I plus 2 dot a sub X or a sub J so that's equal to a sub 0 X or a and you know maybe we could space it out a little bit just so that the visualization is easier a and then Todd a sub I so that a subject right something like that but it is this whole thing X owing there are prefix just prefix that's before the I minus 1 right okay so this is someone like that and want you to notice that then well it's prefix sums and I maybe you don't even need to be honest because that maybe we could do some smart things into loops but the prefix some it became easier to just focus on the my off by once because I knew I would have potentially issues with one five one because of why said about the J and K and the other thing that was a little bit maybe odd but maybe not is that even though I has to be strictly less than J has to be less than or equal to K and I think I didn't have an off by one which as soon as I fixed it was able to submit Bao still not confident after that I was just yeah but yeah cool so that and after that you could just try all possibilities of ijk that's just given and then it's a little tricky to get off by once right but that's pretty much it no yeah so it's been a while since I did one of these cold reviews so let's actually do a couple of code reviews and see where I can learn cuz I definitely did not sound contest way well I end up at 174 so the second one I took way too long it's just I did with prefix um but as you might have saw on the video earlier and I was like oh yeah I should have just do it one in Kell which is the same idea and I started it but I was worried about off by once I really did not I just needed to slow down and think about it more but instead I end up taking more time as it we saw yeah similar to kind of these things for you just keep a running track and that's pretty much it wait this is well this is an n square so that's pretty cool I have to be about this later oh I see what it's kind of that's actually really clever that I didn't really think about at all but basically I do is that into code X or some is civil then there are then for every index that's inside that index like so basic you're given I and J if ya forgiving I and J then if the running count from like I've everything between a zero that means all the indexes in between those two indexes will be true because that's like that like if there's equal then they were EXO will always be wow that is a because you're dividing them in halves and byte if by definition because yes if a xop is 0 that means a is equal to p and does and this is and just kind of reworded that back and it's true for all indexes wow that is actually a great answer that's I think that's the kind of stuff that you get when you're good at math oh yeah everyone else okay like good but I still either way I should have done this really quicker because it's known to be good anyway but where I shoved on someone like this with the rowing number but I did not unfortunately because I was worried about off-by-one Finister I also went about off-by-one Finister I also went about off-by-one Finister I also went off by one so that didn't really save me yeah same thing here with the n square so well played I know in something today that was kind of good I don't have I learned enough to be able to do it next time still good cool now this is an N square prefix some dad also does the same thing so yeah red what okay I mean it's just for you it's the same I just the other ones with the same idea and square algorithm where it uses the dynamic programming to do it that way that's clever and to get zeros and then sum up all the counts in between that's a pretty clever way of doing it I was actually thinking about something similar for n square by couldn't come over to any contest well at least I didn't want to spend more time coming over it so I do know a little bit okay
Count Triplets That Can Form Two Arrays of Equal XOR
number-of-operations-to-make-network-connected
Given an array of integers `arr`. We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`. Let's define `a` and `b` as follows: * `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]` * `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]` Note that **^** denotes the **bitwise-xor** operation. Return _the number of triplets_ (`i`, `j` and `k`) Where `a == b`. **Example 1:** **Input:** arr = \[2,3,1,6,7\] **Output:** 4 **Explanation:** The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4) **Example 2:** **Input:** arr = \[1,1,1,1,1\] **Output:** 10 **Constraints:** * `1 <= arr.length <= 300` * `1 <= arr[i] <= 108`
As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters.
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
null
1,801
so hello everyone welcome to this new video and i will be explaining the problem number of orders in the backlog so this problem is a little bit tougher than medium because this problem is pretty long okay and as humans we avoid doing long things so but you know what if you read this problem if you read this statement this paragraph is the key to solve this problem it will be pretty much clear to you that what data structure you have to use and how to solve this problem okay so uh i will be i please pause this video and i suggest you that please read this statement carefully okay and if you i hope you have already understood this example okay i just don't want to re-explain and waste time i will get to re-explain and waste time i will get to re-explain and waste time i will get to the coding part okay so let's solve this problem so i will be using this statement to solve the problem okay so first things first let's uh code it so the first thing i will do is that since the answer can be pretty large what i will do is that i will make a modulo in time is equal to what 1 in 9 plus 7 okay uh not a big thing so now what i do is that i read this problem statement if the order is a buy order you look at the sell order with the smallest price in the backlog okay so you know this thing is saying look for the smallest price in the backlog okay and in the second statement you it is saying that look for the largest price in the backlog okay so when you read this kind of things like look for the smallest you know like in a group of things uh what should strike you is that you have to use a priority queue okay so for this problem i have to use two types of priority queue one is maxip and a minip okay so first so in case of a selling backlog in cell backlog uh i it should be the least element should be as at the top so it should be a what minip i guess it is called a mini uh sorry if i intermix them okay and one will be a maxi in which the top element will be the largest so that will be the that will be my buying uh backlog okay so let me let's make these priority queues so let me increase the font 16 will be fine actually it is the maximum so let's make this what is happening so let's make this priority queue priority underscore queue priority queue vector int okay so these vectoring are the order okay buy and sell orders so let's name it bpq that is buying priority queue and one will be our minip so priority underscore queue vector in so to make a min heap what you have to do is that along with this thing you have to write uh two other statements vector component one is greater uh let's name it spq okay so and what you have to do in this uh this vector and greater is that just copy and paste them paste okay uh i think i should just decrease the font a little bit okay now it is fine so i have made my two priority queues okay return zero oh just to check if i have not made any uh what uh these arrow mistakes okay it is fine so now what i will do is that just a second okay cool so now what i will do is that i will do i will make a for loop and process all the orders okay all the orders one by one okay so just let's write the follow for entire is equal to zero i less than orders dot size i plus uh so the orders can be of two types uh it is said either it can be a buy order or it can be a sell order okay so first of all let's make another vector in order it just basically means the current order so i just is just because i am writing this because it is easier for me to explain like this so now the order can be two types so if order orders uh order two the second is it is a it is zero then it means that it is a buy type of order else it will be a cell type of order okay so if it is a by type of order what i will do exactly what this statement says so i will see i will make a while loop so while is not spq i will just explain it in a while empty spq is not empty and what spq dot top 0 is less than equal to order zero okay so basically what i'm saying is that what if this statement is saying that if it is a buy order okay you look at the sell order with the smallest price in the backlog okay so since uh sell order is a min heap so if the sell order is not empty uh cell priority queue is not empty i'm looking at the sell orders top element that is the minimum the smallest one and if the smallest ones price okay the price is less than the current order then i will do something okay so uh so this is what this while loop means uh so now what i will do is that uh you know they will be matched and executed so and that cell order will be removed from the backlog okay so what i will do is that i will remove that cell order from the spq so let's make it factor in what selling let's name it selling batch is equal to what spq dot top and i will remove this selling batch from my uh priority queue spq dot pop now what i will do is that there can be two possibilities either the selling batches amount is greater the number of items in the selling batch is greater than order or it can be less than okay so if selling batch one is greater than or equal to order one then what i will do is that i will just let me go full screen uh okay so now what i will do is that so first thing first i will do is that i will it since it can be greater than the order so i will reduce the number of amount the amount in my selling batch so selling batch one minus equals to order one okay so as a result what will happen is that my all the amount in my order current order will get exhausted it will become zero okay and if the selling batch is not exhausted if the selling batch still has some amount left then what i will do is that if selling batch is greater than equal to sorry let it be greater than zero then what i will do is that i will just push it back into my spq dot push into my uh selling backlog because something is still left okay batch be a dch so and after that i will break from this while loop because why because all my order is exhausted okay on and the second possibility can be else if the selling batch is less the amount is less than the current buying orders amount so in that case what i will do is that i will simply order one minus equals to selling batch one so my current uh amounts order will be used to cancel this selling batch okay and i will go and look for another what another order in my backlog so that's it and after this while loop is completed what i will do is that if there is some current order still left if order one is greater than equal to one then what i will do is that or let it be greater than zero okay if there is something left then what i will do is that i will push this current order into my buying backlog so bpq dot push into what order so i don't know if i'm doing a decent job explaining here because this is a pretty long problem but i hope you are understanding it okay so in this way i have processed what if my order is a buying backlog okay so now what i have to do now the thing is pretty simple now what i have to do is that exactly the same just vice versa basically okay so ctrl c i will just copy this thing ctrl c and paste this okay ctrl v so in this case what i will be instead of s i will be writing bpq is not empty and bpq dot top is what greater than or equal to the current order because you know this is what it is saying if the order is a sell order you look at the buy order with the largest price okay with the largest price in the backlog if that buy orders price is larger than or equal to the current sell orders price they will match and be executed and that by order will be removed from the backlog else the sell order is added to the backlog so this is what i am going to do here so uh i have written this statement now what i will uh instead of writing selling batch here i will just make it buying batch so buying batch will be bpq dot top and bpq dot pop after using that i will pop it out of my buying priority queue and now there again can be two possibilities either the buying patches amount can be greater than the order so in the if the buying batch is greater than the order then what i will do is that buying batch minus order one and my order one will be zero and if the buying batch is still greater than i'm sorry buying batch buying batches amount is greater than one then i will push it to bpq dot push buying batch also i had done this mistake here it should be one here buying batch one okay so after uh doing this uh another thing can be is if the buying patch is smaller than the current orders amount then i will subtract this buying batches amount from my current order and in the end what i will do is that uh in the uh and if my selling uh selling batch the current order is a selling one okay so if the current orders amount is greater than zero after this while loop then i will push it into my spq backlog okay so you know this is the thing main thing you have to do so i have done this now uh my thing is done now what i will do is that i will just make a what int res is equal to zero and while i will just process that whatever is left in my priority queues i will just uh i will just count them okay so while is not bp bpq dot empty while bpq is not empty what i will do is that res is equal to i will increase my results count okay so res is equal to res plus what bpq dot top one percent m uh so here also it will be percent m because amount can be go a little bigger than like what 10 raised to 9 so i will just add it and now what i will do is that bpq dot pop and now again i will write a while loop while is not bp for spq while is not spq dot empty uh what i will do is that res uh just basically the same thing ctrl c ctrl v so i will write s here and return res so that's the problem so let's submit it so it is running fine on the test cases now let's submit it and hope if it is working it is 100 faster that's very good so you know just let's summarize it so this is basically a simple priority q questions make two priority question the main thing is writing this logic it can you can go wrong but if you follow these statements the statements that are given here it will not be very much tough so if you have understood the problem please like this video and subscribe the channel so thank you and have a nice day
Number of Orders in the Backlog
average-time-of-process-per-machine
You are given a 2D integer array `orders`, where each `orders[i] = [pricei, amounti, orderTypei]` denotes that `amounti` orders have been placed of type `orderTypei` at the price `pricei`. The `orderTypei` is: * `0` if it is a batch of `buy` orders, or * `1` if it is a batch of `sell` orders. Note that `orders[i]` represents a batch of `amounti` independent orders with the same price and order type. All orders represented by `orders[i]` will be placed before all orders represented by `orders[i+1]` for all valid `i`. There is a **backlog** that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens: * If the order is a `buy` order, you look at the `sell` order with the **smallest** price in the backlog. If that `sell` order's price is **smaller than or equal to** the current `buy` order's price, they will match and be executed, and that `sell` order will be removed from the backlog. Else, the `buy` order is added to the backlog. * Vice versa, if the order is a `sell` order, you look at the `buy` order with the **largest** price in the backlog. If that `buy` order's price is **larger than or equal to** the current `sell` order's price, they will match and be executed, and that `buy` order will be removed from the backlog. Else, the `sell` order is added to the backlog. Return _the total **amount** of orders in the backlog after placing all the orders from the input_. Since this number can be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** orders = \[\[10,5,0\],\[15,2,1\],\[25,1,1\],\[30,4,0\]\] **Output:** 6 **Explanation:** Here is what happens with the orders: - 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog. - 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog. - 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog. - 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog. Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6. **Example 2:** **Input:** orders = \[\[7,1000000000,1\],\[15,3,0\],\[5,999999995,0\],\[5,1,1\]\] **Output:** 999999984 **Explanation:** Here is what happens with the orders: - 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog. - 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog. - 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog. - 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog. Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7). **Constraints:** * `1 <= orders.length <= 105` * `orders[i].length == 3` * `1 <= pricei, amounti <= 109` * `orderTypei` is either `0` or `1`.
null
Database
Easy
null
474
hey everyone welcome back and let's write some more neat code today so today let's solve the problem ones and zeros we're given an array of binary strings and two integers M and N it's gonna be fun saying those two because they sound so similar so suppose these are the binary strings that were given there's five of them each of them is composed of just ones and zeros and we're given a couple integers let's say m in this case is 5 and N in this case is three just like in this example over here we want to return from this the length of the largest subset of this set of strings we can create if we're allowed to use at most this many zero characters so m in this case corresponds to zero and these are the zeros in our input strings and N corresponds to one so these ones over here and we can use at most three ones and at most five zeros so I guess the first thing you might consider is can we just take all of these strings all five of them well how many zeros would we get in that case we'd get one two three four five six seven that's too many zeros how many ones would we get in that case I think we're allowed to get three but we would get one two three four five six seven so more than we're allowed to get so we definitely can't take all five of these strings so then how do we intelligently figure out how many we can get well the Brute Force way to solve this problem would be with a decision tree so for each one of these we consider if we include it so in this path maybe we're including that string and the other path is where we skip it and we don't include it and we make this same decision for every single string so continuing with this decision tree here we can either choose to include zero one or we skip it here we can do the same thing include it or skip it so you can see each one of these paths is going to tell us by the time we get all the way to the bottom each one of these paths is going to tell us which one of these we would have included or not included and each one of these paths will be a different subset and how do we know which one we're going to return from all of those well we're going to find the one that is the longest as in it has the most strings in it and let's say in this case that's going to give us a 4 we're going to get a set of four I think that would look like this these four over here because in that case we'll have three ones and we'll have five zeros so these four do satisfy our requirements and it's the longest possible set we could create the largest as four strings in it so that's what we would return now this Brute Force approach the size of this decision tree the height of it is going to be in the worst case the length of this strings well the size of this array that's the height of this tree is going to be we can call that n and we're going to be branching twice every single time so to calculate the size of the tree it's going to be roughly 2 to the power of n so it's not super efficient how can we make this better well as we go along this decision tree we're going to be keeping track of how many M's and ends we have initially it's five and three this is how many we have available to us and then when we go down to this path we don't have five and three remaining we have four zeros remaining and two ones remaining because we used one of each and by the time we get down here we have three less M's remaining because those keep track of zeros so instead of having four and two like over here we'd have one and one because we used three zeros and we used one of our ones and we'd keep doing this now we're keeping track of our M's and our ends but we have a third variable which is going to be I it's going to tell us which string we're currently at first we start at the first string then we go to the second string then we go to the third that like decides what level of this tree we're in as well so we in total have three parameters M and an I but we can use these three parameters to implement a dynamic programming technique called caching or AKA memoization but we have to calculate how many possible combinations will there be for these three parameters well for M there's going to be what the capacity of M possibly was so we'll just use M to denote itself same with n it can't have more possibilities than these it'll be from zero all the way through what the true value of n is passed in as a parameter so we'll have M times n times the length or the number of strings we have in the input let's say that's so overall this is how many times the function could be called our recursive function when we cache the result every time we compute a possible value for it we're going to Cache it and then we're never going to have to repeat that work this time complexity will be the same as the memory complexity as well because this is the size of our cache now let me show you what I've been talking about this entire time so this is going to be the memoization code I'm going to show you our cache is initially going to be this dynamic programming hashmap it stands for dynamic programming this is our recursive function I'm going to call it DFS you can call it what you'd like but we have three parameters i m and n the other parameters we don't have to worry about because this function is nested inside of this one so in this recursion we know it's going to be pretty simple but we do have to worry about a few base cases one is what if we go out of bounds like how do we know when we can stop going through all the strings well when our pointer I is equal to the length of that array in which case we can return 0 because there's zero strings that we could add at that point if we don't have any left to choose from and the other base case is if this has already been computed meaning if this Tuple is already a key in our DP hash map then we're just going to return the value that this key corresponds to now if neither of the base cases execute then we actually have our recursive step so we're going to call DFS now we have two choices remember we can either not include the value not include the string at index I what would we do in that case then we're going to call DFS on I plus one and we're going to leave M and N the same we're not going to do anything with them now the other case is if we're going to include the string at index I in that case we're still going to pass in I plus 1 we're going to go to the next string but what are we going to pass in for M and N because we have to count how many zeros were in the string which string am I talking about well it's the string at index I we have to count how many zeros there were so I'm going to run that function count the number of zero characters we also have to count the number of one character so let's do the same thing here and let's store these in a couple variables let's say m count and N count and then using these counts we're going to subtract from these variables so M the new count of M is going to be what it originally was minus the M's in the current string that we just used same thing for n so let's do just this now we have our two recursive calls what do we want to do with them we want to figure out which one led to the maximum that's what we're trying to do here we're trying to find what is the maximum number of strings we could include without overflowing these two restrictions so let's just take the max of both of these I'm going to write it like this I don't know what the cleanest way to write it in Python is but I'm going to put it onto multiple lines this Max we're going to set it equal to the value but we're going to store it in our DP hash map using this as the key and we of course want it to be set to the maximum and then after that we're going to go ahead and return that same value actually I missed something here maybe you already caught it but how do we know that the remaining count of M and the remaining count of n is actually valid what if this be became negative that means we didn't have enough zeros or ones to actually use the string at index I in the first place so actually we have to change this a bit I think the easiest way to write it is to initially set the value in DP equal to this value where if we were to skip the string at index I and then we check this if M count is less than or equal to how many M's we're allowed to use and N count is less than or equal to the number of ends we're allowed to use then in that case we will possibly be able to set the new DP value equal to a different one we'll have to set it equal to the max of what it currently is and the max of this call down here so let me cut that and add it down here clean this up a bit but maybe this was even more educational to have caught a bug la live as we're coding so these are the two cases now we just have to actually call our DFS we'll start at index 0 our M and N count will be whatever is supplied to us up here and then we're just going to return the value that we compute from that ah there was one last bug and it's over here if we are choosing to include the string at index I then the total number of strings is guess going to be the total number of strings from the sub problem which is if we were to have this new M and N remaining and starting at I plus 1 but we have to include the string that we just added so we're going to say one plus the result of this sub problem if we actually do include the string if we don't include the string we don't have to put a plus one because we didn't include anything we just have to go and solve this sub problem I hope that clears it up but now let's run the code and as you can see it works and it's pretty efficient let me quickly show you the more efficient dynamic programming solution without recursion now if we were to code this up without recursion we could do so with three Loops because in this case our cache is going to be three dimensions we're going to follow very similar ideas we're going to use the same key as you can see over here we're using i m and n as the composite key for the string we are counting how many zeros and ones it has and then we're iterating through possible M and N values in this case M and N are once again going to whoops refer to how many zeros and how many ones we have remaining so we're going to use the count of the string to make sure we have enough to actually use this string and if we do have enough to use it then we're going to take the max of pretty much the same value that we used before 1 plus the sub problem DP now here instead of saying I play plus one we're doing I minus 1 because we're iterating through from left to right you could iterate in Reverse I'll show you that one in just a second but here we're iterating in the opposite direction so we're doing I minus one that's the sub problem so in this case I refers to we're allowed to use the string at index I and every previous string that's kind of like the sub problem in this case that's why we say I minus 1 when we look to solve a sub problem now if we're not allowed to use it then we just set it equal to the value at I minus 1 because yes we can't use the string at I at index I but we're allowed to use every previous string so we just take the max value from I minus 1 with the same M and N values and then we will return the value at the largest possible indices in this case actually I change the M and N to be Capital so then I can actually use these two as like iterators through our Loops but you can see otherwise this is pretty similar to the recursive solution the complicated part is pretty much just figuring out which direction to iterate through and also that here we need to start at zero instead of one the reason being in some cases we might decide to use zero occurrences of a character of a zero or a one we can choose to not include any if we want to but otherwise this is the iterative solution the time and space complexity is pretty much the same though now let me show you a way we can actually improve the space complexity and this is how we could do it you can see we are once again using a hash map the fact that this is a default deck just means that if we go out of bounds it's going to return a default value in this case an integer and the value is going to be zero which is exactly what we need in our case this is pretty similar except we are iterating in reverse order and the previous solution I actually showed you will not pass I think it gives time limit exceeded even though the time complexity is the same as the recursive one leak code is just kind of weird but this one will pass this iterative solution will pass on leak code because it's a bit more efficient not just because we're using less memory here you can see when we set a value we're setting it once again equal to the max but we're not using I as a key in our hash map and we are iterating through this in reverse order while the M and N values in reverse order because the way we build the grid and it's going to be hard to explain so let me go back to the Whiteboard real quick we know that our cache is three dimension so it's going to be hard to describe it visually but let's say that this is one of the layers of the three dimensions this is like our grid M by n this is for I equals one basically the first string and then we have another grid over here for I equals one the second string previously I showed us filling in the grid like this from top to bottom this is what I meant when I said top to bottom but suppose from this position sometimes we need to take our M value and subtract it so we have to look up from here if we want to fill in the value at this position we have to look above us sometimes we have to subtract from the N so we have to look to the left so we might have to look to the left or up or maybe even to the top left because if we use the current string then we have less zeros and less ones remaining to choose from so we have to possibly look in this direction when we look in that direction we never look at the same grid we never look at the same I value right now what we're doing is taking the I value and saying I minus 1. we're going to look in the previous grid and we're going to look at it going in the top left Direction now what I'm doing instead of having both of these grids in memory though I'm only keeping a single Grid in memory because I want to reduce the memory complexity from being n times m times s I'm changing it to now only be n times M so doing it this way if we fill this in going top to left and then when we get to here and we want to look in the top left but what we actually want to find is the original value that we stored up here but if we overwrote that we can't do that anymore so what we instead do is don't fill top to bottom we fill bottom to top so like this so now if we got to this position and looked at the top left we would find the original values we would never search bottom or to the right so we'd never even care what we have stored here we'd only look at the top left so that's why we're doing this in reverse order and lastly not only are we doing it in reverse order but here starting at M we're going to go up until the count minus one the number of zeros minus one and the reason we have the minus one here is just because in Python this last value is non-inclusive so we have to go value is non-inclusive so we have to go value is non-inclusive so we have to go one past that but the reason we're going up until M count is because we don't need to go to any values smaller than that because if we need three zeros for this current string why should we even consider any of the loop iterations where we have less than that why should we even consider any of the loop iterations where we only have zero zeros or maybe we only have two zeros but we need three of them so we're not even going to consider this iteration of the loop this is kind of a shortcut and this is what helps get this solution to pass on leak code so lastly I'll run this just to prove it to you that it does work and as you can see it does but the runtime is kind of random on late cut I don't really pay too much attention to it but if this was helpful please like And subscribe if you're preparing for coding interviews check out neat code.io coding interviews check out neat code.io coding interviews check out neat code.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Ones and Zeroes
ones-and-zeroes
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:** strs = \[ "10 ", "0001 ", "111001 ", "1 ", "0 "\], m = 5, n = 3 **Output:** 4 **Explanation:** The largest subset with at most 5 0's and 3 1's is { "10 ", "0001 ", "1 ", "0 "}, so the answer is 4. Other valid but smaller subsets include { "0001 ", "1 "} and { "10 ", "1 ", "0 "}. { "111001 "} is an invalid subset because it contains 4 1's, greater than the maximum of 3. **Example 2:** **Input:** strs = \[ "10 ", "0 ", "1 "\], m = 1, n = 1 **Output:** 2 **Explanation:** The largest subset is { "0 ", "1 "}, so the answer is 2. **Constraints:** * `1 <= strs.length <= 600` * `1 <= strs[i].length <= 100` * `strs[i]` consists only of digits `'0'` and `'1'`. * `1 <= m, n <= 100`
null
Array,String,Dynamic Programming
Medium
510,600,2261
1,344
hello and welcome back to the cracking fang youtube channel today we're going to be solving leap code problem 1344 angle between hands of a clock before we get into the problem i would just like to ask you to subscribe i have a goal of reaching 1 000 subscribers on my channel before the end of may and i need your help to get there so if you're enjoying the content and you like the videos that i'm making please subscribe to my channel and help me grow this is going to help me reach a broader audience and make more videos for you guys so you can get into fang as well that being said let's read the question prompt given two numbers hour and minutes return the smaller angle in degrees formed between the hour and the minute hand for example if we're given this hour 12 and minutes 30 so 12 30 we want to calculate the difference in degrees between the two hands so basically what is the difference here so what we need to do is we need to figure out what the degrees of the hour is and the degrees of the minutes is so the minutes is a little bit simpler because we don't have to deal with the fact that the hour hand is actually going to move relative to where um you know the minutes is right the hour hand will move as we can see it's halfway between 12 and 1 because we're halfway through the hour so that's going to be a little bit trickier so let's do the minutes first so minutes as we know is going to be whatever the minutes is so 30 and how many degrees are in a minute right so if there's 360 degrees in an hour then every minute and the 60 per hour so we expect 360 divided by 60 uh degrees per minute so this means that this calculation so we can really think of this as six so we can think of it as having the minute hand is going to have 180 degrees now for the hour hand so we'll just say m here the hour hand its degrees is going to be a little bit more complicated not only do we have to account for you know the base position of the hour we need to also account for how far to the next hour it is relative to the minute hand so the way that we're going to do this is we're going to calculate the base kind of degrees for the hour which is going to be the hour uh times so how many degrees are in an hour so we have 360 degrees per hour and then you know 12 hour markers uh per day right so sorry 360 per day and then we have 12 hour markers so we can think of this as really being 30 right oops you can't really see that uh so this upper portion here is 30. so we're really multiplying the hour times 30 plus then we need to account for the fact that the hour hand is actually going to be somewhere between the current hour and the next hour based on where the minute hand is so we just need to account for that by okay we have if we have 30 degrees per hour now we need to multiply it by how far it is between uh the next hour which is going to be you know the number of uh essentially minutes that have elapsed in this hour so we'll do minutes over 60 right because that's the amount of degrees that we're gonna have in that one um period so for this one in particular so we have the hour so it's going to be 12 so we have 12 times uh 30 plus uh what do we have here 12 times 30 times what is it uh 30 over 60 right so this is going to be what uh let's see 12 times 30 this is 360. plus 30 times basically one half so 15 so here we actually get 375 which doesn't really make sense right because right an hour only has 360 degrees well the reason that we get this is that you know when we get our solution we actually just need to take the difference between the i guess the hour uh degrees and the minute degrees but as you notice we can get you know negative numbers here or they can be in the wrong direction so what we need to do is we now need to take the difference between these two so we're going to say 375 minus 180 so this is going to be what um 195 right but this actually isn't the correct answer uh because it's too big right that would actually be this bigger half so what we need to do is we don't know which side we're actually calculating it for we could be on the wrong side we could be calculating the bigger side but remember we want the smaller angle right there's two angles that are formed here this big one and the small one but we don't know which one it is so our final answer is actually going to be the minimum of whatever the difference is so like 195 and then 365 minus 195. so we take the difference of 300 no not 365 sorry it's 360. uh let me undo that 360 minus whatever 195 is and we can see that this is actually going to be the smaller one so this will be our answer and that's what we're going to return right 165 here so that's how we get that answer so that's really the approach that we want to take what we want to do is first calculate the degrees for the minutes which is going to follow the formula of whatever the minutes is so this is the minutes that we were given times 360 divided by 60 which is six and we're going to get that degrees then we're going to calculate the hour which is going to be whatever the hour is times 360 divided by 12 which is 30 plus 30 which we just got here times the amount of minutes that have elapsed in the hour and that'll tell us how far in between the next hour it is and that will be our hour degrees then we take the difference between these two absolute value because it could be negative and then we want to return is the minimum between that value we just got and 360 minus it because again we don't know which angle we're going to be working with so that's the approach that we want to take the code is super simple it's literally four lines of code here so let's go to the code editor write this up it's going to take no time at all so i'll see you there and now remember that i said the lines of code for this is only going to be four so this is going to be super simple let's write the code so all we need is the minute degrees and the hour degrees so let's derive those so remember that the minute degrees is going to be equal to the number of minutes we have times the number of degrees for each minute so if there's 360 uh degrees in an hour and there's 60 minutes in an hour then 360 divided by 60 will tell us the number of degrees per minute and if we multiply by that by the minutes we'll get the minute degrees now for the hour degrees remember that it's a little bit more complex in that we need the base hour and then we need how far it is to the next hour right we need to figure out you know how far in between 12 and what it is relative to how far the hour hand is through the hour so to calculate the base hour we're going to say we're going to take the current hour and we're going to multiply it by 360 divided by 12 right because there's 12 positions for the hour and the clock and there's you know 360 degrees for one full rotation of the hour hand then we need to account for the fact that the hour hand is going to move uh part way to the next hour so we're going to do that by saying okay again there's 360 divided by 12 degrees in an hour but we need to figure out what fraction of it the next hour we're closer to so we need to multiply that so we can just rewrite this as 30 just to keep things tidy and we'll rewrite this i will just leave that for now and then we'll do minutes time divided by 60. so this is the ratio of how far the minute hand is to the next hour which will tell us how far our current hour hand is between the two hours so that will be our minute degrees and our degrees now remember that we need to calculate the difference between these two and since it can be negative we need to have the absolute value so we're going to say minute degrees minus our degrees and since we don't know um you know which side of the angle we actually took from this because we took the absolute value we now need to simply return whichever one is smaller our difference or 360 degrees minus our difference in the case that we took the larger half on accident because of this absolute value we won't actually know uh which half we took so that's why we need to return the minimum here so let us submit this make sure we haven't made any bugs and we can see that we solve the problem so what is the time and space complexity for this algorithm well the time complexity is going to be big o of one why because we don't need to make any sort of you know parsings through our hour and minutes all we're gonna have to do is just um do some simple calculations and this is gonna happen in constant time right this is just three constant time computations and that's it for the space again we just create some variables to hold these arithmetic results we're not creating any new data structures anything like that so it's also going to be big of one and big of one for the space so the time is bigger one space is big oven super simple this problem is really easy i'm not sure why it's medium i think it's just knowing how to operate um you know i guess a clock but you know if you get it's always good to know how to solve it anyway if you enjoyed this video please leave a like comment uh subscribe to the channel if there's any videos you'd like me to make please leave it in the comment section below i'll be happy to get back to you guys just tell me what you want to see and i'll make the videos otherwise have a nice day bye
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
303
today we're going to be solving lead code problem 303 range sum query and this one is immutable so given an integer array nums handle multiple queries of the following type so we have to calculate the sum of the elements of nums between indices left and right inclusive where we have left is less than equal to right so for our first example we have negative 2 0 three negative five two and negative one in our array so then we take the sum range from zero to two these three indices and then two to five and then zero to five and so then our output would just be null or just zero and then we have one negative one and then three respectively to each of those so this problem is a dynamic programming problem and the solution to this problem is pretty straightforward so we have to create some variable i'm going to call it acc for accumulate and that's going to just equal an array with 0 in it and then for num and nums we say self dot acc plus equals an array of self dot acc negative one plus num and then for the sum range all we have to do is just return acc rights plus one minus the self diac left okay so what we're doing here is we're creating an array acc for accumulate that stores the accumulated sum for nums such that accumulated left equals the nums zero with element plus and nums first element and so on and so forth in the initializer of num array then we just return in the sum range we just return acc of right plus 1 minus acc of left and the sum range and that will give us our answer as you can see this is a pretty decent solution and our time complexity is o of n and our space complexity is also o of n if you found this video informative please like and subscribe to the quant bear
Range Sum Query - Immutable
range-sum-query-immutable
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). **Example 1:** **Input** \[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\] \[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\] **Output** \[null, 1, -1, -3\] **Explanation** NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` * `0 <= left <= right < nums.length` * At most `104` calls will be made to `sumRange`.
null
Array,Design,Prefix Sum
Easy
304,307,325
874
hey everybody this is Larry this is November 28th in New York anyway uh I'm gonna do an extra problem just to give myself a little bit more of an exercise that I think I didn't um I think I didn't click on to do so I think I've done that one okay let's see and hopefully not a premium question so uh paid for premium if anyone wants to sponsor me for premium I have four more days to get that deal and then I'll do more problems not doing uh SQL here obviously again uh for good reason hopefully it makes sense um as you can see everything is very random because I am spending a lot of effort on randoming I don't think I've done all of them right so all the nine uh non-premium mediums so all the nine uh non-premium mediums so all the nine uh non-premium mediums but it's uh it's getting thin maybe I just need to I'm not doing more type for edit stuff uh because python is kind of weird I would say it's weird just I don't know all the constructs in Python mode diet floating um taking a while here though a minute of just RNG and so far no good I might just go down the list at some point maybe it is just one of those uh situations these days maybe I've done all the non-premium ones pretty much all the non-premium ones pretty much all the non-premium ones pretty much uh except for these I mean I could see problems that they're just not RNG me right so I don't know okay fine let's do at least three more ing's and then we'll just go down the list maybe uh this is the beginning of the end until someone uh gives me a premium oh there we go so that was actually the last one anyway okay so today's problem is 874 working robot simulation a vote button Infinity X5 Point starts at zero facing north it could turn what a weird thing oh I guess okay still awkward so you could turn that if you could turn right uh move forward K and then there can be obstacles weapons will stay okay so it seems like a simulation because you can only move K steps anyway so like there's no weirdness with respect to uh whatever and then we just take the maximum uh every step um I don't think that yeah it should be okay right so um let's see right what are we doing so basically um what are we looking at North I guess it doesn't really matter it is facing north but everything's symmetric anyway right so basically we have the way that I like to set it up is maybe I've set up Direction so the north is going to be I mean this is up to you but I'm going to choose minus X um and then if we turn left as long as you're consistent it should be fine um actually they tell you this but whatever we can ignore it doesn't really oh we don't we can because there are obstacles so we have to be very precise okay fine so North is going to be plus y fine so zero plus one um and then what I want to do is just rotate to the right so rotate to the right is going to be rest right or Yeast which side is used in which side is West um okay I think it's West so West is negative X um and then South is you know obviously oops and then lastly but not uh not leastly uh the yeast why is there one extra brand okay so then now we have current direction is you go to zero for North and then we have our current x y but and that's pretty much and then maybe uh max distance right to go to zero um okay and then let's process the obstacles first into a set so we could look it up because I'm lazy um yeah so they just called ops as you go to set and yeah okay and then now we just have to simulate um yeah sorry guys so yeah so then now just for I don't know C in commands um I think there's rules so if C is equal to negative two then we turn left so current is equal to current plus three mod four or something right um and then if C is equal to negative one then we move to the right uh and then else it'll be from there's no we don't have to um okay yeah I just wasn't sure if we have to validate that's all um and then yeah and then we just in range of uh C I suppose if it's one it does one okay fine yeah this D doesn't isn't necessarily have just confusing myself uh okay then yeah then we walk forward so NX and Y as you go to X Plus DX uh um that's why dxty as you go to directions of current uh X Plus DX y plus d y and the way the reason why I write it like this is so that we can check for the obstacles right so if NX and Y in obstacles there are Ops in my case oops um then we can break I mean we can kind of in theory we just do nothing and continue but in this command in this for loop it's just going to keep on running into it so we can break otherwise X Y is equal to NX and Y I think that's pretty much it um except for now we have to update the max distance so max distance is equal to Max of Max distance x times X Plus y times Y and I know that we have the square rooted but oh I was going to say I actually didn't realize this but the reason why I like to keep it this way so that we could square wood later and we don't have to worry about floating point but apparently they wanted the square anyway so easier for us um let's kind of give it a spin I have the wrong answer so that's kind of sad uh what's good for this one hmm maybe I'm not hitting the obstacles correctly that's probably why um okay because it was going so it's saying it goes from zero to zero four turn right go four but it stops at two wait stops at one right so it starts at 1 4 goes to the right and okay um I mean the good point about this is we can print it out at the end of every frame so let's kind of see what it's trying to do um maybe my set thing is weird huh that's awkward so after the first move it goes to 2A did I mess up my directions oh so I could take this out we don't have to keep one whatever but let's do that those cars are getting sloppy there but so silver one is X Y to begin with this should be zero right hmm huh that is fascinating so 0 1 X Y is 2 4 to begin with why is it two foot oh man I am being dumb because I use X Y here that is a very silly mistake okay fine uh this is why you should not Shadow kids Shadow variables makes people sad okay I mean it may still get you one but at least hopefully it'll be wrong for the right reason uh okay let's point it out again though because apparently I'm still well um okay so zero one today it goes to zero four okay turns right um did I do the science one turns right as negative one and right is rest right it is which side is yeast which size breast they should tell you [Laughter] [Laughter] [Laughter] maybe I'm just being dumb uh huh did I mess it up maybe I just messed it up okay let's try it this way negative two is turned left right I mean I guess I just yeah okay and I messed that up because man which side is these let me I'm going to try Googling yeast is he still left away in East Village oh man I am I did confuse myself wow I confused which size you sandwich size West I'm just like looking up maps of yeast Village and I'm like oh yeah of course these were interested away wow it's just one of those days I guess um okay luckily this isn't a contest but that would be kind of sad of divorce but yeah um cool uh kind of a long video because of uh all the detours but um this is going to be linear time linear space uh yeah uh well it depends on what you mean by linear as well um the space comes from the if you want to be more specific it's going to be of O we're always the size of the obstacles and okay let me just write the time is uh space is going to be of oh well oh is the obstacles and in time of course it's going to be uh C plus o where C is commands right um and of course that's only execute 10 times you can maybe add an extra constraint on um how many steps per command if you want to do that as a variable but you know yeah you can play around with that in terms of analysis but yeah that's what I have for this one let me know what you think um yeah that's it stay good stay healthy took a mental health I'll see y'all later and take care bye
Walking Robot Simulation
backspace-string-compare
A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`: * `-2`: Turn left `90` degrees. * `-1`: Turn right `90` degrees. * `1 <= k <= 9`: Move forward `k` units, one unit at a time. Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command. Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_. **Note:** * North means +Y direction. * East means +X direction. * South means -Y direction. * West means -X direction. **Example 1:** **Input:** commands = \[4,-1,3\], obstacles = \[\] **Output:** 25 **Explanation:** The robot starts at (0, 0): 1. Move north 4 units to (0, 4). 2. Turn right. 3. Move east 3 units to (3, 4). The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away. **Example 2:** **Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\] **Output:** 65 **Explanation:** The robot starts at (0, 0): 1. Move north 4 units to (0, 4). 2. Turn right. 3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4). 4. Turn left. 5. Move north 4 units to (1, 8). The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away. **Example 3:** **Input:** commands = \[6,-1,-1,6\], obstacles = \[\] **Output:** 36 **Explanation:** The robot starts at (0, 0): 1. Move north 6 units to (0, 6). 2. Turn right. 3. Turn right. 4. Move south 6 units to (0, 0). The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away. **Constraints:** * `1 <= commands.length <= 104` * `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`. * `0 <= obstacles.length <= 104` * `-3 * 104 <= xi, yi <= 3 * 104` * The answer is guaranteed to be less than `231`.
null
Two Pointers,String,Stack,Simulation
Easy
1720
205
hey everyone today we'll be doing another leaked code 205 isomorphic strings and easy one given two strings essentially determine if they are isomorphic two string s and t are isomorphic if the character in s can be replaced to get t all occurrences of a character must be replaced with another character while preserving the order of the characters no two characters may map to the same characters a character so this is the key point here no two characters may have two same characters no two characters we have to stream the same character just keep in mind but our character may map to itself with okay so we are given by mapping the means you are going to use a hashmap dictionary hashtable you can say and so we'll be making two hash maps and what we will be doing is for the hashmap of let me explain like for egg and also we have add so we'll be making two hash maps and for the hash map one which will be of the egg s this is the s string egg so egg itself will be holding the keys and add will be the values so what does it mean the hash map will look like this g is holding d and g is again holding d this is it and now if we make another hash map which will be just for our second string the things will be opposite add will be the keys and egg will be the character in egg will be the values so a will be holding e and d will be holding g and d will again hold g so this will return true because everything is fine everything in this whole situation is fine uh we are passing our base conditions like uh no two characters may have to send the same character and a character member will say the main problem is this no two characters they map to the same character this is just the same now it were if it was like this would have been an error this is the same thing like this will return true like you can say in the example one but now if we see the example two who and bar if you understand what how the things are working here you probably guess why is this returning false so we'll be making another map for i will just code it down i think you guys know what is happening here is just o will be holding a and o will be holding r and p will be holding f a will be holding it will be holding o and r will be holding o so here we are failing the base condition like two characters may not map to the same character like this so that's why it is returning false so we have to check if the character is present in our map and the value of that character is equal to the value of the character in the correspondence you can say parallel you can just parallel is more understandable uh the parallel character so that's it now just make hash maps and do all the coding stuff so we'll be making a map one mapman will be mapped of s which will be the s string and a map2 making a dictionary this is how you make a map for i in range of you can take one of these strings and put them in range their lengths basically because the length will be the same so now we have to check if but before checking we will make some variables for our own understanding a and b it will be a holding address oh the value at index s and b will be 40 so if a is present in our map one and also map one at a shall not be equal to b so that basically we are just checking that if a is in a map obviously if a is in a map then obviously then we are going to check its value what it is and if it is not equal to b then we shall just return false in that case because it should be equal to b so now we will do the same for map second and map two for map to be and just doing the same thing here so here is one after doing this we can just return false because we have found a character which is two characters which are mapping to the same correct to the same characters so just return false and if not we will just do this like swapping you can not swapping just like putting taking the value from a b and putting it back to the hashmap of one and taking the value from hashmap to and putting that uh one two yes to two obviously two so map two will be b map to the index b shall be equal to a and if we are done with all of this and we didn't return false it means there are no you can say two characters that are mapping to the same character to the yes two characters mapping to the same character and that's it this is just fine i think and we will return true this works and that's it
Isomorphic Strings
isomorphic-strings
Given two strings `s` and `t`, _determine if they are isomorphic_. Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. **Example 1:** **Input:** s = "egg", t = "add" **Output:** true **Example 2:** **Input:** s = "foo", t = "bar" **Output:** false **Example 3:** **Input:** s = "paper", t = "title" **Output:** true **Constraints:** * `1 <= s.length <= 5 * 104` * `t.length == s.length` * `s` and `t` consist of any valid ascii character.
null
Hash Table,String
Easy
290
103
hello and welcome to another one of my lead code videos in this one we'll do lead code 103 binary tree zigzag level order traversal this is today's daily challenge so basically we're given the root of a binary tree and we need to return the zigzag level order traversal so that means that we go first from left to right and then in the next level we go from right to left and then the next level we go from left to right and so on right so in this case 3 29 15 7. so we have to return the output as a list of list so what will be our approach to solve this problem basically we will just use breadth first search because that's how you do a level order traversal right so we'll first add three into our q and then look at what are the all of the children of everything in the queue so we'll get 9 and 20. and then we look at the next level what are the children of everything in the queue so it will be 15 and 7 and so on right but then as we do that we'll have to keep track of the direction whether we're going left to right or right to left and accordingly add things in the queue so that will be our overall approach let's just go ahead and code it and hopefully you'll see how it looks like so we'll start off with our list of integers which is the result and that will initialize to a new arraylist and ultimately that's what we'll return so there's our results list and then what we'll do is we'll initialize a linked list of the current level and I'll use a linked list instead of a queue because it'll make it a bit easier for us to deal with the directions right so we'll keep track of our current level as a new linked list and then we'll just do the standard BFS template which is we keep looping while current level is not empty right and inside that as well we'll have another loop that says while current level is not empty so we'll take out everything from the current level and add it to see if there's a Next Level right and at the end we'll say current level equals Next Level right so this will keep going until there are no more levels right so the outer loop checks if there are still more levels and the inner loop checks if you know during the current level basically to compute the next level and obviously we need to initialize our next level over here so let me just do that real quick and so that's our next level and at the end we'll set current level equals Next Level so that's our BFS template now let's go ahead and write the code for this so initially we'll add our current uh node which is three or the root to the linked list right and sorry this should not be a integer basically this will be a tree node so let me just adjust all of those real quick and so yeah initially we'll have the root as the current level and we also need a Boolean to know whether we're going left to right for the next level or right to left right so we'll say is left to right equals false initially because the root goes left to right so the next level has to go right to left right and so now let's pull our current node from the tree or sorry from the cube so we've captured our current node and here we're just going to add you know compute the things for the current level so if you notice the result is a list of integers so at each level we'll have to compute that list so I'm just going to say integing just a normal list of integers which is basically result for level is a new array list right and at the end what we'll do is we'll say result dot add result for level right so at every time we drain the queue we'll compute this result for level and we'll add it to our overall result and here what we'll do is we'll just say result for level dot add node .vel right because whatever we pull from .vel right because whatever we pull from .vel right because whatever we pull from the current level we'll add it to the result and we'll just make sure to put things in the right order when we populate our next level so that way you know when the it goes through the result for the next level it's already in order right so that we'll add that logic over here but there's just one more structural thing we need to do is basically at the end of each loop after draining the current level we have to flip this flag right so we'll say is left to right equal to not is left right so that will just flip the flag right so just to summarize the structure we have a queue for the current level and here we're going through the BFS while there are still more levels and each time what we're draining the current level we're populating the result and Computing Next Level which we'll do in a second and after draining the current level we're flipping or left to right we're appending the result for the current level to the result and we're setting curve level equals Next Level so it can check if there are still more levels right and at the end we return results so that's structurally how the code looks like and so now what we just need to do is populate our next level based on the right order right so we will have two branches here right if is left to right and if it's not left or right so if it is left to right what we want to do is we're going from left sorry let's populate the other Branch first so if we're not left to right that means the nodes in the previous level are being taken out as in order from left to right but then as within their children we have to add them going from right to left and let's just imagine that this level was processed from left to right so in the else case what we want to do is when we pop the children we want to add them to a list in reverse order right so we add the left at the right at the left at the right but in reverse order right so what we'll do is nextlevel dot add first node.left node.left node.left and the same thing for node.right and the same thing for node.right and the same thing for node.right and obviously we only do this if node.left obviously we only do this if node.left obviously we only do this if node.left is not null right and sorry the next one is node.right so and sorry the next one is node.right so and sorry the next one is node.right so the next one is if node.write is not the next one is if node.write is not the next one is if node.write is not null then we'll add Next Level that add first node.right and so what add first node.right and so what add first node.right and so what add first is going to do is going to say okay every time we add a node make it the first so that way the list will be from the next list will be from left to right and so then if is left to right is true meaning the next list has to go from left to right what we'll do is that means the elements are being popped from right to left right so what we want to do is make them it from The Next Level from left to right so what we'll do is again we'll insert the right one first and then the left one and then we'll do the same ad first technique so it the list is basically appeared in reverse order and this is why we have to use a linked list because that will make sure that we're adding you know it will give us this capability to add first so that makes it easier to um to add things to the next level so that will basically do it let's run it and see how this does all right there's just one base case we need to take care of is basically if the root isn't also over here we'll also just say if root is not null only then we'll add the root to our current level and you know if there's nothing in the current level it will just skip out of this and return results so that check should be enough over there all right accept it let's submit perfect 100 solution thanks so much for watching I'll see you in the next one cheers
Binary Tree Zigzag Level Order Traversal
binary-tree-zigzag-level-order-traversal
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[20,9\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100`
null
Tree,Breadth-First Search,Binary Tree
Medium
102
169
if you're Jeff starting your journey towards Tech interviews trust me this problem is really important at it is one of the facial is that it navigates beautifully how you start to understand the problem and then make your way all the way towards an efficient approach why is that true let us try to find it out Hello friends welcome back to my channel and yes I've got some cold but anyways first of all what we're gonna do is we will understand the problem statement and we will look at some sample test cases going forward we will try to solve this problem using a Brute Force approach then we will start optimizing it we'll optimize it for time and when we will optimize it for space ultimately you will also do a dry run of the code so that you understand how all of this actually works in action without further Ado let's get started first of all let's make sure that we are understanding the problem statement correctly in this problem you are given an array of integers and you have to find the majority element so what is the majority element a majority element is one that occurs more than n by two times where n is the total number of elements present in the array right so if an already have 10 elements then the majority element will be one that occurs more than 10 by 2 that is more than 5 times right to understand it better let us look at a sample test case in our first test is you can see that the value of n is 3 right because it has three elements so therefore n by 2 will be equal to 1.5 and thus you need to be equal to 1.5 and thus you need to be equal to 1.5 and thus you need to find the majority element that occurs two times or more than two times right so when you look at this array you can see that the element 3 occurs two times correct so for a test case number one three will be your answer 3 is the majority element correct similarly let us look at our second test case in our second test case once again what we do is you find the value of n that will be 7 so n by 2 will be 3.5 that will be 7 so n by 2 will be 3.5 that will be 7 so n by 2 will be 3.5 so you need to look for a majority element that occurs more than four times or just 4 right so when you look at this array you can see that the element 2 is occurring four times and hence 2 is the majority element so for a test case number two will be your answer now for this problem it is guaranteed that the array will have a majority element there could be some other problem or some other scenarios where the array may or may not have a majority element but that depends upon the problem in this problem specifically there will be a majority element and that is guaranteed so 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 and see how you're gonna approach this problem as I said earlier this problem is interviews favorite because it helps the interview to judge how the candidate is thinking so when you're given this problem and you have said that okay now try to solve this problem what do you do first of all as a good developer you will always try to come up with a Brute Force solution because that can guarantee you if a solution to this problem even exists so what you're going to do is you say that okay I'll do one thing I'll say that okay how many times can I find the element one so you will travel through the array and you can say that okay one two you found the element one two times right and then you're gonna look for elements two you find the element to four times right and then at the last you're gonna look for element three how many times do you find the element you only find it one time right next you need to see it say that okay the size of the area so n by te will be equal to 3.5 and so n by te will be equal to 3.5 and so n by te will be equal to 3.5 and hence I need to find some majority element that occurs four or more times and voila you can find this over here right you can see that okay 2 is my majority element so you were able to arrive at a solution right and that's perfect but then the interview will say okay you are taking a lot of time and why is that so because to find out the frequency of each of this element you are traversing through the array again and again right first of all you Traverse the array for element one then you Traverse the alloy for element two and then you Traverse the array for element three so in this case your time complexity is very high your interviewer will say okay I need a better solution so what can you do about it and once again you have the same problem and you have a fresh sheet of paper in front of you and you are asked okay optimize the solution correct so when it comes to array-based problems and comes to array-based problems and comes to array-based problems and integers always try to sort your array because 14 can really help you to arrive at an answer and think about it for a second suppose you have this array in front of you right and you've tried to sort this array what will happen when you sort it all the similar elements will come together right so all the ones will get collected together all the tools will get collected together and all the threes will get collected together right and whatever will be the majority element in the array you know that the majority element is gonna occupy a size greater than half the size right so if your error size is 10 then there will be more than five elements that will be the majority element right if your array size is 20 then 10 of the elements will be the same right so what you can say is that once your array is sorted all the majority elements will lie somewhere in the array right it they could all lie in the beginning they could all lie at the very end they could all lie somewhere in the middle or they can lie somewhere else right anywhere in between but the major point that you have to notice is that the majority element it will always pass through the center of the array right and that is because the majority element occurs more than n by two times and you cannot have a combination where the majority element will not be at the center so this tells me right if I sort the array and if I look at the middle element that will be my majority element right so that is exactly what we do we take this array and then we sort it what happens then you get a faulted array right and the next step is simply look at the middle element of the array and this element will be the majority element so you can safely say that for this particular problem 2 will be a majority element and this is the reason because it is guaranteed that the majority element will pass through the center right so this should make your interviewer a little happy you did not iterate through the array again and again you just sorted it once and returned the middle element right but when it comes to sorting what is the best time complexity that you can have a Time complexity of order n log n right that is the fastest one quick font unless there are special cases correct so your interview say that okay I'm still not satisfied I need an even better approach what can you do about it so you see why this problem is interesting it will keep on poking you again and again to come up with a better approach and now you'll think okay what can I do next so once again you would refresh your mind and you have the same problem and a blank sheet of paper the ideas are endless what can you do well you tried farting the array right but we did not try okay what if I can take a help of an additional data structure maybe that can help me with time so this is one approach what you can do is you can take a help of a hash table right so this hash table will store all the numbers in your keys column and all the frequencies in the value column so what we're going to do in this case is we will start iterating through the array from the beginning I see one number I see two so I put 2 in my hash table and I put its frequency as one now move ahead the next element I see is 2 again check your hash table two if already perfect right so if an element is present just increment its frequency correct now move on you see element one check your hash table this element does not exist so you will add this number and put its frequency as 1. similarly you will keep on going along you will see three is not present over here so I am going to add 3 and put its frequency F1 next I get a one again one is present in the table so I will update its frequency now I get a 2 again check its frequency and update it the last element is 2 again check its frequency and ultimately update it now in just one iteration you were able to find out the frequency of each element right and you already know that the majority element will have a frequency of 4 or more correct so just scan through your hash table once and see that okay two will be your majority element you were able to optimize your code correct in just one scan you were able to determine the majority element correct but this time what did you do you took help of an additional data structure right and that means you took some extra space this is where your interview will catch you again and he will say okay I do not want you to use any extra space What do you do now so this is why I keep saying that this problem is really interesting and the last solution that I'm going to offer you will really blow your mind it is so simple and you will say that hey why didn't I think of it before so what do you do about it when it comes to majority what comes to your mind well you can say that voting comes to your mind right because based on number of votes a certain candidate can get elected right if there are a thousand people and the candidate gets more than 500 votes they are a majority and they form a government so we can try to apply the same voting algorithm on this problem as well so I have the same array with me and then I will try to determine who is the majority and how many votes they have so starting off with my first candidate someone comes and they vote for candidate too so what I can say is that okay right now two has a majority and they have one vote correct next one more person comes and they vote for two so what I'm saying gonna say is okay the number of votes for two increase by one so I do a plus one over here right now moving along a third person comes and they vote for one so to laugh double right so I'm gonna reduce this count but we do not update the majority element because it could still be possible that 2 might win again now move ahead the next person votes for three so two lost his vote again and if total number of votes again became zero so now you are in a dilemma okay who has the majority do you remember how in the beginning we chose two as a majority candidate so this time it could be possible that okay three could be a possible candidate right and three will have one vote right because he just got the vote now move ahead a next candidate came in again and they voted for one so once again three lost a vote their votes became zero and it could be possible that one is a new candidate right he got one vote correct based on a similar idea just go ahead one more candidate comes and they vote for two again so check the vote this vote reduces to zero and now no one have a majority again let us say that 2 will be the majority so I'm gonna choose 2 as a majority element and their vote counts get updated to 1. move ahead for one last time and you feed two again so what does that mean the number of votes of 2 increased by one and we have reached the very end everyone has casted their votes correct and what do you see over here you see that 2 is the majority element in the array correct so you see how in just one iteration we did not take any extra space and we were able to determine the majority element in the array now let us quickly do a drawing of the code and see how it works in action on the left side of your screen you have the actual code to implement the solution and on the right I have this sample array that is passed in as an input parameter to the function majority element oh and by the way this complete code and its test cases are also available in my GitHub profile you can find the link in the description below moving ahead with a dry iron what is the first thing that we do first of all we choose a majority element and we say that okay let the first element be the majority element and I give them one vote right now as the next step what we'll do is we will start a for Loop that will start from the first element and go all the way up to the end right so we will get the vote of each person correct so now in this Loop what do we do if the vote counts becomes 0 at any point we update our majority element and we increase the vote count back to 1 right and if our current number equals the majority element we will increase the number of votes else what we do if someone casted a vote for the other person we decrease their vote count right so this and at the very end whatever will be the majority value that will be your majority element in the array right note that this part of the code is doing exactly what I just explained you a few seconds ago right so the time complexity of this solution is order of n because we iterate through the array only once and the space complexity of the solution is order of 1 because we do not take any extra space to arrive at a solution I hope I was able to simplify the problem and its solution for you as per my final thoughts I just want to say that I know this problem is not very difficult and after some iterations you will be able to arrive at an efficient solution and even if you practice on lead code you will ultimately get an accepted Foundation but the interesting part and the Beautiful part about this problem is there are so many ways to solve it and I would highly recommend you to go on and explore all of them because that will segue and open a gateway to you to attack more problems and it will show you ways how you can look at new problems so when you are approaching such problems try to come up with new Solutions try to optimize for time as much as you can try to optimize for your space as much as you can because these problems are not very complex they are very simple right so it kind of helps you to widen your brain and your thinking power so always watch out what other problems did you find that can be solved in a so many number of ways while going through this video did you face any problems tell me everything in the comments section below and I would love to discuss all of them with you would be also glad to know that a text-based explanation risk problem is text-based explanation risk problem is text-based explanation risk problem is available on the website study a pretty handy website a pretty handy website a pretty handy website for your programming needs as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what problems do you want me to follow next until then see ya
Majority Element
majority-element
Given an array `nums` of size `n`, return _the majority element_. The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array. **Example 1:** **Input:** nums = \[3,2,3\] **Output:** 3 **Example 2:** **Input:** nums = \[2,2,1,1,1,2,2\] **Output:** 2 **Constraints:** * `n == nums.length` * `1 <= n <= 5 * 104` * `-109 <= nums[i] <= 109` **Follow-up:** Could you solve the problem in linear time and in `O(1)` space?
null
Array,Hash Table,Divide and Conquer,Sorting,Counting
Easy
229,1102
1,207
hello friends today we gonne discuss this question founded code one 2:07 this question founded code one 2:07 this question founded code one 2:07 unique number of occurrences this is an easy question instead start you're given an array of integers ARR I have to write a function that returns true if and only if the number of occurrence of each value in the array is unique it means that as you can see in this example one occur three times two occurs two times and three occurs one time the occurrence of each number is dooty then only after return true okay so what we can't do this as you can see this is the original edit I written out all the numbers and it's occurrences so what we can do it we make a map I make a map M in which each number corresponding corresponds to its occurrence then I also made a map called B and then in that I check whether each occurrence is unique or not a simple logic would face it so what we have done here is you have to first make the first map to store the values and since then if we find any take any value in the array we just store it in the map of M as you can see in here then I and make another map to check if each element has unique event so what we can do is we just iterate over the stored values in the map m and check whether each value is like unique or not how you can check it if you just in count one value encounter when value like if we encounter one in the map one we just if you have not seen it then we just put it in the map and if you have see it returns false and if each value is unique we just did we just put all values in this map and we just I come out of this tube and you turn through I hope you understand this logic if you have any problem mention all in the comment box I applied to all the comments thank you for watching this video and I will see the next week thank you
Unique Number of Occurrences
delete-nodes-and-return-forest
Given an array of integers `arr`, return `true` _if the number of occurrences of each value in the array is **unique** or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[1,2,2,1,1,3\] **Output:** true **Explanation:** The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. **Example 2:** **Input:** arr = \[1,2\] **Output:** false **Example 3:** **Input:** arr = \[-3,0,1,-3,1,1,1,-3,10,0\] **Output:** true **Constraints:** * `1 <= arr.length <= 1000` * `-1000 <= arr[i] <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
2175
140
Hai Hello Guys Welcome Back There Devotion In This Video Will See The Vote Back To Problem Swiss Roll Absolutely Number One 409 The Requested For Watching This Problem Is To Watch Videos One Is The Problem And Explain The Cockroach Video Solving Problems Unit-2 Such Remedy Unit-2 Such Remedy Unit-2 Such Remedy Try Play List Play Video Problem Dictionary Subscribe Very Well Written All Possible Sentences In The Budding Dictionary Also Reduce Multiple Times In The Segmentation So Let's Fuel And Inverter Virver Dictionary Subscribe Request To All Possible Efforts And Different Words Will Be In Between The subscribe to The Amazing Dictionary valid tense which is formed by segmentation of this interest in no way can form no The sentence as well as a partition in between December and January will send you a sentence with multiple times in this is not needed to solve This problem was already discussed in the video problem only partition and the given dictionary will give you want to live in are you can make the partition and any point but between any two characters you can create partition here and will see the first word you and You will regret for the but you will only person speed it 9999999999 this is the thanks partition so let's create partition in between 10 first words not present at the event and again is not valid and subscribe to that no In this pain is considered it is not a petition in the present in the world against partition in between their goals painting competition subscribe The Channel and subscribe the Video then subscribe to the Page if you liked The Video झाल Returned to Swadesh Mein Bi Mein Olive Oil झाल Returned to Swadesh Mein Bi Mein Olive Oil झाल Returned to Swadesh Mein Bi Mein Olive Oil Partition Display in Detail A Video Endeavor's Return to the World Need Not Arrested in Rape Cases Problem Subscribe Now Your Data Structure for Watching the Validity of Its Present in the Best Possible They are always Sentence Example Cats and Dogs Dog Show is from Lab Cat and Dog Saunf How to Make Diwali Petition Knowledge is Deficit Between There are a few NCERTs are not valid for moving from left to right subscribe The Channel Please subscribe and subscribe the Channel Please Noida And Deposit Will Never Create Partition On The Left Side And Was The First Politician From Left To Right The World Akhbar The Indian Partition In Between When You Can Create Partition subscribe The Channel and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the Page and no I will recover back to 10 condition dedicated to partition between India and I can create any modifications to the right of every true Indian homes and did not valid word against York between you and did not valid in The Chapter Note Send Your Dog Is Not A Valid subscribe to the Page if you liked The Video then subscribe to the Page China's Cats And Will Go Tow Schedule See The World And Value Must Be Greater Than Soon Like This Video Comment Subscribe Share Like Share and Subscribe Partition Middle-aged Called a Friend on Thursday I'll Keep Adding Spaces Whenever a Big Question Call No Verification Call Divert Raees Ahmed Partition Avoid and Home 9 And Did Not Valid And You and Your Mother Carried You for 9 Subscribe Sentences and Provident Twenty -20 Values ​​Where I Have Intervention Values ​​Where I Have Intervention Values ​​Where I Have Intervention World And Value All 240 Se Z World And Indicators Effective Video give And Contented And The Giver And 12345 [ 12345 [ 12345 Withdrawal A Soap Is You Already Know How To Implement Destroy Evidence Was My Video And usage examples for we will not be spared them know what is the time complexity building destroy what is the order of total number of characters in the total number of the characters of wave the great indian laughter number to the length of the So in the worst case How Many Politicians Can You Read This Book Example Like Share And That Dictionary Apps 1114 subscribe The Amazing 1000's Not Only Single Again A Sensitive Were Not At Least One Is The Answer Is The Length Of Resident Evil Points 95 Bhind Saunf Bal Se Dam Minus One Capsule Partition Points Partition Point Will Have Two Choices But To Enter And To Not Include Total Number Of Items Which Can Be Made To Minus One To Three Do Subscribe Due to which Partition subscribe The Channel and subscribe the Channel Please subscribe and subscribe the Channel Tomorrow Morning Tried All Possible Combinations with the 251 More Remove This Point Two Three Idiots and Total Time Complexity of the World Channel Subscribe My Video Do Subscribe must subscribe here all the same will eliminate them in this program will only two functions special award function program with no problem give the validity subscribe channel subscribe search subscribe and subscribe the ke din hai bill record se absolut 10 years function to solvent and avoid the rate of the ring starting from withdraw from plus one will be sending this world and answers and share thank you for watching my video and once you get all the politicians and your family will go to the position of The Position Chest Size Dekh Chali You Have Petition That You Are Madea Valid Politicians Know Your Success Fully Segmented This Entering Into A Writ Petition Restored And Also In The Answer Is Very Mostly In The Subscribe Sentence Will Be Able To Understand this video please like subscribe and
Word Break II
word-break-ii
Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "catsanddog ", wordDict = \[ "cat ", "cats ", "and ", "sand ", "dog "\] **Output:** \[ "cats and dog ", "cat sand dog "\] **Example 2:** **Input:** s = "pineapplepenapple ", wordDict = \[ "apple ", "pen ", "applepen ", "pine ", "pineapple "\] **Output:** \[ "pine apple pen apple ", "pineapple pen apple ", "pine applepen apple "\] **Explanation:** Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** \[\] **Constraints:** * `1 <= s.length <= 20` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 10` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**. * Input is generated in a way that the length of the answer doesn't exceed 105.
null
Hash Table,String,Dynamic Programming,Backtracking,Trie,Memoization
Hard
139,472
48
yo what is up youtubers today i'm going to be going over rotate image it's a medium leak code problem has to do with arrays it's been asked by microsoft apple and amazon please check out my channel and subscribe if you haven't already i post videos basically every day about recode so now let's get to it teaches you a lot about how to manipulate arrays so it's really i think it's really important to know this problem um i could see it being asked an interview question i've heard it's been asked before so let's jump right into it you're given an n by n 2d matrix so that means the rows and the columns are going to be equal um that makes it a lot easier it could be m-by-n where they're different be m-by-n where they're different be m-by-n where they're different which is actually another problem that i will get to in the future so we just need to rotate the image by 90 degrees clockwise so they just want us to basically pick it up and rotate it so one two three will be on the right and um the column the first column will be on top so it's like just imagine picking it up and switching it right here as you can see right here um and so yeah they're end by end so there's four here four columns four rows three columns three rows it's always going to be the same so that makes it easier i actually have all the code written i need to clear that and so the logic behind this is a great one to whiteboard i drew it out the logic here is you got a you don't actually want to like there's not an easy way to as far as i'm aware to just like you can't really just like pick it up and turn it you have to turn them oh and the other thing is we have to rotate the image in place so they want us to not create another array we have to change it inside the array so that means we're going to have to use temp variables to keep reference of previous variables that we're going to change it's similar to like swapping when we swap two variables we're gonna have to basically do that um so the one thing to notice is that um the row is down here so if we first transpose it i think this is probably the hardest part the logic to realize is if you transpose it which means if you switch the so if you transpose it you're basically taking um you're basically rotating it to the left um so this row becomes this column um you're just swapping the rows and the columns and you're going through the whole thing so you see uh as you can see this the last column becomes the last row that's transposed now how close is this to um this well if you look here we have oh sorry it's my video is in the way there you we have 147 on top if we transpose it now if we reverse it 741 it matches it's just the transpose is reversed of the um the rotated matrix basically so we need to transpose it and then reverse it so now we just need to write code to do that so let's go ahead and jump right into it um i'm going to create a temp variable and uh i'll do no i'll name it and so into end this we're going to grab the length so matrix dot length um so because it's m by n we can just do matrix that length because they're going to be the same if we needed m by n we would have to do n is matrix that length m is matrix.length zero m is matrix.length zero m is matrix.length zero it would be like the zero how you grab it for a 2d matrix 0 and then blank um so yeah so and then we just need to transpose it i've done a video on this before so we're going to do a net 2 nested for a nested for loop i guess so for instance i equals zero whoops i less than n we're gonna loop through all the rows i plus and then we're gonna do j same thing um actually so we're i believe it's j equals i because we are um uh we have to once we let me show you on the board once we swap this row um we're going to so we swap this one i is one here once we get to i equal or i equals zero i'm sorry because it's zeroth index once we get to i equals one we are only swapping these two we're no longer doing the four's already been swapped so um j is going to be equal to i we don't need to do j equals zero we've already done that in when i is one so that's why we're doing that hopefully that makes sense um that's a little bit harder concept to pick up but you just gotta think about it logically draw it out picture it in your head however you need to figure out how to do that so temp is let's set i'm sure you guys have swapped variables before so let's set um temp equal to you could do either i j or j i it doesn't matter what order you do it but when you're swapping variables you do so now we're going to change we're storing matrix i j and temp so now we can change matrix i j we can update it when we're transposing it and we still have the original value in temp so just remember it goes in order so i'll show you what i mean by that so we're setting it equal to matrix ji we're just swapping the rows and columns and then matrix j i we still have that original value or yeah it's still the original value so we need to update it to temp so what i mean by is they go in order is first you um store matrix age i intend and then you change matrix i j to make j i and then matrix you update matrix j i so it's like i j i that's what i was trying to explain that's how i think about it and um oh i'm still in the for loop so that was transpose and so obviously that's oven squared it's two for loops it's pretty simple okay so now we just need to um reverse the rows so um let me reverse rows so how we're going to do this is um the biggest thing we're going to take basically two pointers we just need to swap this one with this one um so we're gonna swap i which is we're gonna swap i j this is i j with um how do we get to the last one well you take the length which is so n equals three this is the second index so you would think well three minus one yeah that works for this scenario but imagine we had one two three four five this is the fourth index third index zero one two yeah that works for um the last index only we need to um so if n is five n equals five minus one gets us four we third well in this case we're still swapping it with this one so j equals one so we get n minus 1 minus j so 5 minus 1 equals 3 which is the index we want to swap so it's just n minus 1 minus j hopefully that makes sense i don't know how else to explain that um so yeah let's code it out i equals zero i less than n i plus and so if you see here we're only i'm gonna draw i did a lot of drawing up here so i'm gonna do it on this one we're only swapping this in this we're doing one swap um per row so we're in a row we're doing one swap how do we do that we do so j while j is less than n divided by two n equals three so j less than 3 divided by 2 equals 1.5 less than 3 divided by 2 equals 1.5 less than 3 divided by 2 equals 1.5 as you know in coding it rounds down so it's going to be while j is less than one we're only doing one swap so it's only going to execute once so that is going to be for our second for loop equals zero and j less than n divided by two and j plus okay so now we just need to swap them let's store it in temp so matrix equals matrix i and j matrix i the j equals so now we need to we're not um we're staying in the same row so it's still i uh you don't want to swap it with uh the other column so it's a little bit different so now we do n minus 1 minus j like i just said and then you do matrix i we're just swapping n minus 1 minus j equals 10 and there you have it this is a void um function so we don't need to return anything this should work yup it works as fast as too hundred percent five percent uh memory usage so it's o of one we did it in the description it's in play in place we're not creating a new matrix so it's over and space complexity o of n squared um running time complexity it's just two and two nested for loops so i mean there's two separate ones so technically it's two n squared but we just simplify it to n squared and there you have it please like this video if you haven't already it really helps with the youtube algorithm and subscribe and i'll see you guys in the next video tomorrow
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
21
all right so today we are going to look at how we sort or merge two sorted lists now Alyss is an abstraction I can have a linked list I could have an array so the question on lis code is with linked lists or walkthrough will be with a linked list so I can show you how it's done and how we can like avoid some work at the end you'll see what I mean in like a little case where we exhaust one list but so the question is given two sorted lists this is very similar to my video talking about merging K sorted lists this is actually a smaller video in scope because this is the fundamental that I built off in that video merging two sorted lists this is very important for algorithms like merge sort I have a video on merge sort for algorithms like merge sort we need to know how to merge two sorted lists because what we do is we drill down to base cases and those base cases push us back upwards and we have sorted lists as we go back upwards and medium merge those after doing the split steps for this problem two sorted lists we have a sorted list how do we do this let's look at how we do this so we're gonna do this with a linked list so the thing is length las' problems are so the thing is length las' problems are so the thing is length las' problems are pretty tricky when I first started learning them I was horrible at like pointer manipulation and moving those pointers around to solve problems linked those problems can become very easy with practice and just like knowing the methods that we do to work with these nodes so what we're gonna do for this problem is we're going to put a pointer at the beginning of each of these lists and we're going to use a dummy head to builds this new list so this is what the setup looks like all right so we have pointers on each of our first nodes we have a dummy head I really like using dummy head nodes for limitless problems why because we do not need to worry about having an empty state on the dummy head when we're building our new list if I put a pointer cur on this head which is what we're going to do actually let me rename things so it's a little more clear so what I'm going to do is I'm going to build my list off of curve if I didn't have a dummy head what if cur is know what occur has nothing I can't just say cur Tom next because what if the actual her is not a dummy head node gets rid of this problem by when we points occur I know it's gonna have a value it's just going to be my dummy head I keep saying dummy head this is kind of annoying so I point list 1 points are here L 2 points are there we are going to advance those pointers as we eat up the parts of the list and we choose items so we perform our first comparison we want the lesser item gets the placement if they're equal we can take it from both list one or list two negative one versus one the smaller item is going to be negative one gets the placement so this is what happens so what just happened I appended the negative one node to the dummy head so now this is the first node in our list and it's the last node in our list and what I did was I moved her to this node so cur is always going to be pointing at the tail of the list we are building the tail of the sorted list we are building and I advanced L 2 and now L 2 points here and now we can continue our comparisons between l1 and l2 and advance and just stay with me it becomes very straightforward the thing about these length list problems is they're often done in M plus n time or linear time and we use constant space because it's just about rewiring it's literally like reelect wrists we're just rewiring stuff so what we do is 1 versus 2 one gets the placement because it is less so turn X we point it to list 1 and we advance list 1 and of course we advance occur to the tail of the sorted list cur always points to the tail of the sorted list and so as you can see we rewired the node kurwa sitting at 2 now points to this node and now cur hops itself to what it just pointed itself to because current needs to stay at the end of the sorted list so list 1 is sitting here list 2 is sitting here those are pointers they're pointing into the lists so 2 versus 3 2 gets the placement let's do our rewiring we advance list 2 because we just add up to one of its nodes we point this node that cur is pointing to this node I Bakr hops on to the node is pointed to and now Kearney's who stay at details and list always that's what happens and so now do you notice how as we're going through this we're slowly building up a sorted list we start at negative one we go to two so you see it slowly we're eating up these lists through these comparisons and we're building a sorted list so now what we do is compare list one and list two again cur is sitting at the tail of the sorted list this is the stuff we still are working on so now three and three hoomans so we can take it from either the list let's just take it from the list one so what we do is list one hops here we rewire the node that Curtis sitting on two points to the node that just one and now kurz got a point to the tail which is this node that is about 2.2 and again Curt always sits at the 2.2 and again Curt always sits at the 2.2 and again Curt always sits at the tail of the sorted list do you see how we're building a sorted list and now we continue our comparisons unprocessed territory processed territory unprocessed so now comparison three gets the placement the reverse is five three is the winner so now curve points over here this arrow gets erased curve points over here and then cur hops onto what I just pointed to and L to needs to advance because we just ate one of its nose and so now what we do is we look at l1 and l2 who is the winner is altitude how to gets the placement we point cur to where l2 was and we move cur to the tail of the list for building which is the note that it is about 2.2 all right so now that it is about 2.2 all right so now that it is about 2.2 all right so now you see we're slowly building a sorted list and notice wait I've exhausted l2 so if I've exhausted l2 what conclusion can I make I can make the conclusion that everything from l1 and beyond is going to be greater than the last element in this list it's going to be greater than or equal to the last element in this list so I could still have a four there and I'd still tack this on so what we do is this is a linked list so all we need to do is I arrange this pointer I point to l1 I points to where l1 is pointing because we made the conclusion all these nodes must be greater and as you can see they are going to be greater than the element which is for we can make that 504 it still be greater than or equal to it so what I do is I point this note to l1 and then I am finished because I have exhausted the second list and I know that the first list is all going to be in the right place and so this is how our algorithm works and this is our final linked list so let's write it out so at the end of our function all we do is hey we have a reference to the dummy head point the dummy hat next return the value of dummy head next return the pointer to this note when we have the pointer to this node then bang we have our whole list negative 1 2 3 4 5 10 15 and this is how you merge a sorted list so this is just how we would do it with an array although with linked list is kind of easier because I can just do that pointer I could just adjust that pointer and then bang I have the first list in place first list is finished and we know it's going to be greater than this last item that is how you merge two sorted lists so now let's look at time complexity we always declare our variables when we're doing Big O so M is the length of the first list and is the length of the second list you can swap those I don't know why I put it in this order I shouldn't mean anything Swan anyway but M comes before and in alphabetical order but we use n more often so I would assume that guess precedence so the time complexity is going to be Big O of M plus and at worst we traverse the length of both of those lists if they're very similar we're going to have to do a lot of comparisons and then we'll go towards detail if they're very different if I have a list of 1 2 &amp; 3 and then the other list is of 1 2 &amp; 3 and then the other list is of 1 2 &amp; 3 and then the other list is all values greater than 10 then I'm going to terminates very quickly and just do the rewiring and then jump out of there because I'm finished we're going to be using constant space because all we're doing is shifting of pointers jumping around doing our little rewiring and then getting out of there we're not creating a whole new array we're not create who knows we're not creating an array we're not creating anything that will scale as our input gets arbitrarily large which is what's big o is about what these complexities and asymptotic analysis is about if you like this video if this was a clear explanation hit the like button subscribe I know that this video was kind of easy but the thing is we'll have our fair share of hourly code horns and Li code mediums we'll get to those and do those but I want to set a fundamental basis and teach these because it is key to have these fundamentals for our sorting algorithms and apply to other questions like merge K sorted lists that's all for this video
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists `list1` and `list2`. Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists. Return _the head of the merged linked list_. **Example 1:** **Input:** list1 = \[1,2,4\], list2 = \[1,3,4\] **Output:** \[1,1,2,3,4,4\] **Example 2:** **Input:** list1 = \[\], list2 = \[\] **Output:** \[\] **Example 3:** **Input:** list1 = \[\], list2 = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in both lists is in the range `[0, 50]`. * `-100 <= Node.val <= 100` * Both `list1` and `list2` are sorted in **non-decreasing** order.
null
Linked List,Recursion
Easy
23,88,148,244,1774,2071
86
hey everyone today I'll be doing another delete code problem 86 partition list this is the medium one given the head of the link list add a value X partition it such that all the node less than x comes before nodes greater or equal to X so you should preserve the original order relative order of the node in these two partitions so if you if the link list is given to us a linked list head 143252 then we are going to have also an X variable which will be just an integer and if it is 3 in this case you can see the values we are going to have less than 3 will be coming to the left of the linked list and the value is equal to or greater are going to be on the very right and their order should remain same one two four three five and the right side of the resultant link list should also have the same four three five order so first of all we'll be making just two separate lists so left and right which will be just list nodes a dummy node the dummy nodes so list node okay so we will have an Alger variable and a right current variable so right current left current variable left will be for the left and right will be for the right and a current variable for our current pointer these are also pointers uh for the left and right link list which we are going to create and then we will join it later to form our original linked list so while current is equal to head we will go till current becomes null in our original linked list and if the value of current dot well if it is less than x then we are going to add it in our left link list and then just updating the pointer on the left side dot next and in the else case we are going to do this for the right side so girl dot next is equal to current and right oh right current dot yes okay just updating the pointer in our original linked list so current is equal to current dot next and after that we know that our L Cur variable pointer Al current pointer is going to be at the very end of the left link list so we can just say L current dot next is equal to the right dot next because right itself is a dummy node so rigst dot next so if we have a left linked list like this and the light linked list will be like this but with like this so bar 2 will be pointed to 4 and now the whole link list will become like this but we have to make five point at null because the at this point the 5 does have the next node pointing at 2 so we will go like our current dot next is equal to none and just return no not dummy dot next the left dot next so left dot next and that's it this should work let's see if this works or not let's submit it and that's it
Partition List
partition-list
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`. You should **preserve** the original relative order of the nodes in each of the two partitions. **Example 1:** **Input:** head = \[1,4,3,2,5,2\], x = 3 **Output:** \[1,2,2,4,3,5\] **Example 2:** **Input:** head = \[2,1\], x = 2 **Output:** \[1,2\] **Constraints:** * The number of nodes in the list is in the range `[0, 200]`. * `-100 <= Node.val <= 100` * `-200 <= x <= 200`
null
Linked List,Two Pointers
Medium
2265
354
Hello Guys Welcome To Know The Video The Series According Dhb Blood Circulation Lakshya Studio Painters Of Is Difficult To Win The Inside Of An Appointed To Another Indian Live With 1.138 Appointed To Another Indian Live With 1.138 Appointed To Another Indian Live With 1.138 Volts And Short Term Interest Rate And Which Is The Longest River In This Question Is the longest in increasing order for example subscribe The two in this eliminates all elements are increasing and example you love you all the best during subsequent problem and truly solution to all problems tuvvy tv 10 consisting of elements definitely limit like this perform look at How To Find Answer Of What We Do You Want To Change The Language For Example 12345 125 The Amazing From 0202 Enough To Look For This Is The Parameter Gift Enough To So Let's Move With Example 12071 Subscribe Consisting Of Elements Are You To 9 2012 Question Six And Cigarette In The Basis Of Increasing Sub Chipk Bittu Element Weight 600 Vacancy In The Value Of One Year To Win The Correspondents Pay Are Switch Enter Value And Visit To Elements Of Knowledge To Connect With J2 6 And Again For Subscription For Increasing Clutch Point To The Point Where You Were Too Old For Increasing With Other Elements In Entry Sequence Of Events Of The Day Qualification For Its Elements In This Form Of Increasing Subsequent So Let's Take More Examples To Hate You Welcome More And More Teer Website In This Is Called Afternoon And Job Change So Gel Change From Zero Flashes Will Be One And They Will Be Two In The Morning Punishment Influential Doctor Follow Variable Is Selected For A Question Is The Celebration Is Equal Three ranges echoes in this will have two elements for informing subjects which country is the value of d p kar is point to medium size two three subscribe decoration definitely add two watch Thomas Skimming Now Subjects With Another Element Of Clans 2017 Senior Citizen For Giving Information Supply Switch On The Amazing Value To Three And Immediately St Mira And Clearly Person Weakness Ok No Let's Go Forward To Our Website For More Details In 12 And Is Equal To 9 4 6 Increasing In The Society And Nation Will Reach To Change From 0230 J2 End Subscribe 90 Subscribe Try Na Benefits Loosening Airing Element Select One Or Two You Can So That Value Hears Point To The Intake It Not Let Go To Back Side Reaction One Addition Waves Equal To One Is Good For Elections Poison No Response Green Sabzi Panchvati Colors Point To That Free Indergarh Find The Length Of The Mystery Solve Informing Sabzi Follow 139 It's All Chicken And Will Be Friends Free Switzerland Seervi Changes Strange Land And Three So Let's Go Work To Back side reaction and equation of vacancies shrunk 2012 hands where is equal to forces and subsequent matka responsive to the value in delhi are its history the means 16 element 6 forming in freezing subsequently three elements and that you can see that 1369 sona love you all and 162 Others and Others in No Way Increasing Chicken Planets to Switzerland Year Two for Lips to the Extra Fashion Show in a Side Reaction Bhauji Killed Three and Who Is Called Fool So in This Case with the Elements for Age Suzy Lee Forces on Sunscreen Subject Karj Point Ko For All Defense Todi School Was Already Skimming Assumptions Offline Free Mode Vacancy Warning And Force One Free Forever All Chicken Due To Zoom Lens For Holiday In The Difficult Point To The Index Of Chief Wali Forests Oye It's Ok Services Banyan Tree Se Tension Recovery And This balance for all should be solved finally balance and depression length after all this addition system that Note 4 100 or 125 to interest DP are requested to enter this point excise problem and nurse to the next size in rural sanitation by this point to equal To Find The Value Of Will Reach From 0240 Equal To Zero Ujjwal 2012 Pimple To Four Slaps Previous Lok Sabha Equations With This One Is Equal To Watch And James To 20 For Celebration Select Me Redmi Y2 Price With Different Colors And Vikram Such Physical Profile Change School Par Divas Have Everything Seems Of Elements 147 Days When You Hear For The Indore Difficulty Value Here And Demerits Of Wallace Govardhan Excited Modification One Side Reaction This Rings Total To One And Equal To 50 This Particular K Switch Again Into Elements And For So Let's Let Me Rajeev Rate Subjects Were Wearing A Free End For This Lesson 4 Bread And Butter Quality Of Sperm In Vegetables Switch Of Clans 2014 This Vegetable Is Unheard Of Weekend It Is Necessary And The Planets Needle Scissors Is The Value Of The Day Piary Knowledge Ko Banyan Tree Element 3D Max Elements Make records related to this 6 record finance elements that ashwa great and for withdrawal from which is not for me in reading surgical strike enters go to back side reaction in a side reaction also f4 is equal to full is not smaller than for president for r security Forces Will Not For Increasing Vegetables Soldier And To The Next First Become 12349 All Ingredients Only Manpreet Singh Subsequent And Adventures Complete And Hydration Finally After All This Edition Spread This Explosion Clear Now Late May Zinc Color That Joint NCW Trees To Share So English Particular K Support also cheese repair if then inside maximum possible in physical evidence for any one should support 11516 subjects for and another session according to the judge cheese C 149 302 most strongly and will give the maximum garlic more people basic principles hundred-one and a half hundred Vikram Solar principles hundred-one and a half hundred Vikram Solar principles hundred-one and a half hundred Vikram Solar question accused And This Point To Shoulder And Lag Questions Let Me Clear Govardhan Logic Pro Will apos; Can See Will apos; Can See What 's The First You For Elements For 's The First You For Elements For 's The First You For Elements For Add With Small S With His Two And Half Inch Come After Us And Uk 06 Bodhi Vriksha Airplane Come Here From This Is Vivek Oberoi And This Tractor Sorted By Which Way Can Make You Love You Can Just One and Half Inch Width Minimum Volume Maximum Number of Giving One to Two Boys Subscribe Now 104 Diet Relations Will See Back Na Person Parameters to Compete with Amit Vikram Very Good Source Spell Check 512 Withdraw Develop This Into In Cases in a Small Enterprises Difficult Friesland Opinion Village Support System Options Vision with Faith and Fight for Pain During Inner Wheel Club InnerWheel is now having a relationship with two and wearing tight Free See the Question Meaning Properly * * * * * * * * * That going inside to here follow Suji Kal 2012 112 2800 Hero BJP Are Properly Which Continent And Electrification See Tension I Want To See Them 9 6 And Interact With Them Properly Can Just Subscribe To My YouTube Channel The Channel and subscribe the Big Person When England Makes Sex with Six and Light Practical Another Innovative Sighting Let's Say with Spinach and Life Is the Winner of Annual Love This Place in the City and All Over the World and Two So Let's Check the Most Obscure One Two Three Should You Are I See Two Three Should You Are I See Two Three Should You Are I See Code Free This Rings Kumar Forensic Condition Him Loudly To The Height And Width Side So This Of This After Winter Huge Tree Mast And Adding Another In Are In Love With The Significance Of Life But Inside Famous For Its Already Fallen In Love How Did Not Because Zindagi Peer Value 230 Rings Monitoring Luck Last Year England Tour And Height Free Which Were Seen Previously Soil And Having One Quick Tour And back to in love story doctor interview hai vaibhav cold days six all cervix cancer value two three layer in peace and love suggestion value sperm donor given two plus ministry said adding this afternoon of polar region's 10 mediums of engineering research just opposite It will be free, let's go Vatavriksh Example member Lal Singh and last hydration for a classic example Eye record for senior judge 250 66 distribution camps present to give dollars Twitter The Channel and subscribe the Possible Velvet Questions and Answers to life and finally Bigg Boss Maximum Free Play List of Solid CO2 subscribe and subscribe the Video then subscribe to the Page Muddasar Very Simple Inch Plus Office Gift Function Of Us Want To Know Automatically Short And Adventures Of Birth Per For Annual Rainfall Utsav Term Us Look Into Equal To Zero Electronic And Develop Dot Size And Half Inch Plus Pendu *Also Give You Will Have This And Half Inch Plus Pendu *Also Give You Will Have This And Half Inch Plus Pendu *Also Give You Will Have This Post Will Be Able To Point To Subscribe To The Page If You Liked The Video Then Who Is With This Great Up And Also Will Give Another Condition Smooth on Yellow Height and Laugh IS One Such This is the Height of the Lambs Paid the Height of the Year and Loves U Don't Know To subscribe to the channel Russia Change the Value of the Country of the World Subscribe to the channel and G Plus One plus one and more than half volume maximum selected from easy sequence give maths elements and elements of obscuritism up dot big b dot net a tent and light show i will run this and its effects of working withdrawal it gives no gratitude of this i and Let me see where no man and develops in and we lighter sort of interest to begin ok so why have the given water mixed and definition of a plate mixing sheet against its surface made in the west royal zones the draw and the 9th 800 l x Resolution Scientific
Russian Doll Envelopes
russian-doll-envelopes
You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_. **Note:** You cannot rotate an envelope. **Example 1:** **Input:** envelopes = \[\[5,4\],\[6,4\],\[6,7\],\[2,3\]\] **Output:** 3 **Explanation:** The maximum number of envelopes you can Russian doll is `3` (\[2,3\] => \[5,4\] => \[6,7\]). **Example 2:** **Input:** envelopes = \[\[1,1\],\[1,1\],\[1,1\]\] **Output:** 1 **Constraints:** * `1 <= envelopes.length <= 105` * `envelopes[i].length == 2` * `1 <= wi, hi <= 105`
null
Array,Binary Search,Dynamic Programming,Sorting
Hard
300,2123
151
welcome back everyone we're gonna be solving Lee Code 151 reverse Awards in a string so we're given an input string s we need to reverse the order of the words and a word is defined as a sequence of non-space characters the sequence of non-space characters the sequence of non-space characters the words in s will be separated by at least one space so essentially what they want us to do is right they give us a string the sky is blue they want us to return blue is the sky and if we take a look at the follow-up and if we take a look at the follow-up and if we take a look at the follow-up question if the string data type is mutable in your language can you solve it in place with all of one extra space uh as we know strings are immutable in Python so I won't be doing the follow-up Python so I won't be doing the follow-up Python so I won't be doing the follow-up question uh python is my main language so there's no reason for me to be asked this follow-up question but if your language follow-up question but if your language follow-up question but if your language does do it you know leave some comments down below and show me how you do in your language of choice all right so what we're going to do is we're going to create an array and it will be equal to uh s dot split right what is this going to give us let's print this out so we'll print out our array all right so this gives us all of the words right in a list format okay so now what now we can just make a pointer right we'll point it to the very last word and then we'll just create a new string with the word at the pointer position and then decrement our pointer every time we use the word right super simple so let's say uh we'll have a resulting array which we will use to put the words in and we're going to have a pointer all right the pointer is going to be equal to the very last position in the array we just made so it'll be the length of array minus one now we are going to run a loop while this pointer is greater than negative one we want to add the word at the pointer position to our resulting array so we'll say well pointer is greater than negative one we are going to say um actually let's make it I'll make it more clear so the word that we're going to grab is going to be equal to array at the pointer position and what are we going to do we are just going to append this word onto our resulting array so we'll say res that append the word and then we can just decrement our pointer by one and then let's before we return let's print out what we have so we'll print res and we see we get blue is sky the right that's what we expected uh the all the words are in reverse order but how do we return this well now we have to return a string join right they want it in a string format so we will say we will return a string join of our resulting array but each word needs to be joined by a space right so we add a space to our string join and we can just return and that should be it so let's run this perfect we pass all three test cases we'll submit perfect it does run so time and space complexity time complexity is going to be o of n right we are looping through our array and grabbing all of the words touching them at least one time we're also creating a split array right this is going to be o of n this while loop is over n so now space complexity is going to be based on the length of our resulting array plus the length of the array we created with our split function so it will be array.length plus the resulting array.length plus the resulting array.length plus the resulting array dot length all right that'll do it for Lee Code 151
Reverse Words in a String
reverse-words-in-a-string
Given an input string `s`, reverse the order of the **words**. A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space. Return _a string of the words in reverse order concatenated by a single space._ **Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. **Example 1:** **Input:** s = "the sky is blue " **Output:** "blue is sky the " **Example 2:** **Input:** s = " hello world " **Output:** "world hello " **Explanation:** Your reversed string should not contain leading or trailing spaces. **Example 3:** **Input:** s = "a good example " **Output:** "example good a " **Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string. **Constraints:** * `1 <= s.length <= 104` * `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`. * There is **at least one** word in `s`. **Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space?
null
Two Pointers,String
Medium
186
373
Hello gas welcome you me YouTube channel so today we are going to solve problem 373 fine pairs with small further problem what is doing this is medium level problem you are life you interior are name one and you sorted in ascending order and Consists of one element from d second between waiting if it has to be returned then how much will be made in it, there are three names and that with 11, you with 11, 411 567, then 3 is the smallest [ praise] how to make plus, it is done like this and they are vector. Your type is done, what will we do, which is the index here, if we index both of them, then what will we do with this, then this short function will always be short, what will we do now, just now there is only one less total. Those who answer the first one But this is the type of store, it is of this type, so let's take it as mother, what happened to it, the total is a value, it needs the one with this number, it will go inside the answer, which type is yours? Is of vector and is of vector type but how much is there so that it can become two, then we will check that the number of feet we have made, if it is more then we can enter only two, otherwise only two have to be returned here. You will see that if the value of the cake will be more than 3x, it can be made on two, one can become three and you can make three, so what will you do, then you will check that the amount that you have made should be limited to that, otherwise if there is extra, then it will go to A. If it is done, now we will run it and submit it will come to you, the memory limit will go straight, why would we increase the time complexity here, like how much will it take to shorten it, how much will be its length, how much will be its legs, and then we are sorting it. Take total mother, if it has 3 size relief, 3 * 3 = 9, relief, it has 3 size relief, 3 * 3 = 9, relief, it has 3 size relief, 3 * 3 = 9, total will be 95, then why should we do the full shot, then why can we give it priority, how will we give it priority, then what will happen to it, what to sort? If it will be in sort, then for the first time there will be a memory limit that whatever number of elements will remain on it, that much time will be required because the size of this will be multiplied by the size of this, that will be the total number of elements, then how will we optimize it? Let's first remove the vector that has been created for this. Now, how will we optimize it? So let's see here, what will we do to optimize it, this is the value in it, this is 12, first of all, first is the element of this. Now why should we make it a priority? First, what do I need in this? If I want minimum, if I want minimum then what will I make in this How is it divided? To make mini, it is better to write so many times here. Whoever knows the short, then direct it here also. It can be written, there is no need to write it again and again, let's type it here first index. If we will create the first index to put it in Preetiko, then how will the priority be divided, which is your type and which type is greater here? First of all, what will you do and what will you do with this, give all this pulse, first give these pulses, what else will you do, what will you do after posting, this one who is the one with the answer, this one who is your greater Give it zero, this one, what else, what is the size of the priority, give it a greater zero, this is also possible, the priority has become the first zero, how can this one be emptied first here we have to top of that if If we go to extract it, then it will come here because we are extracting it from the empty space, so this should also be checked, the meaning should remain, so what will we do now, your time is gone and its second is this second, this one, so these three. A went on this, now this has been done to you, if you put it in the direct answer, then answer dot answer where you will create vector answer dot post back, your value will be back. After doing that, what will happen in the first step. This is yours being stored here, so these first three 30, these three will be inside it, if it is in hip, then what will come first in it, three came three, what will be the difference between three, one and you, what will be its index, what will be the value of index. So the IPA index was zero, what will happen if you change the name to zero, then what will happen if you are the same, we will put it in 12, now after flying, one has become less, it has happened with this one, we will compare one with four. So now we will enter the value of K by doing plus one, something will happen here, one plus, how much is one second, what is one plus, 5, sorry, so what happened by putting six, now put six here, so here But what will be the seven and here the index is the first one, so how much is it, now which is the minimum among the three, 7 then 7 will again pop top, the corresponding name of seven is zero, how much is zero, your name is zero one, so here How much will be the value of name one and six? Then again we were writing the answer, so now what has happened, it has popped, now what is less, now we will also check the first one, so now to compare with it, compare with the second one. If we get it done then now we will give its second index pulse, whatever it is, it should remain small, so if it is small then only if we push inside it, then why will we do it because mother, now there is relief here, so now it has reached six, now how much is the plus one going, now it If you do K plus one with one, it will be taken out, neither is this, nor is the name, K plus one, nor is your name, when should the name be from the studio side, because six plus one will go further also, there is something in the future, otherwise. So only then we will push it inside, we are doing it with this one, then we are adding it inside it, if we add it to the second one, then now this first one is not removed, so now it is reduced, so now we will compare it with this one, mother, whichever one comes first. If it is in sorted order, then whoever comes first, what will be the name, here the name will come but the size of both of them is the same, this one has so much time complexity, so now when we want to go private in it How much is there in this, now how much is the total in it, how many elements are there in it, how much is there in taking out the hip from the total, if there is n size and if we have to extract a value from it, what will happen then what will happen to that To pop the time complexity means to bring it to the top, if we pop from it, then the top operation is done, its time is still there, as per the size of the people and as per the size of the login, the mines will run till the login, the mines are fine, see you in the next video. Please like and subscribe tu me channel
Find K Pairs with Smallest Sums
find-k-pairs-with-smallest-sums
You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`. Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_. **Example 1:** **Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3 **Output:** \[\[1,2\],\[1,4\],\[1,6\]\] **Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\] **Example 2:** **Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2 **Output:** \[\[1,1\],\[1,1\]\] **Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\] **Example 3:** **Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3 **Output:** \[\[1,3\],\[2,3\]\] **Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\] **Constraints:** * `1 <= nums1.length, nums2.length <= 105` * `-109 <= nums1[i], nums2[i] <= 109` * `nums1` and `nums2` both are sorted in **ascending order**. * `1 <= k <= 104`
null
Array,Heap (Priority Queue)
Medium
378,719,2150
745
hey everybody this is larry this is day 18 of the rico day challenge hit the like button here to subscribe and join me on discord let me know what you think about today's farms i'm back in new york i went to wedding actually it was a beautiful wedding it was a beautiful day uh and now i'm back home where i probably should set up the ac but it is very hot let's put it that way in my room right now um i mean i think it's like 80 degrees outside fahrenheit for those of you with normal time scales i think or temperature scales i think it's like 20s or something i don't know what is it they have to see is 27 degrees uh and my apartment is inside is hotter so yeah anyway with that said today's problem is prefix and suffix search okay design a special dictionary with some words that are searched by prefix and a suffix what does that mean so apple uh so you have an f function that's a and e so return zero so what do we turn to okay let's see so we have a word list okay that's fine we turn the index of the word in the dictionary which has prefix and suffix if they're more than one violin then return the largest of them okay um yeah and each of these will be at most 10 length i mean i imagine my first instinct i mean this is obviously a data structure farm uh or this is set up that way um and i for my first instinct is to have like a try right um a try for both the prefix and the suffix um of course it's still a pre you know a prefix try but for the suffix you would just uh process all the words on the other direction and then maybe do like an intersection of the sets or something like that um but i don't know if that's good i mean in theory that should like on average case will be okay right but definitely you can construct cases where that is just not acceptable right so then in that case what do we do if like for example if maybe i'm actually like for example if the two intersection is like if i'm trying to think i mean this the average case would be okay but the worst case right is if both of them contain say 7 500 uh or yeah 7 500 uh words um and they don't intersect at all and we do that like you know 15 000 times that's gonna be too slow right so can i do better hmm um definite prefix makes sense can i walk that dag i mean it'll still be like if you zigzag so you can't really walk the two-pointer so you can't really walk the two-pointer so you can't really walk the two-pointer algorithm or something like that um in a better way i mean maybe it's slightly better but uh um yeah sorry i got messaged hmm like i don't know if this is just one of those problems where you know maybe the like how bad is the worst case right or maybe i'm missing something maybe can we abuse something with the word length of ten in a good way are all the words unique see i guess if they're not i guess if they're not unique then you just keep track of the larger index anyway right because it doesn't make sense to um yeah but i don't know the way that i was thinking about it is that uh i don't know if i should figure out this one for the average case or the worst case i think that's the tricky part um but maybe it's fine i don't know if there's an easier way so maybe this is fine i don't know um because my thing is that like let's say yeah my thing is that if jeff's let's say an ae case right let's say you have i mean just like the set intersection it's gonna be very expensive if none of them matches but if it does match you under the biggest one so you do a linear walk but that's still like the average case would be good but the worst case may be bad and you could keep on pumping the worst case um hmm let's see i don't know i mean okay can i take advantage of the 10 in a way um can i brute force oh can i save the answers in a good way um i want to also just like if i can keep tr maybe i can keep track in a good way but i don't know about the timing no because i was thinking about way we're almost like a pre-filtering thing we're almost like a pre-filtering thing we're almost like a pre-filtering thing of um of like okay so yeah because just getting the a list of all these numbers and then removing them will already be too slow right like let's say you have um a 10 000 word length and then you kind of just um you kind of uh yeah you have 10 000 words and then you maybe go down a tree with those 10 000 words and then remove them as you go right but even that seems too slow can we do intersection in a good way with respect to that huh um well okay no can we take the suffix in a good place no i don't know i'm a little bit stuck on this one i'm not convinced that at the double try ideas fast enough just because unless i'm missing something but because this can have like a lot of words right um i guess like for example if we have like we can easily construct an example where like this is the worst case so then you have f of say a e even which is the one of the examples but then you have word style like a e a or maybe even something now that this would be okay but just something like you can even just do something like a b uh a b a c dot like 10 000 of these right um and then maybe i mean this is not even the worst case i guess okay you have something like this maybe and then you have something like you know uh e a e well maybe b and then c e d dot 7 500 of these right so there'll be no intersection between these and therefore it would take the full 7 500 um per function call and each function cost 15 000 times so 15 000 times 75 000 is not gonna be good enough right um so i don't really know how to do it in a better way to do like some sort of intersection without figuring um out like maybe i don't even uh like should i yodo like is this fast enough no hmm i guess one way we can do it is what is uh this times 100 right so to do 1.5 million 1.5 million 1.5 million 1.5 million times 10 is 15 million is 1.5 million times 10 is 15 million is 1.5 million times 10 is 15 million is that enough uh something like that maybe 30 million i guess maybe that's enough memory i guess we could pre-process guess we could pre-process guess we could pre-process all the possible for each word we can pre-process all the for each word we can pre-process all the for each word we can pre-process all the possible prefix and all the possible c suffix and then we can do def f of one the only thing i'm a little bit worried about is that um so f so this will be fast enough the only thing that i worry about is about memory whether we have enough memory um to do it um but um let's see right so there are a hundred prefix hundred suffix so we do a hundred square well technically one to ten so i guess that is ten a hundred um so that's uh what is it 1.5 million and each of them what is it 1.5 million and each of them what is it 1.5 million and each of them may contain up to 20 characters so that's 30 million um and that's probably pretty okay 30 million characters with some overhead it should be okay let's try it that way uh a little bit sad that it took me that long though to be honest to think about it but there's just a lot of i was trying to figure a way to do it without this thing but maybe that's just the way to do it i don't know let's give it a spin so that now for word in words uh maybe i don't need this actually but anyway self.lookup is to go to hash table um so self.lookup is to go to hash table um so self.lookup is to go to hash table um so then now key is equal to let's say yeah um well so for i in range of length of word and then for j in range of length of word right is it maybe plus one but also starting from one so i is the sub or prefix and j is the suffix so then we have something like um oh what is it from the first eye yeah maybe uh maybe something like this it doesn't really matter just some sort of maybe just space maybe this place is fine uh and then is that j now it's um negative j right let's print this out real quick because i'm always really bad with off by ones with these indexes so i think this is right but maybe i'm offline one a e a o e a b okay that looks okay so yeah okay so then now we can do something like sub dot look up of key is you go to index right i didn't actually do the enumerate i forgot um and this will overwrite with later one so i think this will give us the largest one so then now we have key is equal to um also technically what i would recommend is actually putting this in a function but functions in python are expensive this is not so if you're doing production code definitely put in a function lead code is slow so um i'm the code is silly so uh yeah i mean yeah they don't have any optim uh it's just slow so that's what i'm doing this way so okay if key is in sub.lookup okay if key is in sub.lookup okay if key is in sub.lookup we turn uh i should say we turn negative one which is not true we return self.lookup of key this is zero indexed self.lookup of key this is zero indexed self.lookup of key this is zero indexed i guess so let's give it a spin i mean this is a really easy thing to do let me see if i can well there's only one way all right let's just give a quick submit and see wow apparently in the past i've done it in many ways okay this time i did it i mean i solved it on the first try so keeping the streak alive at 809 days but much slower i don't know if they added more word or anything how did i do it previously let's find out oh let's go with complexity real quick i mean like i said this is o of um n one for each word times uh let's say l times uh or maybe p times p where p is the size of prefix suffix to curry right and then i use i didn't actually use as much memory as i worried about uh and then here this is just o one basically uh depending on how you say it or one in terms of lookup you can maybe say of n in terms of the size of the input and then look up it um but that's up to you i am i'm trying i'm curious how they did it last time definitely ate some things uh i did do it with try so how did i do it try oh so this is the thing where i did the set intersection is going to be too slow i think i was very optimistic in uh and i don't know why i did it this way except just like max but maybe i was just 2019 i was still learning python a little bit or like learning yeah i mean i would say i was still learning python um yeah you would just get the max but i'm not surprised that time limited and then what would i do uh and then i did some up what did some weird optimization but oh and then i did the thing where i moved one at a time but apparently there's some like weird thing going on i don't know uh and then i gotta accept it and ultimately by oh i still use huh so the try in the section thing works i wasn't sure that this was fast enough to be honest that's why i didn't um but i guess my past larry is more confident about it's the thing like i said right like we can construct cases where this is just too slow and then if you do that query like 15 000 times it's going to be too slow um but today i just wasn't maybe i self-doubt today i just wasn't maybe i self-doubt today i just wasn't maybe i self-doubt myself too much and i should yell no more what was the hint anyway oops what did i cook uh what was the hint oh that's basically what i end up doing but that's not even a hint that's just like telling you how to do it uh how did i do it the second time oh i did do it well i did it the same idea but i did it with uh much slick no yeah well i mean this is not a stuff seems like the second time i did i got lazy with the tree and i just put everything in a set um but then it was the wrong answer and then time limited so it was too slow so then i oh i did what i did today except i use a tuple instead is that better i don't even know but i got wrong answer what did i get wrong answer oh i don't know why i did it this way but this is the wrong answer because i um i reversed the word uh maybe so i could write this a little bit better wait what this is just silly i think it was just like me being careless because this should be j at the very least um so there are a couple of errors there but then i autumn i think i just because the inputs didn't test it so there you go and then suffix i reversed it so i reversed it twice so it's a little bit silly actually um but basically it's the way that i did it today so maybe there is more input as well um maybe not i mean strings does take more time to construct but maybe not i don't even know anyway this is a very weird problem because i think it i think this is uh one of those problems where the constraints don't really tell you the whole story it depends on the distribution of the inputs which they don't really or there's no easy way to tell because like i said um i don't know i guess i deleted it but because you know you can probably break tle most cases if you just have something like your word dictionaries a b a c a d no a e uh a f dot and then like just doesn't really matter what they are just anything that starts with a but 7 500 of them and then something that ends with say e and then also doesn't matter what they are um as long as you have 7 500 000 of them and none of them with a prefix right and then you just run query f of a e 15 000 times and if you do it that way just with time limit because there's not nothing to do you have to do it essentially a full set intersection which is 75 100 times two um and and fifteen thousand times fifteen thousand square is gonna be too slow so which is why i hesitant um but i don't know sometimes you have to read minds or yolo and get a little lucky uh didn't do either today so whatever anyway that's all i have though i did get it on the first release time so i guess that's good anyway stay good stay healthy to get mental health i'll see you later and take care bye
Prefix and Suffix Search
find-smallest-letter-greater-than-target
Design a special dictionary that searches the words in it by a prefix and a suffix. Implement the `WordFilter` class: * `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary. * `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`. **Example 1:** **Input** \[ "WordFilter ", "f "\] \[\[\[ "apple "\]\], \[ "a ", "e "\]\] **Output** \[null, 0\] **Explanation** WordFilter wordFilter = new WordFilter(\[ "apple "\]); wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ". **Constraints:** * `1 <= words.length <= 104` * `1 <= words[i].length <= 7` * `1 <= pref.length, suff.length <= 7` * `words[i]`, `pref` and `suff` consist of lowercase English letters only. * At most `104` calls will be made to the function `f`.
Try to find whether each of 26 next letters are in the given string array.
Array,Binary Search
Easy
2269
1,732
hello so it is uh 19 June 2023 is lead code uh daily challenge it's a easy level question is find the highest attitude yeah so what's the question stated there is a biker going on a road trip the rotor consists of n plus one points at different altitudes the biker starts his trip on point zero with altitude equals to zero you are given an integer array gain of length and where gain of I is the net gain in altitude between I and I plus 1 for uh index ranges from 0 to n minus 1 both inclusive return the is attitude of a point so basically from the problem statement it is clear that a gain of IE is gonna be sum of the of that value which the value that is there in that I that index and the previous Index right while you are the previous index so that's how it's going to go and that's the example the one also State States the same thing so if we calculate the gain array and this is how the gain array is going to look like because the initial gain is going to be 0 because we are starting from uh because at some point altitude with equation zero so this is how the initial attitude is going to be then the second uh first started is going to be minus 5 because that's the again at this point and then when you move to the first index uh yeah when you move to the next index the gain is going to be the addition of that index plus the previous index correct so that's what has been done so basically um what is happening is we are calculating the prefix sum of the array uh we are calculating a prefix gain array right the gain error is actually a prefix uh of the array that is prefix sum of the array that has been given to us so when we if we could calculate it and we could keep uh running some running marks as a as answer or finally if we could uh maintain the maximum amount so that we are getting at each and every index that will be a running Max and your at final when the render traversal is done if we return the answer and that's how and that's that would be the answer and the thing that we are an additional case attached is zero could also be the answer so initially by setting up answer equals to zero and running your uh running calculating the prefix this uh some of the gain array that has been given to us and uh at runtime calculating the maximum for each and every index that has been given to us calculating the getting the answer correct so this prefix array could actually be can you calculate by using an X carry also as there is so many connections even on the gain area that has been given to us that is it could be modified also so we will actually modify this area to calculate the prefix uh sum for each and every index so initially we'll have an answer zero and this is what is going to be written as answer could be 0 and then we'll calculate the size of the given array and then we are going to travel Travis from the first index because screen of I is going to be gain of I plus the previous index so we'll grab us from the first index so that there is no out of boundaries or something like that so but the possibilities of answer being gain of 0 is also a exists right so we'll make sure that we calculate it separately and then now we rapid Ours from the first index all the way to the last index and Performing this particular operation that is gain of I will be addition of gain of I plus the previous gain that is gain of I minus 1 and we'll update maximum answer also that is yeah and that's how it's going to be done answer after this foreign yeah so without discussing the diamond space complexity time complexity is going to be order option because we are doing a single trouser space complexity is going to be constant for the implementation that we have done uh if at all there is a constraint on the given area to be not modified then you have to say I can create a separate area for calculating uh the gain even that is not possible if even that is not needed we could just perform the action with just two variables because gain of I is actually depending on the previous index rate so we could have a previous well and then the current well so previous value will uh get updated every time when we move uh to the uh new index and current will be calculated and the next iteration when we come to the next iteration previous value could be made as current value so that could be done like a sort of yeah that could also be done and it's calculating the answer in an easy way so I
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
328
okay hi everyone so today we're going to swaminate code problem number and 3D challenge problem number three to eight on demanding list so in this uh what we have to do is we have to just uh basically grow all the elements or all the nodes at uh odd indexes and all the notes of uh even indexes together and one more keynote over here is the first index will be treated as a odd index okay it should not you know you should not think of it as a zero index element and mobile so the first index will be treated as a odd and X and they have also given this constraint that we must try to solve this problem with order of one extra space complexity and Order of end time context which means we should not use any Extra Spaces to throw the link list and we should try to uh you know solve the problem in a single path okay so solution for this will be a very simple solution in which what I'm going to do is I'm gonna use two pointers first point to the very first node which is an odd node like the first pointer will be used for uh you know keeping a track of odd index values or notes and second one will be used for the even indexes okay so I'm gonna initialize that the or going to be the first one and even point to the second and what I want to do is incredibly if I want to create two separate linked lists for odd and even and at the last I just want to point the next pointer of the last forward element or node to the event list okay so how we're going to do that is for example my pointer is currently pointed to 1 like the odd filter and the even responding to the two okay what I'll be doing is odd dot next will be equal to what even dot next right so 1 and 3 will uh get together and similarly for even and of course like I'll move my odd pointer and we can simply say R is equal to odd dot name so now I want to be moved from 1 to 3. similarly for SEC like the even pointer my pointer was pointing to the two ways of now but uh after making you know all the changes in our pointer my odd pointer is three right uh next of three is four so what I'm gonna write is even is equals to odd dot next okay so essentially I'm just uh changing the pointer of my event to the next of odd and similarly we are going to update the even pointer as well so to do that Let's do let's start writing the question and first of all like you know this is a base condition or an H case condition for any linguist problem we should check if we even have a valid head Dot if it's a emptied linked list I just don't want to proceed further and I'll just simply return the head now as per explain I'm going to initialize my mod pointer to head and even pointer to head Dot next right now what I want to uh check is for example you know my even water is my uh how to say like the last point is uh or the after 0.2 the last point is uh or the after 0.2 the last point is uh or the after 0.2 which will be pointing to the last note for example if there is a single node only okay then there will be no even want or node right or let's say we are moving ahead so our node will always fall back off even right so what I'm going to do is go even like I'll check if my even node is valid yeah even has one next Point that's only when you will be able to update your odd pointer or linked list right and makes you know we discuss about this condition what I'm going to do is r dot next will now become even dot next and we're gonna update the power pointer similarly even dot next will now become or dot next and we will have data forward okay uh one more thing which I wanted like you know which I mentioned while describing the problem is I wanted to keep these uh sorted uh these odd and even lists separate so now we have the but to unite them again we would need but more pointer so basically this is a pointer to the first node of the event list okay and at the last what we should do is power dot next we will now point to even point and now we can simply return our headquarters over here let's see uh if the test case is you know it's passed yep so test case it was passed successfully let's submit the solution for rest okay so the submission uh you know so once you've got the solution got accepted successfully and I think we can optimize a bit Pro on this part on the solution but you know it got accepted so thanks everyone guys for watching the video and stay tuned for the upcoming ones thank you
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
169
foreign from lead code and then solve it so I am picking a problem number 169 majority element so this problem is actually asked in Google Facebook and Amazon so let's go to lead code and see what exactly the problem States so if I take you to lead code majority element the problem says given an array of size n given an error numbers of size and return the majority element so let's read the description the majority element is an element that appears more than n by 2 times so if there is any element which appears more than half of the times it's considered to be a majority element and what we have to do is we have to return that particular element if and there is some more description given you may assume that the majority element always exists in an array so always there will be a there will be one element which will occur more than n by 2 times now if we just see the input so in this particular input you can see there are there is three two three but three has occurred twice so it's occurring more than half of the time so the output is 3. if I see another input you can see 2 has occurred four times and one has occurred three times since 2 has occurred more than half of the times output has to be now let's try solving this problem so now I have taken this array as an example now if You observe in this particular array there are seven elements so if there is any element which occurs more than seven by two times in this particular array that element can be considered to be the majority element and that has to be returned so if You observe this 8 has occurred four times so it has occurred more than seven by two times so definitely eight has to be the output so now let's see how we can approach towards the output so what is the logic that I would follow is I will pick any one element from this array and then other count the number of times that the element has occurred and if the number of times the element has occurred is greater than n by 2 I will return that if that's not the case I will check for another element so how to do this let's just Tempest so what I would do is in this particular array I will pick the first element so if I pick this first element I will Mark its index to be I so in the value of I is what 0. so I'll say I is equal to 0. next since I need to keep track of the count I need one more variable so I'll create one more variable named as count and at starting I will initialize the value to be 1 y 1 because I already found first occurrence of it next what is that I need to do is I need to check how many times it has occurred in the complete array since I picked this particular element in the zeroth index I need to check how many times 8 has occurred from index 1 till the last index so how do I do this definitely I need to check for this element is that equal to it next I need to check whether this is equal to it next I'll need to check whether this is equal to eight so basically I need to check for all the elements means I need to Traverse this so to Traverse this array I will pick one more variable and I'll name that variable to be J and it will start from index 1. now I have marked J to be index one next what I will do is I will check whether the element present in index J is that equal to the element present in index I no I won't do anything in case if it was true I will I would have increased the value of count next what I would do is I'll increase the value of J I'll check whether the element present in index J is equal to the element present in index I yes I'll increase the value of count becomes 2 and if You observe you have encountered it twice next I will increase the value of J I will check whether the element present in index J equal to the element present in index I no next I won't do anything I will go to the next index I'll check whether the element present in index J is equal to the element present in index I no I won't do anything next I will go to the next index that is index file is the element present in index J equal to the element present in index I yes so in this case I need to increase the value of count becomes 3. of count the value of count becomes 3. next again I will increase the value of J I'll check whether the element present in index 6 is that equal to the element present in index 0 that's index I yes it's equal I will increase the value of now if You observe the value of count has become 4 and if You observe the 8 has occurred four times so basically what I've done is I have traversed this particular array and checked whether the element present in index I is equal to the element present at index after doing this what I do is I will check whether the count value is greater than n by 2 times so how do I check I will simply write one if condition if count is greater than n but the length of the array divided by 2. if it is yes then I need to return a value and which is the value I need to return the value which has occurred this many number of times and which is that value that's nothing but 8. so how do I uh return it in a generic format so eight If You observe is present in index I so this is what you were checking for so what I need to return is I need to written a r of I so this is what I need to do now let's see this part now if you had observed the value of J actually started from index 1 and when till index 6. so how can I do I can simply write a for Loop where the value of J starts from I Value Plus 1 and then goes till length of this array inside this what I used to do I used to check whether the element present in index I is it equal to the element present in index J in case if it is true then I used to increase the value of count so I'll check that condition and increase the value of count so basically this is an algorithm but there is a problem in this algorithm the problem is this is not complete why it's not completed because in case if 8 was not the majority let's assume 5 was in this place and 8 was over here now the number of occurrences that you have got or the value of count that you would have got would have been one because you were checking for five now till the end you have not found the majority when you check this condition the condition is false so what is that you have to do simple you have to pick the next element and then check for the same so in case you have to pick for the next element don't you think you need to increase the value of I yes you need to increase the value of fine after that what should I do I need to check this element with all the other elements from index 2 to index X so basically again you are checking from index I plus 1 to this and for that I have already written the code over here in case if that's not the majority what is that I need to do I need to check for the next index so if I have to find for the next index again I have to increase the value of I and repeat the same operation if that's not the majority find the next index same way I need to go till the last so don't you think the same thing has to be repeated multiple number of times means I need to check the same thing for the value when the value of I is 0 next 1 next 2 next 3 in case if I don't find the majority so what I do is this whole code I'll be writing inside a loop and in that particular Loop the value of I would actually start from index 0 and go till the last index so how would I do that for I is equal to 0 to length of this particular array so this is an algorithm to find the majority element now let's go to lead code and write the code for this particular algorithm so now let's start writing code so if You observe there is a method named majority element it's accepting array named as nums so I will change that array name to be ar so that it's easy for me to type as well so I'll name it as AR and the return type is int so that's nothing but the element which has occurred majority of the times so basically what we did is we picked the uh picked one element at a time so what I need to do is I need to write one for Loop so I'll write for and I started from index 0. so the first element that I picked was from index 0 so I'll say int I is equal to 0. and in and I need to go till the last element so I will say I is less than a r dot length yes and in case if I don't find the element I need to go to the next element so basically I need to increase the value of I by 1 so I will say I plus I'll come inside this what I need to do is since I'll pick the element present in index I now I need to keep track of its count so I need to create one variable count so I'll say int count is equal to I will initialize the value to be one so I will say count is equal to 1. next whichever element is present in ith index I need to check with all the other elements so I need to create one more Loop in within this so I'll say create one more Loop so I'll say for I'll name it as J int J is equal to now if You observe it should start from I plus 1 means from the next element so I'll say I Plus 1. and I need to check till the last uh element of the array so I will say J is less than a r dot length and then J plus and basically inside this what I am doing is I'm just checking if the element present in ith index equal to the element present in jet index so I will say if a r of I is equal to a r of J so is a r of I equal to foreign yes now once I come out of this Loop it means I have checked for the number of times the element present in AR of I so what I would do is I'll check how many what is the value of count is it greater than n by 2 how do I do that I will say if value of count that's count is greater than n by 2 N is nothing but the number of elements present in this array are so I'll say a r dot length divided by 2. yes if this is true then it means to say the element present in index I is the majority element so I need to return that element so I will say return the element present in AR of I so I'll say here of I and I'll do this and in case oh sorry they have told us very clearly you may assume that the majority element always exist in an array yes now what I do is I'll just run this code once so I'm running this code so it's checking so they're saying error missing return statement why it's showing me this error is for a simple reason if I just close this so what has happened is I have written if a return statement inside if condition let's assume the return statement never executes in that case there is no return statement outside the loop so that's the problem so Java is saying you have to put one written statement outside the loop because you have put this within if condition so I will come out of the loop and simply I will say return -1 will say return -1 will say return -1 I know for sure this is not going to execute but let's just put this now we'll go and run the code so if I run the code yes it has been accepted so let's go and submit the code over here so if I submit the code it's still running so you can clearly see uh run time the milliseconds faster than 5 percent of java online submissions means I am faster than only five percent of the people so I am among the last five percent of the people means my solution is among the last five percent of the people why if you ask me because of its approach now if you ask me what is the time complexity of this approach the time complexity of this particular approach is Big O of n Square so this is not an efficient way of writing the code and in case if you go and write this particular code in Google or Facebook or Amazon they are definitely not going to shortlist you so we need to write a better approach or a better uh better solution which is better than big of n Square so is there a better solution yes there is which is that solution let's see in the next session
Majority Element
majority-element
Given an array `nums` of size `n`, return _the majority element_. The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array. **Example 1:** **Input:** nums = \[3,2,3\] **Output:** 3 **Example 2:** **Input:** nums = \[2,2,1,1,1,2,2\] **Output:** 2 **Constraints:** * `n == nums.length` * `1 <= n <= 5 * 104` * `-109 <= nums[i] <= 109` **Follow-up:** Could you solve the problem in linear time and in `O(1)` space?
null
Array,Hash Table,Divide and Conquer,Sorting,Counting
Easy
229,1102
118
hey friends welcome back to my channel i'm here to do a hundred lethal challenge today's we have 118 pascal's triangle so for this question like this triangle demo looks giving a non negative integers num rows generates the first num rows of pascal's triangle and it starts on one and then later you another one and one after one and one so it will be three num row b3 and f3 this middle one will add one and one just like a triangle just keep adding each other you can see the demo right here but to solve this one i take some time to think about the method which is not really looking like this i can show you in here as a test so you start with one so you do nothing because it's beginning the second row you still do nothing you can see in here they have an empty area in here look wait for a second see here see you have the end and this is the thing that you need to feel and the rest of them on the side is all one so see the first top two rows you don't need to do anything but we start doing things in this area which is in row three how we do is we copy one and one from this row and add one in the beginning so it looks like this and this two is equal to one plus one but you can think about uh the cases these two is at one and one here and this one and one actually is moved to this area but we just add one in here just to push back so to align them and this one is equal to current index which is here plus the next index so you will get two so this one will be equal to two if this next one we'll have one two one or this original one and we have the plus one in the beginning so starting from this one the first number at this one is equal to one plus two actually is here which is one at is next number becomes three and in here at x two's next number is just one so become three in here so we only process a number between the first one and the last one then this is the solution and if we need to do n rows time until we reach the end of yeah and rows that's it for this logic comment this out and start coding now we have to make a template output equal to new arraylist this is our output template and we need to use a list to keep track of the current situation let's record two new after that we will loop you need to loop and rows time and in here first we need to do first thing we need to do is a curve we start with one every time we have a loop we will add one at index one so that mean currently curve is empty we have to put one in here so every time we have every row we go we start putting a one in the beginning for everything between the first one and the last one we need to process something which is minus one this is everything between ones and one and what we need to do is set um x equal to curve got x and x plus one after that after you process that one and you just simply put it to the output this array to the output and that should collect all the possibility and in every row and the end we should return output as a result okay it looks good let's submit it okay yeah it passed so yeah this is the solution so if you have any question please comment down and i will see you in the next video bye
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
240
240 search a 2d matrix number two from liquid let's jump to the question and write an efficient algorithm that searches for a value target in an m by n integer matrix this matrix has the following properties so first in first each row are sorted in ascending from left to right and each column are sorted in ascending from top to bottom so this is a sorted matrix that we are going to have and we have a target value that we need to look for and if we can find the target value in the matrix figure are going to return true otherwise we are going to return false uh so the first thing that comes to my mind is using a brute force we use two for loops and iterate over every single item that we have in this matrix but it's going to be the quadratic time complexity and the other thing is we are not using the properties that is given here to us and which is like each row is sorted and each column is sorted so we should use this and for doing that what we can do we can uh you we can use two pointers one pointer is pointing at the bottom row and one pointer is pointing at the first column the reason that we start from here not here is because like we are you looking for a target value right so if the target value is a smaller than these so we can easily eliminate this row right but if the target if you start we start from here if the target value is bigger than these um we don't know it can be any of these rules so we cannot eliminate anything but by starting from the bottom it can help us to eliminate uh some of the rows and hopefully have less iteration and uh so let's go through the code and see how we can do this so the target value that we are looking for is 12 and this is the matrix that is given to us first thing we are going to um have the special cases if there is no matrix or like um we don't like the length of rows or columns are zero so we're gonna return false because there is no matrix to look for a target and then we are going to use two pointers one pointer is pointing at the last row as you see here and one pointer is pointing at the first column as you see here and we use a while loop and we decide how to um a small scope of search by the value that we are pointing at so if the value that we are pointing at is equal to target we're just gonna return that this is the first if and the second condition says if this value is bigger than the target which it is bigger than the target in this case 18 is bigger than 12. we're just gonna like eliminate this row and we decrease um the row value from like let's say this is zero one two three four from four to three so we're gonna point at uh this row and uh what we are going to do uh we go to check to see if row value is um bigger than zero a column value is smaller than the length of the matrix and if it is we are going to check the value that we have here right now is um equal to target which is not equal to target so what they're going we are going to check if the at row 3 and column 0 the value that we have which is 10 is equal to 12 and it is not or we're gonna see if 10 is bigger than 12 which is not so we are going to add the column number here so now the column pointer is pointing at this number and then we are going to check if 13 is equal which is not if it is bigger and if it is bigger we are going to um decrease one from the row so we are going to row number two but the column number still is pointing at one as you see here and now we check two and um index two and one and we see the value is smaller so we're gonna add the column so now column is pointing at um index two and row index two so nine and nine is a smaller so still we're gonna like increase the column number so now the column number is going to be three and row is going to be two and we check this value if it is bigger yes it is bigger so what we're going to do we are going to decrease the row value so now it's going to be one and now we are going to check at row one and column three which is 12 and that's the number that we were looking for so it's equal to target and we are going to return true and this is how we solve it and it's going to be there at worst case it's going to be m plus n m is the number of rows and n is a number of columns so we iterate over every single item and the space complexity is going to be one because we are not using any extra space thank you
Search a 2D Matrix II
search-a-2d-matrix-ii
Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties: * Integers in each row are sorted in ascending from left to right. * Integers in each column are sorted in ascending from top to bottom. **Example 1:** **Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 5 **Output:** true **Example 2:** **Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 20 **Output:** false **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= n, m <= 300` * `-109 <= matrix[i][j] <= 109` * All the integers in each row are **sorted** in ascending order. * All the integers in each column are **sorted** in ascending order. * `-109 <= target <= 109`
null
Array,Binary Search,Divide and Conquer,Matrix
Medium
74
261
today we are looking at lead code number 261 it's called graph valid tree all right so let's take a look at the prompt here given n nodes labeled from 0 to n minus 1 and a list of undirected edges each edge is a pair of nodes write a function to check whether these edges make up a valid tree okay so we have example one n is five the edges are zero and one zero and two zero three one and four the output is true example two and it's five the edges are zero one and two and three one four okay we have a note here you can assume that there's no duplicate edges since all edges are undirected and the same as 1 and 0 thus will not appear together in edges okay so right off the bat what we got to figure out is what is a tree what is the definition of a tree okay and so the definition of a tree is that it is a graph but it cannot have cycles the only difference between a tree and a graph is that a tree does not have cycles so first we got to fig we have to convert these inputs into a graph okay we can do an adjacency matrix or an adjacency list i think if we do an adjacency list we can easily traverse this input and figure out if there's any cycles in the input so that's number one number two is that there cannot be more than one region okay so let's kind of visualize this if we have zero let me use a different color here okay if we have zero and then we have one and then we have two and three and then we have four here this is not a valid tree okay because we do have a tree here but we cannot have more than one region so this will not be valid likewise if it was just a connection from this one to this four this would be a valid tree okay but if we have a connection here between this two and three then we have a cycle here and that will not be a valid tree okay so what we want with this with the valid tree is no cycles and regions are less than there cannot be more than one region so not more than one region if we can have these two elements checked and the graph has no cycles and there's only one region then we can assume that our input is indeed a valid tree okay so let's jump into this and what we want to do here is right off the bat when we see this okay we're getting a list of edges and an input of n so we're getting an edge list we want to just first convert this into an adjacency list that way we can just easily traverse this and we don't have to think too much about it okay so i'm going to just create a helper function here build adjacency list that takes in n and the edges okay now i'm going to actually create my array that i'm going to use that's going to represent the adjacency list from and then here we're going to do a length of n and we're going to set every element in the array in this adjacency list to an empty array and this is a brand new array that's mapped to its own specific place in memory okay we have length here and now what we're going to do is just iterate over our edges and we're going to pull out the source and the destination of our edge so the index 0 is going to be our source and the index of 1 is going to be our destination we're just pulling those out here as we iterate over these edges right over here and we're just going to map that to our adjacency list and because this is an undirected graph we're going to mirror this so as we push in the destination of the source we have to mirror it at the destination we have to also push in the source here and then we just go ahead and return our adjacency list okay and so in the first part of this main function the first thing we're going to do is we're just going to create our adjacency list build adjacency list and edges now for this main function we have to create some variables to keep track of the nodes that we're visiting as we traverse so we're going to have a visited object set it to an empty object and we're going to also have a parent object we want to keep track of the parents and then we need a region and we'll set that to 0. so we want to keep track of everything that we're visiting so we don't visit anything twice but we also want to keep track of the parent of every node that we're visiting and the reason we want to do that is going to help us determine whether we have a cross edge and that's the key to this we have to figure out does this graph have a cross edge if there's a cross edge that means that there is a cycle and if you're still unclear about the different edge classifications i highly suggest reading the chapter on graphs in introduction to algorithms it's that giant book you can find it online and there's a section in there for edge classifications you can have forward edges backward edges cross edges and it's really important to know those different edges and how to figure out whether your graph has those or not okay so we'll just create our main loop here equals zero next is less than you can see the list vertex plus okay and this is all like just basically off a very basic graph traversal template i'm not doing anything new here and if you look at a lot of my other videos i just follow the same template in the same pattern and it's good to have those in your back pocket because then when you see these problems you can really quickly solve them you don't have to think too much so here we can check if not visited then we want to go ahead and first we want to go ahead and increment the regions because that means that we have a region and now we want to check is there more than one region remember if there's more than one region then we do not have a tree and so we want to exit out of this so we can say if regions is greater than 1 return false and now we just have to check is we'll do breadth-first search cycle vertex if there's a cycle from this vertex node that means that we do not have a tree and we're going to also return false and then if we make it through this entire loop and there's no cycles and there's only one region then we can assume that our input is indeed a valid tree okay so now we just have one more function is we have to create this bfs cycle and we're just making a slight modification and we're adding this parent in there that's going to help us determine whether we have a cross edge or not is b fs cycle this takes in a node our adjacency list visited and our parent okay now remember anytime we're dealing with a breadth first search algorithm we want to use a queue okay so we're going to go ahead and create our queue and we'll go ahead and set that node that vertex as the element in the queue and now we want to create a while loop and while we want to keep on iterating over this cube and pulling nodes out of the queue while they're while we have elements in that queue so we can just do it q.length while we have a q.length we're going to while we have a q.length we're going to while we have a q.length we're going to go ahead and pull out that node we're going to shift out that node so we can say cur node okay we want to update our visited and we'll set that to true that way we don't repeat visited nodes that we've already been to and now we want to iterate over all the neighbors we're doing a breadth-first search so we're doing a breadth-first search so we're doing a breadth-first search so we want to check all the neighbors from that current node okay and now we want to check have we been to this neighbor before now we only want to go into this if we have not been into this neighbor so we check if visited of neighbor if it's false that means we have not visited we want to update visited okay and now we want to update the parent right the parent of the neighbor is going to equal the ker node and then we want to add that neighbor to our q okay now we need to check is there a cross edge okay and how do we do that well we have to check does the neighbor and the parent of the current node if they do not equal each other then we can assume that there is a cross edge so if neighbor does not equal parent of per node then we return true okay else we return false and again this is the main part of it right here this lets us know whether we have a cross edge or not if this is true then we do have a cross edge and we want to go ahead and return true okay that means that this bfs does have indeed have a cycle and what i would recommend is that if you're not sure how this works step through the code make a little chart draw it out each iteration by iteration use a simple graph like the input you know three or four nodes and go through each one to really give yourself an idea of how this line right here works okay so let's go ahead and run this and we are good okay so that is valid tree i hope you enjoyed it and i will see you on the next one
Graph Valid Tree
graph-valid-tree
You have a graph of `n` nodes labeled from `0` to `n - 1`. You are given an integer n and a list of `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between nodes `ai` and `bi` in the graph. Return `true` _if the edges of the given graph make up a valid tree, and_ `false` _otherwise_. **Example 1:** **Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[0,3\],\[1,4\]\] **Output:** true **Example 2:** **Input:** n = 5, edges = \[\[0,1\],\[1,2\],\[2,3\],\[1,3\],\[1,4\]\] **Output:** false **Constraints:** * `1 <= n <= 2000` * `0 <= edges.length <= 5000` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * There are no self-loops or repeated edges.
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
207,323,871
567
everyone welcome back and let's write some more neat code today so today let's solve the problem permutation in a string and there's actually two solutions to this problem one is the 26 times n solution and there's another solution that's actually just big o of n now we know that a constant number here doesn't actually affect the overall time complexity but that being said i'm still going to focus on the slightly more optimal solution uh because it's a little bit more difficult but it's also interesting and it's a pattern that's actually used in other leak code problems as well so we're given two strings s1 and s2 and all we want to do is return true if the string s2 contains a permutation of s1 and we return false if that's not the case now you can get bogged down and really confused with the explanation of this problem like focusing a ton on permutations but i'm going to try to simplify this for you immediately without going down too many rabbit holes and let's actually take a look at this first example so we see that s1 is the target string that's what we're trying to look for we're looking for a permutation of this string somewhere inside of s2 can we find it now what does permutation mean well we could actually you know create a permutation of the string which would be really complex and annoying but we see that over here there actually is a substring of s2 and it's a permutation that matches s1 it's ba right the exact same characters just in a different order which is perfectly fine now by the way a b itself technically counts as a permutation of itself so this string is also allowed but since you kind of see what we're really just looking for is there a substring of the exact same size so this is two characters so we have to look for a substring of two characters here right we can't just take three characters and say that's the permutation but you know we're looking for a window same size as this and it has to contain the exact same characters as s1 just maybe in a different order now does that kind of sound familiar to you well it's the same thing as looking for an anagram right we're just looking for the exact same characters we don't care about what order they're in right so it's looking for an anagram so we can actually use a typical sliding window technique we're going to look at every window in s2 that's the exact same size as s1 so in this case length 2. so we're going to look at the first two characters then the next two characters the next two etc until we find an exact match with s1 now if we were actually comparing the exact characters that would be pretty annoying the time complexity in that case would let's say be n times m where n is the size of s2 m is the size of s1 because we're looking at every single window but we can do it a little bit better we can reduce it to be 26 times n if we use a hash map because actually in this problem it's written all the way at the bottom of the description so it's not on screen but they tell us that all the characters in both of the strings are going to be limited to lowercase a through lowercase z so therefore the size of our hashmap is going to be at most size 26. there's only 26 characters so as we build that hash map we're actually going to have two hash maps we're going to have one hash map for s1 which is going to stay the exact same we're also going to have a second hash map for s2 which is going to have the characters of the current window that we're at so every time we create a window right each time we shift our window to the right we're only just adding one character and maybe removing the character that was on the left and then once we have those two hash maps we're going to compare them if they are equal which is a 26 operation right there's only 26 characters and so that's where we get this time complexity from but there actually is a better way this solution is doable it's easy to code up and you can do so if you would like but i'm going to show you the slightly more optimal solution which is actually not even going to have this 26 it's just gonna be big o of n so let's look at the big o of n solution and it's actually similar to the previous solution we discussed we're actually going to still have two hash maps one for s1 so as you can see we counted the occurrences of each character we call it s1 count so we have one a we have one b and one c so we filled our hash map with the same values and rs2 hash map is empty because first we're going to set our window here and then we're going to continue to shift it by one each time but the difference here is we're not actually going to be comparing the two hash maps together we won't need to because we're going to keep track of one more variable we're going to call it matches we're basically going to have a little shortcut initially this is going to be set to zero i'll just create a box for it even though it's just going to be a single value but we might be updating it to other values but this matches variable is basically going to be a shortcut that's going to allow us to not have to compare the entire hash maps each time which we know in the worst case could be a 26 operation having to look through every single character of the hashmaps because this matches variable is actually gonna maintain the total number of equal characters in each of these hash maps and actually even though i didn't draw the entire map for s1 and s2 in this case because actually we know that there's a through z there's 26 characters and i didn't actually draw the entire thing but we are gonna you know fill in the values in the code because we know that the rest of the characters in s1 are gonna be of count zero right and matches is gonna tell us the exact number of matches of each character between the two hash maps so we want to know does the a count of s1 and of s2 match if it does match then that's a plus one if it doesn't match then that's not a plus one right and we want to know the number of matches for every single character and we want to know that initially right it could be 26 matches or it could be zero matches right it could be any value in between but once we have 26 matches that means that for some window in s2 and by looking at it we know that this is going to be the window we know that this window has 26 matches with this window because they both have a single a character a single b character a single c character and for the other remaining 23 characters they have they both have zero of those characters so therefore they have 26 matches that's what we care about and we can do that with a single variable without having to look through the entire hashmap let me show you the algorithm to do that it's pretty straightforward actually so first thing we're going to do is actually just look at the first three characters of s2 and then fill up our hash map so we have a single b we have a single a and we have a single x now you can see that this is what our hash maps actually look like we have looked at the first three characters and now what we're actually going to do for the only time we are actually going to iterate through both of these hash maps comparing each character we actually do have to do that at least one time but it's a single 26 operation so and then after that we'll only have to just iterate through this string so the overall time complexity is going to be n plus 26 which we know is going to be equal to big o of n uh it's definitely better than if we were just doing 26 times n okay so we're gonna look at every character a they both have one b s one has a single c but s two does not have any c's so therefore they have two matches a and b but c is not a match then we're going to look at all the other characters after c and we're actually going to see that yes there is a match right because they both have zero d's they both have zero e's they have zero f's etc but then we're going to get to x okay this has a single x but s1 does not have any x's that's not a match but they both have zero y's and zero z's so all in all they actually matched every single character except for c and except for x those were the only characters they didn't match so actually initially we have 24 matches next we're gonna look we're gonna take our window which was like this and we're gonna shift it to the right by one when we shift it we're obviously removing a character from the s2 window we're removing a b now as we make changes to the count we want to know does it affect the number of matches so here we have one right which was equal to what it was supposed to be in s1 as well but now we're now changing it to a zero so therefore it's not matching with what it previously was matching with therefore our matches total is actually going to be updated now to be 23 we're decrementing it by one okay but we also added a character a y does this affect our matches was this a character we were looking for well let's increment our i by one and we see that now it's one but what was the y value in s1's count it was equal to 0 so now we actually created another mismatch so actually the total number of matches is gonna be 22 now and now we're going to actually shift one more time so this a is no longer gonna be in our window now we're gonna have x y z in our window so we remove the a count is now gonna be set to zero we created another mismatch so our matches count is now gonna be 21 but we added a z so our z count is one but the z count in s1 is zero therefore we created another mismatch so now our total number of matches is actually going to be 20. now let's shift our window one more time let's chop off this x so x count is now going to be set to zero so let's update that x count is now set to zero which is good for us because s1's x count was also zero so therefore we can actually increment our number of matches now right so let's uh set matches now equal to 21. we also added a character we added this a character at the top so let's actually increment the number of a's we went from having zero a's to now having one a and that's what we were looking for right because one a is also found in s1 count so now we can increment our number of matches from 21 to b22 we're getting closer to our goal and i'm gonna kind of fast forward the remaining two spots clearly we're gonna see that the y gets chopped off and then we're gonna be two we're gonna add the b character which is also what we wanted to do right we have one b and we have zero y's so that brings us to be 24 matches and then we're gonna shift one more time uh to be at this last window we're gonna get rid of the z that we didn't really need so now our number of z's is zero that's good that's exactly what we want and we added a c character so now we have one c now we have the exact number of matches we were looking for that our matches count is going to be 26 whenever we get to 26 matches that's our magic number we are going to go ahead and stop the algorithm and return true because all we're looking for is does there exist a single permutation of this in s2 or in other words does there exist an anagram of s1 and there does we found it we return true immediately and we can stop the algorithm that's the big o of end time algorithm now let's actually code it up okay now let's write the code but there's just one little edge case we actually have to look for that i didn't talk about previously and that's if our s1 string is actually shorter or actually rather longer than our s2 string which would make it impossible for us to find a permutation of s1 in s2 in that case we can just return false immediately but after that we can get into our standard algorithm even though i was talking about hashmaps we can actually implement these with arrays as well because we are getting fixed values uh lowercase a through lowercase z and we can convert those characters to be uh integers and we can use those integers as indices indexes of our two arrays so initially i'm just going to set these to be 26 numbers and each of those numbers is just going to be a 0 for now uh we're going to go through every character in s1 and we're gonna go so suppose s1 is maybe three characters long at the same time as we're going through s1 we're also going to go through the first let's say three characters of s2 so we're going to initialize both of these hash maps at the same time so let's do that now so the way we're going to convert these characters so in s1 we're going to get the character at the ith indexed and we're going to use the ord function now depending on your language it might be a different function all we're doing is getting the ascii value of this character with our ord function and we're going to subtract from it the ascii value of lowercase a let's get this right and this will map to an index this will map to one of the 26 indexes and to this all we want to do is just add one to it and i'm just going to go ahead and copy and paste this line and do the exact same thing for s2 we're gonna in s2 count uh we're going to update the count of this character and just increment it by one so now before we actually get to our sliding window portion don't forget we actually have to initialize the number of matches we're initially going to set it to zero but let's compare each of these maps or arrays we know that there's going to be 26 spots in the array so we can actually just hard code that so now we're going to say to the number of matches we want to add one to it only if s1 count at index i is equal to s2 count at index i that's the only case where we'd want to increment this by 1 but if that's not the case then we are not going to increment it by one so we can just say else zero right so else incremented by zero which is the same as not incrementing it at all let's put parentheses here just to clean it up and now we can move on so now we're going to do the sliding window portion we're to initialize a left pointer to be at the beginning so at index uh 0. so then we're going to have our right pointer which is actually going to iterate through every position in s2 but we know we don't actually have to start at the first position because we already initialized our windows so we're actually going to start at the length of 1 the length of s1 because this will start us at the next character that we left off at right and this range is actually non-inclusive so we range is actually non-inclusive so we range is actually non-inclusive so we stopped before we reached this index so now we're actually going to go to that index with our right pointer but remember what happens if matches is 26 shouldn't we return immediately yeah we can put a return statement outside of this for loop but it'll be redundant so we can actually put it as the first statement inside of the for loop so basically if matches is equal to 26 then we are returning true if that ever happens we can immediately return true no questions asked but if it's not the case then we have to update the number of matches we know that we just visited a character at index r and this is the part where you actually might have hoped that you used a hash map rather than an array and that's fine if you want to rewrite the code that i'm about to write using hash maps i think it's perfectly fine but i feel like i usually overuse hashmap so this time i actually wanted to kind of show you guys the array solution even though it's a little bit more annoying because remember our character is not the key of our array we have to map that character to an index and we can do that just like this so s2 at index r uh minus ord of lowercase a so we're also going to take the ord of this because that's how we're getting the index of our count arrays so now we can actually use this index but what are we going to use it for well we know that this character is the character that was just added to our uh window in our s2 string so we're gonna increment the count of this by one but now that we just incremented the count of it by one it could be possible that now it exactly equals the count in s1 so if that's the case if now that we incremented this and now it finally equals exactly s1 count at the same index at the same character then we can increment our number of matches by one but it's possible that also by incrementing this instead of making it exactly equal we made it too large we made it exactly bigger than the target by one that's how you know we have got to actually decrement the number of matches so basically else if s1 count at the same index plus 1 is now exactly equal to s2 count at the index and if this is the case that means they were equal they were exactly equal but we just incremented s2 count by one so now we made them unequal so then we actually have to decrement the number of matches by one okay and that's pretty much the entire algorithm but there's one last thing and i'm just going to go ahead and actually copy and paste this entire block because we're going to do the exact opposite thing we know that we're adding a character to the right of our window but at index l at index left we removed a character so we're just going to replace this with the opposite case right here i replace the r with an l and here instead of incrementing the count we're going to decrement the count because this is the character that we just removed from the left side of our window and here what we're going to say this is actually going to stay the same if somehow by decrementing this we made the counts exactly equal then we're going to increment our matches by 1. but if somehow by decrementing this value we changed it from being exactly equal to now being too small meaning it's now going to be equal to s count s1 count minus 1. if we changed it from being exactly equal to now being slightly too small that's when we are going to decrement the number of matches right so we really didn't have to make too many changes to this block of code but that's actually the entire algorithm except we know our right pointer is being incremented by one each time but we also want to make sure our left pointer is being incremented by one each time as well and after that we are done then finally we can return false well not quite because it's possible that after our loop eggs are exited right the last iteration of our loop we didn't check after that if our matches were equal to 26 so instead we're actually going to return does matches equal 26 so it's going to return true if it does equal 26 it's going to return false if it doesn't equal 26 now let's run the code to make sure that it works and on the left you can see that it does and it's pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Permutation in String
permutation-in-string
Given two strings `s1` and `s2`, return `true` _if_ `s2` _contains a permutation of_ `s1`_, or_ `false` _otherwise_. In other words, return `true` if one of `s1`'s permutations is the substring of `s2`. **Example 1:** **Input:** s1 = "ab ", s2 = "eidbaooo " **Output:** true **Explanation:** s2 contains one permutation of s1 ( "ba "). **Example 2:** **Input:** s1 = "ab ", s2 = "eidboaoo " **Output:** false **Constraints:** * `1 <= s1.length, s2.length <= 104` * `s1` and `s2` consist of lowercase English letters.
Obviously, brute force will result in TLE. Think of something else. How will you check whether one string is a permutation of another string? One way is to sort the string and then compare. But, Is there a better way? If one string is a permutation of another string then they must one common metric. What is that? Both strings must have same character frequencies, if one is permutation of another. Which data structure should be used to store frequencies? What about hash table? An array of size 26?
Hash Table,Two Pointers,String,Sliding Window
Medium
76,438
247
okay so lead code practice time so there are two goals in this video the first one is to see how to solve this problem uh find the solution then you're going to do some coding work and the second one is to see how we should behave in a real interview so let's get started so remember the first thing is to always try to understand the problem and ask some clarification questions in case there isn't any there is anything you don't understand and also think about the ash cases so for this one let's see strobo grammatic uh number two okay so a strobogrammatic number is a number that looks the same we rotated 180 degrees so look so okay so 180 degrees means looked at upside down so find all strobogrammatic numbers that are of length n all right so i think i kind of understand the problem uh and i think the edge case i can currently think about is n is equal to zero then what should we return then i think a is equal to zero then we just return an empty list so let's find the solution so how to solve this problem so first of all we need to see which numbers we can treat as uh like a pair when we look upside down so for once we could have one when i look upside down it is one so one for it nine is for six it is nine for nine it is six and four eight it is eight um if there's i'm trying to think if there's anything else uh i should take care of so it's what two no three no four is no five six we have it eight seven i don't think so seven eight and nine all right so we have the i think we have the zero to 0 stuff so if it is 0 um so of course if n is equal to 1 we can have we will we could return one zero or eight so otherwise um if n is larger than one then we can not really have the zero to appear as the first digit but if n is equals to three then of course we can have something like one zero one so something like that uh so i'll say uh we will need to trade uh and when it's odd um and when n is equal to even so and it could be even or odd so this is something we need to think about and the other special thing i think is the zero stuff so you cannot put zero at the very beginning except n is equal to a one um yeah so i think that's it for yeah i think that's it um yeah sure so let's think about how to solve this problem so we have found all the cases i would say we could define a recursive function uh to find it like enumerate so for each bit okay so one let's say for n so we could define a recursive function like we knew more so for each bit we enumerate all the possibilities but for each bit the possibility if it is starting if it is the first digits when a is larger than one then it could be one six nine or eight so that's a that's finite uh enumeration and uh so for example let's just give you an example let's say when n is equal to three so when you try to enumerate the first digit it could be either one or six or nine or eight so one is uh when it is a second digit it could be one or zero or eight so this so and then when it is the last digit it really depends on what the first digit is so it's like we first try to enumerate the possible other possibilities for the first half and if n is a odd number in the middle there are only three options and for the rest half it really we cannot do any motion it is just based on the first half so i would say that's pretty much about it and if you want to think about the time complexity i would say roughly if we consider just um okay so if we think that each digit can have uh if we think each digit can have five but i mean it's a very rough uh estimation if we have five possibilities for first of the half i would say the runtime is going to be the possibility it's something like this um and to process each of the possibility it takes time a little bit so essentially the runtime will be something like this again this is very rough because it depends on if any is equal even number or is an odd number it's um it's different but in general i think this should be uh fairly correct so the next part is about coding so coding don't be too slow care about the correctness and also the readability so let's get started and do some coding work um so um well if um n is equal to zero then i'll say first of all create this thing let's say uh let's say straw and nums uh straw nums let's say yeah straw nuns has new linked lists all right so if n is equal to zero let me just return control so if n is equal to one then stroll now let's now add a uh this says if this is the thing we could have one or eight or zero um yeah so let's just uh zero or one or eight then we just return the scroll numbers otherwise we need to define a helper function let's say find this dual strobo okay find strobo grammatical so first of all we have we need to pass the end and we pass the index as zero and uh we also need to pass the straw nums to store it uh yes i think yeah i think that's it and finally we returned the stroll now all right so let's try to implement the helper function let's say while this is a or load of the function so this is idx and this is um a list of the string uh what is that this string um this is uh let's just draw nums all right so if um if i dx is equal to uh all right so we also need to have like a time string so this is temp um so if i dx is equal to zero uh we only have one six eight and nine the three options so we are going to say um cars car array options all right so uh i think we need to define the exit of this recursive function first so if idx is equal to n then what we are going to do is we are going to have strong numbers dot add a temp and then we return so if um idx is equal to one then we have several different options so we could have car array cars is equal to the first one is one plus x eight and uh nine so we are going to go through the cars um see in cars and uh you're gonna say fine find strobo grammatic and this is okay so idx is equal to zero then it should be that so this is idx plus one and then this says um so this is 10 plus uh c and this is troll nums all right so um and if idx is smaller than n divided by 2 and then this is like this is this should be returned so if it is smaller than this so let's say if it is four and minus by in divided by two is two so it is you have zero and one uh like this okay so if i did this we have different options car cars are like you could have zero it could definitely include zero there uh so what if it is five so five divided by two is two so we only have zero and one there okay so this it's zero one six eight and nine so we actually could have this all right so if um n is a odd number and um so if n is a odd number and we are actually at there so i dx is equal to uh so it if it is five so if it is five we when we are at two then it is that is zero and one uh so one sorry so when n is equal to three then divide by two is one so we have all right so one and divide it so when n is a odd number and idx is equal to and divide by 2 so that's the time all right so i think i should have it okay so when this uh hose that means it is a metal so we have how many options do we have the zero one and eight okay we have those three options yeah so otherwise it is time for us to find the it is the second half for the string so we need to find the corresponding character from the first half so for example when n is equal to five uh we have zero one two three four when we are trying to enumerate the character at index three we need to try to look at the character at index one so um we are going to see uh we are going to see the character index so car c is equal to uh tam dot car at which is n minus uh index and then minus one so this is a character we are looking at and we are going to switch c and if all right so it doesn't have the just use f so if c is equal to uh so if it is equal to 1 then we need to find the strobo grammatic and the time plus one so else if let's still use which i think um otherwise it's just uh two yeah case uh one so just find the dramatic and then the break it and the four case uh one and six for ks6 um we need to do something like find zero chromatic break um this would be nine um so actually we could have a hash map um which could be it's a map character car character enter um that is equal to car map so okay car map is equal new uh hash map so this one let's say we are going to have car mapped output uh this is one and what else so we have the six to nine and uh eight to eight and the knight to six so you're just going to call flying strobo chromatic on top of tamp plus car map dock at c alright so yes i think that should be pretty much it and uh remember after you're done with coding it's not done you still need to do some testing so the way to do testing is uh if it is not a runnable platform uh you should go through the task case manually explain how this piece is going to work on top of it and also at the same time um explain at the same time do some sanity check on the logic otherwise if it is runnable i think you could just make use of the console to do some testing let's see if okay so if it is oh okay so how should be string okay so if it's two it's okay if it's three is it okay so it's if it's one it's okay i think okay yeah so i think it should be fairly good regarding uh regarding it regarding this piece of code so let's give it a submission all right so it says wrong answer so why it is a wrong answer oh so if we forgot to put the zero stuff here that's essentially why we are so if it is four then let's just run it yeah so we forgot to put the zero into the map so let's do a submission for it again okay so now it's all good so uh regarding the test case setup i would say definitely instead of uh when n is equal to zero because it's special y is equal to one it's also a special thing when n is equal to a odd number and even number so that's essentially what the task is i would set up uh in my test cases okay so that's it for this coding question uh if you have any uh question about this coding puzzle about this solution please um leave some comments below if you find it pretty helpful please help subscribe to this channel and i'll see you next time thanks for watching
Strobogrammatic Number II
strobogrammatic-number-ii
Given an integer `n`, return all the **strobogrammatic numbers** that are of length `n`. You may return the answer in **any order**. A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down). **Example 1:** **Input:** n = 2 **Output:** \["11","69","88","96"\] **Example 2:** **Input:** n = 1 **Output:** \["0","1","8"\] **Constraints:** * `1 <= n <= 14`
Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.
Array,String,Recursion
Medium
246,248,2202
83
hey what's going on everybody so today we are going to solve one of the coolest problem remove duplicates from socialist so this problem is quite good so if you see the like and dislike they show this problem is quite good all right so what we have to do is basically simply like if you remember the last problem which we did is which is remove a duplicate from an array it's similar to like that but uh right now we have the list so we have to perform something in this it's not too hard i will show you this is quite simple the logic which i will show you is quite simple all right so what we are going to do is i will something do like this for example if uh we find if i if right now i am on this one this node and i find the next node is similar then i will simply mark my next node will be this one so i will not go on this one now so this is my next node okay so same thing will happen like uh if i will show you for the uh big example then a good example so if you look at this example this way all right so if you look at this example then we have uh i'm on over here so i see like this one is similar so i will just simply go over there all right then right now i am on here so i will uh say is this similar no it's not similar so i will simply move over here all right now i will say is this similar yeah it is similar so i don't want to go anywhere so i will just end up over here so my the final one is one two three all right guys so i hope this thing uh makes some sense so i will just let me just code it so you can get to know like what i want to say all right so just let me right over here uh i will scare from on this note i will say as a list and this is my pointing me to the head right now this is my initial stage so it is pointing to head so i will say like while list is not equal to null till then the root will run all right and uh in this let me create one base condition first so the base condition will be like for example if list dot next equals to null like if my next like if i'm in the end and like after that nothing is over there then i will simply break it right there is no sense to uh go any further like that because otherwise it will go out of the boundary now i will communicate one if condition if list dot uh i will say like if this dot next dot val is equal to list dot well which we are looking for like or like you can write in the reverse it doesn't matter all right so like uh what i write over here is i will say like i'll just i will explain in the driver so if this is the condition then i will say list dot next will be though next so how we remove this thing because like we are not removing we are just keep skipping that part all right else if uh the next value which you are looking is not similar with the one which we are standing then we will simply say like okay that will be one next so we don't have to skip that so i will say just as uh list door uh list equal to list load next and in the end i will just write to my head all right guys so just let me give a quick run then i will uh show you like what i have written my code if you don't understand till now all right guys so okay so what i written over here is so i just write this is my base condition okay so once i reach in the end once i reach over here i will just simply break it alright guys so now what i have done over here is i'll say like if for example my this well is uh similar to this well then i will just gonna skip this so that's what i did i said like my next one my the next list will be this one so dot next door next means you just keep escaping this one that's all what we have did so i hope this makes some sense to you so let me just give a submission and uh this question is quite simple to understand this is not too hard anything all right guys so if you have still any problem then do just let me know in my comment section let me just give a submit button all right so it's working very good all right guys thank you for watching this video i will see you in the next one till then take care love you guys
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** **Input:** head = \[1,1,2,3,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List
Easy
82,1982
916
hey everybody this is Larry this is day 30th of the July leco day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem word subsets hmm cool uh yeah hit the like button and subscribe man I am up shape and mentally I think I reset that but yeah one thing I've been doing just I've been spamming this as well but uh I've been doing an extra problem every day so you wanna if you feel like these problems are too easy you know do an extra problem with me some of them might some of those Farms are easy too but um for me it's just about doing a new apartment for example I probably yeah I would have done a lot of these Farms so I'm trying to do one that I haven't seen before just for a little bit more extra practice if you will um I don't remember these apartments though so we'll see how that goes uh you know maybe on a subconscious level anyway today's problem is 9 16 word subset you're given two string arrays words one and words two B is a subset of string a if every word in every letter and B of cursor okay so it so we want to see if words uh every string and B outwards have multiple okay so basically we want to see for words two if they say E and O then uh Facebook has g d n o Google as you know and because you know okay um I could return the thing in any order uh okay so that means that yeah I don't know that we need to do anything that uh that you know optimal but let's start with something more naive first right um and just write our skeleton n is 10 to the fifth so I so we cannot do it you know n times F type thing because that'll be too slow so let's think about this a little bit um every letter and this is a subset is a little bit of a phrasing uh all strings and red ones are unique okay and what's two what is which two oh they only gave examples of one nighter which is kind of a crappy example to be honest because you know just explain it but this is a subset of warrior but not of world okay so you can have multiple letters of word too okay um I think so the first thing that we can do for example is that for each word in words one we go okay is this word Universal and the way that this Universal is just by like you know word two maybe in words two and then you do that dot and again of course this is gonna be too slow because this is n times M or however you want to say it um but however you want to say it the way you say it is that this is too slow can I do a little bit of a filter I was um and I think there are things that oh way actually so the length of these things are 10. right what does that mean all right um I mean that allow us to make one optimization right which is that um does have to be in the same order this is not the same order thing okay so which means that for example yeah um okay that's good because then now we can normalize the string a little bit if nothing else um the timing is a little bit tight because I was going to do something like 2 to the 10 because they're only 10 characters you can pre-process characters you can pre-process characters you can pre-process everything you know two to the 10 kind of way each which uh each letter you know possible and not possible um of course that's gonna be two to ten is uh one thousand so that's a Thousand Times Ten to the fourth is going to be a little bit slow um 10 to the 7 is probably honestly in but then you're going to put in a hash table and a hash table even though it's over one it's a it's an old one that adds up uh it probably is actually login but in any case so okay um so those are the two things that I'm thinking of immediately what can I do to filter it all strings in which one is unique um well so we can pre we definitely want to pre-process words too I mean we can do pre-process words too I mean we can do pre-process words too I mean we can do very minimal things with respect to with respect to um with respect let me think about this for a second um I was thinking about something like yeah we definitely could to could pre-process words too pre-process words too pre-process words too but I was just thinking maybe um this is a tricky one potentially okay these mediums are kind of tricky one day maybe I'm just not thinking right uh okay so the first thing that you would do is still like sort these or the normal or normalize these but then what do you do after normalizing them I mean for these with two words it's kind of you know straightforward okay or whatever but hmm let's see time is sweets remember string a and word Step One is universal if for every string in b is a subset of a no I'm not talking about I still think this wording is so awkward but foreign oh wait I'm thinking okay I think one thing I was trying to think is still thinking about this as independent but the thing to do is that because it has to be for every set not every string that means that um yeah that means okay I am just being dumb then um that means that we can build out the every uh almost like at the intersection of order for inverts two and the intersection of all the uh wow I'm just really slow today um yeah and then in this section of what the words and were which two is just going to be something like uh so then now we can normal we can normalize the intersection of each word wow I'm like a little bit I don't I wouldn't want to say I misread this poem but I'm not thinking about this pump uh at all right uh but yeah um because here the idea is that okay if it's satisfied this word how does it satisfy each word right meaning that if we break it down it is you know if you want to say it in a sentence maybe you might have something like now that's it was two and this these are terrible examples the terrible uh of like ABC uh a d e or something like that well in that case to satisfy both this and this you'll you can break it down saying that um the each word has to have one a one B one C and three a One D one e right and Etc um and of course if you think about it these things are end anyway like within the same word you have these n operations if you will of requirements and as a result and some of these you can clearly merge because for example 3A 1A you know uh merges into three a because the three supersedes a superset a bit if you will uh one is a subset of the three a I guess so yeah and then here then we can do um maybe someone like uh yeah Max as you go to and then here for uh okay and see that Keys someone like this right and that'll give us the intersection of all the requirements that we actually want I been struggling a lot with reading lately and then now we can ask if this word is universal by just looking this up really quickly which is um yeah uh which is okay seriously again I'm using calendar but you can just put everything in the hash table is what this is or uh yeah look up hash table uh character by characters what this is asking so yeah okay and see that Keys um yeah okay good as you go to True um if this is we if we have fewer characters then we're no longer good so good is going to force break if good then we put in the answer uh okay wow I took a nap earlier but I don't know I totally misread this formula uh okay this is very well oh we need to compare it with Max not Max the keys in Max not C because the answer the reason why that was wrong is uh is because I'm sloppy but also because it was missing keys that um for example if an a is not in the word we would not do this comparison which is obviously wrong because yeah um let's give it a submit cool and a little bit faster this time I wonder what I changed uh oh I guess this is the same color oh I mean we just set intersection actually I should have maybe done it that way too but maybe it's a little bit slower I don't know um this is going to be linear ish time linear space uh oh wait sorry linear time at Alpha space um linear because for every character in word one we look at it once uh well this part is the word one and this is part L2 um and this is at most o of L which is the length of the word and that's going to be all of uh well in this case is 10 but even if you don't bound it's going to be at most 26 week um or whatever because you know that's the size of the alphabet so this is n plus L um for that reason uh but still I guess n times l in um yeah maybe n times L but linear in the size of the input because we look at each character exactly once really and then maybe a little bit and over Alpha space for the counters um and technically refer it away afterwards so depending on how you define space because obviously the way we actually code it is we allocate new memory but if you really want you could just you know do like a C that reset or something or clear maybe I don't know something like that right um but it's fine or you could just do a for Loop through it um cool that's all I have with this one let me know what you think stay good stay healthy to good mental health weekend is here uh you know hope you enjoy it stay good stay healthy take your mental health I'll see you later and take care remember I have one more question so wait for that one to come out bye
Word Subsets
decoded-string-at-index
You are given two string arrays `words1` and `words2`. A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity. * For example, `"wrr "` is a subset of `"warrior "` but is not a subset of `"world "`. A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`. Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**. **Example 1:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "e ", "o "\] **Output:** \[ "facebook ", "google ", "leetcode "\] **Example 2:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "l ", "e "\] **Output:** \[ "apple ", "google ", "leetcode "\] **Constraints:** * `1 <= words1.length, words2.length <= 104` * `1 <= words1[i].length, words2[i].length <= 10` * `words1[i]` and `words2[i]` consist only of lowercase English letters. * All the strings of `words1` are **unique**.
null
String,Stack
Medium
null
450
hey guys in this tip in this video i'll be going over delete node in a binary search tree so basically this problem gives you a binary search tree um and uh it wants you to delete a node with a target value so um if the value here is three they want you to delete it and you can either move two up into its place or four up into its place um as long as it's maintains the binary search tree uh like where all the elements to the left of a node all the nodes to the left of the node are less than it and all the nodes to the right of it are greater and uh yeah it wants you to solve it with runtime with respect to height of the tree and so yeah i'm pretty sure the problem is fairly simple to understand so yeah so let's get into the solution so essentially what you want to do is you just want to search through the binary search tree as normal because let's say you have like some numbers here um like it doesn't actually matter but uh let's just say we're looking for like three we look at our overall root of the tree and we say oh if three is less than five so we know we want to look over here i'm in this direction um and then we go to the left guy and we see if um that guy's equal to three and so of course um you won't be going over all the nodes in the tree just the through the height of it so that's just like standard um usage of a binary search tree the more interesting part is what happens when we actually find the node we want to delete and um so basically what happens when we find three over here um and we want to delete it so you there's two ways to really do it you could shift the right guy up in there or the left guy up in there um in my solution i shift the left guy it's pretty arbitrary though um so basically what you know that um all the values in this the right guy here in this right guy they'll be larger than um the largest value in this left guy so basically um if we start at this left guy here we can just keep on taking the right like it doesn't matter what's on the left side we don't really care about that we just keep on going right and right because we'll know that's biggest and then whenever we reach the end there's nothing on this notes pointing to whenever we end of it we know this is like the largest value in the left subtree here and then basically we can just grab this right guy we know it's larger than all the guys in this left subtree so we can just tack it on to the end here and point this guys right to uh this right guy here because then we know hey look at this node everything to its right is greater than that which is true and then we after we go all the way down this right thing and tack this thing on to the end um then what we can do is we can just uh point this guy like have this pointer uh point to this guy instead of this three so then that effectively removes three from it and still keeps as a binary search tree and yes let's just get into how to implement this um yeah so by far and away the easiest way to implement this is recursively using um like an exchange x type of scenario where um yeah i'll just step through this logic here so of course if there is no you just um don't worry about it so essentially this is the only important part okay uh well this is the most important part so this is the part where you um traverse through the tree to find the note that you node that you want to delete so if our value is greater than the key we know that we should look at nodes less than it so we um run delete node and just go to the left of it and we whatever this values returns we'll point that to that left so it's like a like an x change x type of algorithm and then you go to root.right and then you run delete to root.right and then you run delete to root.right and then you run delete node and pass in that and then uh basically uh this part this will basically recursively go through the tree until you find the node that you want to delete because it'll just um like it'll just walk through this binary search tree until you find the node with the value that you want and once you see that value like let's say you pass in delete node root dot left and you go to this side here so five you're looking for three you go to the left because you want a smaller number you find three so then what you want to do is you enter this case um what you do is first of all so this part here is the logic where you go all the way down this uh like the left guy of it so if we find three here the left guy is two and then we'll want to keep on going right to find the largest number to attach this four to the right of that so uh what if we find three um here we get the left guy of it and here we also get the left guy of it um just so i grabbed this guy just so i can return it and so then you keep on going to the right after that and then um so this moves um this guy ml he'll start here and he'll keep on going to the right and so eventually ml will be this guy and then um then we'll make that guy's right equal to this right guy so we'll point this guy for this guy's right child will be this guy so it'll also carry over whatever this guy has in his children and then we just return this left guy uh we'll return this guy and then um we'll like we'll make this guy here instead of pointing that this guy will just be pointing to this guy because we returned him because um when you do hear the left equals delete node um when this thing runs and it'll return um this guy's left pointer instead of pointing to this guy it'll point to this guy and so then that's basically just the answer and you return the starting route that you were given because yeah and that's about it so uh yeah we'll submit this um yeah and this is the fastest possible runtime because you're just going through the height of the tree so um yeah it you don't even need to look at all the nodes in the tree you just need to um go all the way down to the bottom of it and uh yeah so that's about it for the video thanks for watching and i'll be back with another video tomorrow
Delete Node in a BST
delete-node-in-a-bst
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return _the **root node reference** (possibly updated) of the BST_. Basically, the deletion can be divided into two stages: 1. Search for a node to remove. 2. If the node is found, delete the node. **Example 1:** **Input:** root = \[5,3,6,2,4,null,7\], key = 3 **Output:** \[5,4,6,2,null,null,7\] **Explanation:** Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is \[5,4,6,2,null,null,7\], shown in the above BST. Please notice that another valid answer is \[5,2,6,null,4,null,7\] and it's also accepted. **Example 2:** **Input:** root = \[5,3,6,2,4,null,7\], key = 0 **Output:** \[5,3,6,2,4,null,7\] **Explanation:** The tree does not contain a node with value = 0. **Example 3:** **Input:** root = \[\], key = 0 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * Each node has a **unique** value. * `root` is a valid binary search tree. * `-105 <= key <= 105` **Follow up:** Could you solve it with time complexity `O(height of tree)`?
null
Tree,Binary Search Tree,Binary Tree
Medium
791
39
hello friends today less of their combination some problem lessees diamond first given set of candidate numbers Kinder's without duplicates and their target number target find all unique combinations intended where the candidate numbers sums to target the same repeated number may be chosen from candidates unlimited number of times all numbers including target will be positive integers a solution cell must not contain duplicate combinations so as this problem only have positive integers so we can try to sum up keep some older numbers but a wench should we stop then we need to find the base case the best case should be when we sum up like this to multiple times then if some is exceeded then and hug it we will stop and try to add their Nexus 3 and keep doing this problem is a classical problem using backtracking to solve it hmm we should notice that so this Candice numbers are actually a set they're done have duplicates so when we are try to choose one number and the do the recursion there keep searching you should err steals start fronds or current a number and though we won't use we just needed to remove the last element in their temporary list so basically we will use backtrack but there is some detail we needed to not pay attention to so let's of it we need a list Adobe result array list there we will call our help function panel just to return this result so let's see how to implement disease to help function okay we will the first parameter will be the results list and we also needed a temporary list we also need the candidate candidates and there are targets also we need an index which means the current starting next four days search so what will this case be when their target less or equal than zero we should have stopped because we will not use another variable to record those accumulates the sum we were just - from this target so sum we were just - from this target so sum we were just - from this target so it's less oh it was in zero this is the best case if the target you go to zero we should our ad this chamber listen to our results but we don't we cannot just add the temporaries because it's a reference which means when X and the can release the changes the results are placed will also change so we just need a snapshot of the current attempt released and their return so this is the recursion part the I will start from the index I less than their candidate can the third stalin's I plus we just add that the current I into their temporary list and do the recursion see we start from the result the temporary and their candidates the target will sub structure these candidates can leaders I and their this index will also be I because we can you see the multiple times and we remove the a Laster element size minus one okay Oh minus one so let's fill this part there will be the result new arrays and there will be the candidates and the target who will be target and the starting net will be zero so okay thank you for watching see you next time Oh
Combination Sum
combination-sum
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** **Input:** candidates = \[2,3,6,7\], target = 7 **Output:** \[\[2,2,3\],\[7\]\] **Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** **Input:** candidates = \[2,3,5\], target = 8 **Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\] **Example 3:** **Input:** candidates = \[2\], target = 1 **Output:** \[\] **Constraints:** * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. * `1 <= target <= 40`
null
Array,Backtracking
Medium
17,40,77,216,254,377
136
hey welcome to this video we're going to solve the code problem 136 single number which is pretty easy to solve it'll give you an array of numbers and you have to return which number appears just once so in this second example 4 is the only number that appears just once so we return the number 4. now even though this problem is really easy to solve i think the technique you use to solve this problem is incredibly reusable and you're going to use it a lot to solve other leap code prompts so this is like a good foundation problem to know how to solve future problems and of course if you like this kind of content be sure to like comment subscribe so more free content comes out and with that being said let's get started so i'll go to my code editor i'll say cons ht for hash table is equal to an empty javascript object and what this hash table will do is create an account of how many times something appears so let's say the number thousand appears four times our hash table will store that the number three appears i don't know 2200 times right of course we can also use this to say how many times a string appears like maybe hello world etc but for this problem we're just counting number times a number appears so let's do this for now and now we have to fill this hash table up with a tally right i'm going to use a for of loop so i'll say four const num you can call this variable whatever you want i'll call it num for const num of nums right because we're going through the input array called nums i'll say const or not cons i'll say h t num is equal to h t num plus 1 or one and literally this single line of code will create a tally count of this so what's going on here well let's say our num here is a thousand right well then we're gonna increase the count from four to five so that's what this chunk of code does but what about this or one operator now let's say a new number appears that we've never seen before like the number one three seven right well if it's the first time that one three seven appears ht num which is asking does number one three seven appear in this hash table object well it doesn't right there's no one three seven in here so this chunk will evaluate to false or undefined or like a false value and the or operator it says if whatever to the left of it evaluates to untruthfully or false we'll use where's on the right hand side so now htnum will be equal to one so let's say up this is the first time that one three seven appears make it the number one because this is the first time it appears and we see one three seven again this evaluates to true and we only run this code and we increase it by one to two so this for loop here creates this tally count and now we'll just say four i'll use a for in loop which if we check the documentation is a really easy way to loop over the keys and values of a javascript object and our hash table is a well javascript object so i'll use a for in loop so i'll just call it for key const key but you can call it whatever you want the use property i'll just use key for const key in hash table i'll say if hash table key right so this value here is equal to one then i'll say return key so i'll copy this head over to leap code and let's submit okay cool so we passed and before we go over the time and space complexity if you like this kind of content i also have paid content on my website of where i go over more complex lead code prompts and we also go over data structures too which is pretty foundational if you want to pass an interview now that being said let's go over the uh time space complexity so time complexity is of n we loop through the input array right so right here this for loop goes over every element in the input array of n and space complexities of n from our hash table right we use this hash table and while we fill it up with values and worst case scenario of that and that should be it for this video and i'll see you guys in future videos
Single Number
single-number
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. **Example 1:** **Input:** nums = \[2,2,1\] **Output:** 1 **Example 2:** **Input:** nums = \[4,1,2,1,2\] **Output:** 4 **Example 3:** **Input:** nums = \[1\] **Output:** 1 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-3 * 104 <= nums[i] <= 3 * 104` * Each element in the array appears twice except for one element which appears only once.
null
Array,Bit Manipulation
Easy
137,260,268,287,389
380
hey hello there today we're looking at this lead coding challenge questions insert delete get Rendon in constant time we need to design a data structure that supports the following operations in average constant time the suite different operations are insert we try to insert a value into the set if it's not already in there so if we just literally use a set this operation is constant already the second operations to remove an element from the set if it's indeed present again if we use a set the membership checking and remove as they all gonna be in constant time so if the set actually satisfy the first two the third one is to do this get render we need to return a rendering element around the current set of elements each element must have the same probability of being returned this one is not so easy this set but it will be super easy you with array because I really have index access to the elements on that so if it's just note down the number of elements on the array let's say that we have six element we just saw a die if it's number one we just returned the first element on the array 1 we can use the number that the random number generator as the index access our to the bottom so with array we can support that the third operation in constant time but for array the insert and remove is going to be a linear time because we have to first do a linear scan so already try to find the value so for that reason we're gonna try to fuse this two data structure together to basically support each other so that the they combine they can support all three operations and constant so obviously the set here just by yourself is not able to bridge this to data structure so we're going to use something that really similar to set which is going to be hashmaps you know the keys in the hash map it's sort of like a set but the value the key value relationship can help to link the hash set to the link list so the key on the hash map is going to be the actual values because we had to do the duplication checks or those kind of things so the values of the key and the key is sorry the key is the value the key on the hash map is the value we try to throw at it and the value associated with that key it's kind of complicated is the is going to be the index on that Ray so that if we indeed in need to remove something from the set we can simply easily remove that from the hash map but for the linked list we have to grab that index and do something to remove it you know in constant time so actually we're not gonna be really to remove it because if we really remove it we're going to do another concatenation with the right-hand side shift every with the right-hand side shift every with the right-hand side shift every elements towards left by one so instead of doing this actual hard delete we're gonna swap that element or is the tail element on the right the real last element on the right and since that this swap it you could be doing constant ID but after the swap we have to update the hash map as well so that next time we're looking for the tournament it's no longer there but it's in this particular previous deleted elements position so we need to basically have the hash map and the linked list and the array sorry in sync with each other so any operation we have to update those by full again get rendon it's going to totally operate it on the array yeah so that's pretty much it I don't think I need to really draw pictures that's a pretty simple so go I got a hashmap and I just getting lazy today so variable name is terrible so it's this Python here again benefits it just append elements to the end and the we don't need to keep track of the number of elements it just called the size the list here is basically a array and the linked list hybrids and it's pretty handy the hashmap it's a dictionary they are all empty in the beginning that's improved documentation a little bit so for insert we can have first do the check let's see that I'll get rendered first because it's I think it's easiest amount all so we just Brandon randomly choose the number from the list from the Python list so that's okay Brendan in constant time insert we do the checking oh here we also need to return the boolean indicator whether this operation succeeded or not so if what is in the hash map that means we wouldn't really do the insert we return false otherwise we'll do some actual work and the return true the insert is going to be we can append on this valley to the end of the link the list here Python list or for array is just going to replace the ends of value very last location with this replace the whatever that random value is this value and update the hashmap so that the next time you want to check whether do we have this value if we do have that where is it on the array this is gonna tell you that I thought that this particular location here so and given that this insertion moment is going to be the tail at the end of the elements on the array so that's insert and then we do the remove first thing first is to check whether we have actually have this value so if it's actually on there we need to do is to do a swap and then to update yeah so let's create an earlier here create a reference so that I don't want to type itself over and over again so what are we gonna do let me actually just draw a picture so let's say that we are doing the lead of not value of four we have something that's tell about six on the array here we have yeah something like this the noted there is the stuff on the hashmap the key value pair are the key on the hashmap the it's pointing to the index where this number four located in the array and we got the other one that's pointing towards that element the six is the TEL element so to actually perform this like there are so many little text box here oh geez what anyway just forget about that one if we actually wanted to remove this for what we would do is to drifting today so we will do a swap not really swap but just copy would be fine so we copy the lost elements Valeo to are here and have six two points here so that's what we do after that we just remove this node with this link and remove the very end and it's ah come on yeah so that's what we do we copy the last tail elements Vario towards this division location and have the last that the key for the last value points to this new location then delete this and also delete the rare loss the body so that's what we do here in the deletion so it would be so the array here at the ball here this is the this is what this is this location the value up to this location we change that to that thing that's the last elements on the on our list you will be the ends elements if you keep track off a number so that's a that's this by doing this assignment that we changed we moved to six would copy the six to this but the particular location the second thing we need to do is to update the value for the key value pairs with the key insta six over there so it will be and the you know the original so this is the link as associate with this thought six we're gonna put that into this location is we can find the index by looking up the volume and yeah and then we're just gonna remove the useless stuff right now so yeah so that's it we copied the last elements value to this location the deletion location and then we update the hash map so the value that's pointing to the original tail is now pointing at this deletion position and we pop the last element from the list also delete this key value association in the hash map alright so that looks right yeah that's give it a try one two does it really should be something like two we have the Rendon set we insert one we remove two because it's not there it's not gonna do anything we insert two so we have one two we get Rendon we get one so we will get Rendon and then we remove one we answer to the only thing that's there is to what we call get Rendon we should be able to return to why I'm not returning to okay let's see and the true forces right true false true or true false true the true forces for right but that the valley will actually be returned as not why is that did I mess up somewhere so if it's a okay I think it's the insertion that's problem if I just insert one thing the rare first thing I append this so the list have become size one and the lens is going to be one then the index does messed up okay to do want to yeah this looks right now as submitters all right oh yeah I messed up with this step so I have to create this Association first then to the update and do this okay I should be more careful but anyway that's this question
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Medium
381
684
Hello hello guys welcome brother video daily follow problem in it online correction tree which aims and objective of this content does not fit for as a result of written test for example it is connected to two to 9 tree nov23 that which No More Words Related To No More Difficult Note Such Cycle In This Case Vanshu Connect This Is It Dozen Reminder Cycle Pred God This Problem You How To Remove The Best Wishes Mosted 238 Remove Discretion Commentary Pansap's Election This You Can Group Also Remove The 123 love you to remove the last witch makes it a point to solve problem solve 120 question ok me too you free me connected to food divine one witch connected to kurla from it twist vada president minute reducers side this cycle reports from one you can come Back to one right from where you can come back to one should no tension no someone will come back to remove from you can not come back to you can only be used for the candidates and candidates can be the words of various problems in the lost in Which is the Order in the Giver Who is Applying for a Date Su Play Beloved Festival City Interview and Wide and Lots and When You Make Corrections and They Should Not Be to Make the Order of Law and Order in Which Is the Best Love You Love you love you two baikunth vote soft lips teacher graphical representation and will see what they are doing ok suryavansh connected to right ok so initially top separate and tourist places two elements After but now one and drop connected fennel liberation loot within 10 minutes okay or watch the video connected two three one two three four one candidate from country to country from this is not from being connected okay so basically graph one To three and set aside from this pushkar dies in na carolina selection of same areas you want to the latest connect 3434 and pattern 123 overall development in patna bihar correction print serial to near forest hotspot of the same thing for course of to this entry through Your 12345 Latest 1414 You Already Have One Two Three Four Connected To India Against Corruption From 124 A Long And Even Last Connection 1234 So Definitely Subscribe E Agree With U Back Side To Zaveri To Manoj Gautam Today Cycle To School Do Spoon During This Way You CAN BE REPRESENTED AS A REPRESENTATIVE AND REPRESENTED BY A SIMPLE 12345 EDDY Austrian Airlines Loss 12345 Debit The Return Of The Day Madam Sundha Okay All On The Side Half Inch Dia Element Honda Motors Jingle All The Note Single Nobody Connected To India Website All The Paranoid Sudhir Way All No Different From What Do You Okay What You Want To You Are Going To Process Fast Subscribe To Latest Dad 121 Basically To You Are You Will Go Towards This Offspring Pickup The Parents To 9 Of Ones Went To Give Anything For Having No Differences Of One Or Two For Simplicity And 182 2.2 Subscribe Now To Video 132 Well Parents 1.30 Parents Units Parents 1.30 Parents Units Parents 1.30 Parents Units Sudhish Kumar And Different Parents Means The Difference Parents Laker Representatives S Part Of Different Family Meets President Over Into Three Do It To Family 323 341 Subscribe To Saudi Arabia * Stop Attack Train To Saudi Arabia * Stop Attack Train To Saudi Arabia * Stop Attack Train Begusarai To The Year In Different From Inside A Small Cycle Of Wheat From Notice To Live Whole Life But This Correction Hai Serial Ko Refer To Make Corrections Worldwide Collection Awake And Independent Of This Wonderful School Festival Notes For Exam Note 4 K Bheda Notes For All Chuttu Na For Parents Also Welcomes One Of This Land In The Middle Of Parental Welcomes One Okay What Is The Meaning Of The Word Connected 4.11 More Connections Between The Quality Connected Pooranmal And Already Connection Records Where Are In The Same Parents OK Notification Ball Cycle OK Twitter The Video then subscribe to the Page if you liked The Rule 10 You 345 Okay Darling Say Part of the Meaning of Between Two Friends Okay Thank You Include 12345 But It's Full 2121 12345 Subscribe The Water Brings Up To Way Strict In History Taste Will Change It's Thoughts Part Too Different It Will Help You They Students Have Fun With Acids And They Make A Great Ones Upon It's Real The Forest Which Will Give It's Okay So It's Better To Choose Which Would Request That E Support You Want To Find Different Facebook Next Time You Want to Find the Pants Off White Widow Admission Process and Want to Find the President of HSU Travel Through Which They Will Take Off Its Husband Travel Through This Will Take You Three Steps for Its Soldiers Will Give Better Time Complexity of This Will Give Better Time Complexity Now Another Issue Travel Through This Website Will Take Steps To Reach Is The President Dance For Kids Four States Should Not Be Too Basic Which No Decide Left Side To Grand Vision No Decide Loop And Left Side Results Included In The Ashwagandha Height Off the Note Weight Should Remain Same and You Can Find It Should Recite Maxims Sudhir and Try Doom Notes Problem Late for Rich Man Subscribe mid-2012 Good Plus Serial Gift From One Officer This Potato Boil More than 120 It's Amazing Love You to Front Of Why the giver is I late to dare given there side effects pizza bread given to withdraw from this element battery element 231 don't forget to subscribe element to and parental already tagged that you can simply do been curved under current acidity Ki problem ko simple and finally you all the best shubhendu subscribe baith pati fearless soul simply aapke detail flashlights ki don't know place for elements trying to subscribe top in the middle of the aggressive aapke ki porn site rating ashland ki and Pendent in final elegant different civil defense department but this time you tried to find the length of department for fluid notes23 What is the rate of wave fight Shri 420 return 1617 subscribe this Video Please subscribe our hua hai ki undeclared and fire i know The problem was that in date of high school pass idol winner problem ok by I miss you a subsidized rates amused to see what will be the end definition of I am tomorrow morning here is that being given and Vijay achi tan left side good to 10000 The 900099 that Mukesh working side and latest update is updated on switch working fine ok no less previous incremental optimization project simple elements in place of define the term cream and assist you can have tried to your voice over to rent from within their lives in future Also Give The Stranger Land Of Every Element Is Mantra Kauleshwari One Elementary But When You Come In Treatments Algorithm Changes What Is The Year To Give Me The Back To Make Egg Subscribe Play List Ko Bajao Hu Is The Singer Smaller Height Complete The Set Hai BJP One so you are to connect p2p force intelligence to the Video then subscribe to the Page if you liked The Video then subscribe to the Page Apni Bluetooth Idles But Improvement Trust Suream Of Speed2 OK Built In Treatment Vid U So now cash withdrawal should be understood that C and High School Gas Service Interver is simple that Spiderman series is working side Bluetooth setting is significant and e
Redundant Connection
redundant-connection
In this problem, a tree is an **undirected graph** that is connected and has no cycles. You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. The graph is represented as an array `edges` of length `n` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the graph. Return _an edge that can be removed so that the resulting graph is a tree of_ `n` _nodes_. If there are multiple answers, return the answer that occurs last in the input. **Example 1:** **Input:** edges = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** \[2,3\] **Example 2:** **Input:** edges = \[\[1,2\],\[2,3\],\[3,4\],\[1,4\],\[1,5\]\] **Output:** \[1,4\] **Constraints:** * `n == edges.length` * `3 <= n <= 1000` * `edges[i].length == 2` * `1 <= ai < bi <= edges.length` * `ai != bi` * There are no repeated edges. * The given graph is connected.
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
685,721,2246
155
Hello Everybody Welcome To My Channel It's All The Problem Ministry Platform No.1 500 Design Effects Upon Receiving No.1 500 Design Effects Upon Receiving No.1 500 Design Effects Upon Receiving Minimum Element In Time For This Post Is Limited To Remove Element On Top Element Minimum Elements In The Recent Example Subscribe - 21000 Channel Recent Example Subscribe - 21000 Channel Recent Example Subscribe - 21000 Channel Free Leg No like subscribe and last first year erring district - to will be only water day or district - to will be only water day or district - to will be only water day or three left call the great man to minimum wishing all three elements - free wishing all three elements - free wishing all three elements - free software to return - than any porn in software to return - than any porn in software to return - than any porn in form will remove the three for absolutely top 100 songs top 10 Tourist NGO And Easy Call The Great Main Fuel Now Only To Our Minimum World Top 10 - 2 - 200 Will Minimum World Top 10 - 2 - 200 Will Minimum World Top 10 - 2 - 200 Will Implement The Channel Subscribe Not Only Not Distract You Don't Like Subscribe And Share Vighn Tractor Minister For The Post Of Top Live To Attempting Or Starting This problem you can wash today interview weather use this tax like library and the language in wealth tax or not doing them in effect 100 list start the first session with rising in library language subscribe our video hai vo subscribe normal operation and colleges in english Medium School Sports Minister Will Just Need To Every Step Question What Is Mean Stack What Will U Will Complete Three Elements From The Minister PK Element Absolutely Minimum And Current Elements Of Water Current Element And Chief Minister Ajay AP PK Element Is The Year So Let's Element Attack It On Medium Minimum Uniform Vanity Van Will Simply Like It And Elements Of Minimum 200 NS 200 Will Check Minimum Between - 26 - - - - - - Up To 20 Minutes Minimum Between - 26 - - - - - - Up To 20 Minutes Minimum Between - 26 - - - - - - Up To 20 Minutes Subscribe Now To Receive New Updates From Subscribe Now To The Last Impression Wooden Get Minute This Is - Two Way Will Send You Can Wooden Get Minute This Is - Two Way Will Send You Can Wooden Get Minute This Is - Two Way Will Send You Can Simply Implement Like My Video And Quality And Subscribe Now Don't See The Story This Time Like Subscribe Like This Is The Year To You And You Will Like And Subscribe Do Not Wick nda minimum bill online maximum that will be coming events to sources say any thing you can find a solution but you want to do you want to the time minimum for solving in the creative works so well check every time is the current element is lunar minimum will b is dip last minimum and updated and how it will work so let's a distance initially it is som minimum is infinitive compare Who initially minimum element is this guide which hair infinitely so and after that will update soon after this condition will oo everything will also adds vaccine 98100 - - - 29 vaccine 98100 - - - 29 vaccine 98100 - - - 29 202 Bihar to insert blast minimum which will Id believe - to hair and when will the will Id believe - to hair and when will the will Id believe - to hair and when will the element Which is the best app for subscription Minimum distance from all evil elements Like Comment The Next To Me Quinn - To 9 Chapter Note Water Element Quinn - To 9 Chapter Note Water Element Quinn - To 9 Chapter Note Water Element Object Will Send - Not To Implementation Again In 2019 Subscribe Object Will Send - Not To Implementation Again In 2019 Subscribe Object Will Send - Not To Implementation Again In 2019 Subscribe Tweet Including School Staff And That And In HIS LIFE VERY * ATTENTION In HIS LIFE VERY * ATTENTION In HIS LIFE VERY * ATTENTION CONSTRUCTOR MINISTER WITH FESTIVAL VYA IS DISTRICT WITH NEW STOCK MEMBER CONSTRUCTOR PARTS DON'T KNOW YOU WILL BE AMAZED SUBSCRIBE AND WILL NOT BE MAINTAINED AND UPDATED WITH POPULATION WILL BE ID PORN KI AND TOP BUSINESS RETURN COMING IN STAGE DOT ELEMENT In the assembly written in this he has also been written member implementation using vansh sexual potency this code vikram point 200 his painting sometime aayenge this letter ko tarzan is type spelling life in a hai honey singh s9 plus you directly lets be confident amavas solution sizzling 100 Babes Hot Operation In Wave And Storing Subscribe Now To You Will Create A 200 Hair Will Create Three Variables Which One Is Valentina Type Dividend Minimum Is Stubborn Nodal Point For Next Notice Like And Subscribe Initially Will Start At No Additional With A New Chapter Of Class 9 Math Explain You are doing subscribe class 9 in which will work properly and which point to do subscribe mode of internet shravan ji node which is later software will update date of birth and death 220 filmy desh ka 12512 valueab start minister also mean ki And this let me start Next this college nursing staff distinction changes reference next member constructor tender notice no evidence for private node subscribe minister will push subscribe channel subscribe 959 recommend will help you help me Chinese slice held within you node of x9 body minimum value will check Maths for him in the current person subscribe and deprivation and width I took population will update play list operation turn on the in come dot busy dot minerals subscribe to 210 will be compile judge take this compile and submit this expel access salts understand this Example with new Udayveer Singh 900 to 1000 is this point internal in the West Indies simply channel subscribe my channel like this which will love you two billion from this point to video like subscribe do not merge minimum - your hair neck do not merge minimum - your hair neck do not merge minimum - your hair neck Point to subscribe my channel like this mb to basis of this kind of bahujan increase in the state from his own this is solution without dresses with solutions also agree like for notification thanks for watching a
Min Stack
min-stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the `MinStack` class: * `MinStack()` initializes the stack object. * `void push(int val)` pushes the element `val` onto the stack. * `void pop()` removes the element on the top of the stack. * `int top()` gets the top element of the stack. * `int getMin()` retrieves the minimum element in the stack. You must implement a solution with `O(1)` time complexity for each function. **Example 1:** **Input** \[ "MinStack ", "push ", "push ", "push ", "getMin ", "pop ", "top ", "getMin "\] \[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\] **Output** \[null,null,null,null,-3,null,0,-2\] **Explanation** MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2 **Constraints:** * `-231 <= val <= 231 - 1` * Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks. * At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`.
Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)
Stack,Design
Easy
239,716
1,817
Hello hi friends welcome back today we are going to year record problem is 30 finding viewers active minutes on ka surya mandir lock for users actions only good and teacher's lock represented by today end year people where is a lock come is having id and time indicate Set user with ID is performed and action add them in time after multiple users can perform execution and sleep and single user can go for multiple options in 10 minutes the user active minutes gives user-defined active minutes gives user-defined active minutes gives user-defined number of units minutes in which usage for Deduction Liquid Minute Can Only Be Counted 151 Multiple Options Updated On You Are To Calculate One Indicated Answer Option Size K Sach That Point 6 And Lies Between One K Inclusive Answer Is The Number Of Viewers To You A Em Quite Check Return Se Are Answers Describe with answer a is going to be starting with wonders why still alive when India got here and this arrangement lock six year notes and what answer is expected from porn let subscribe and have given and find some logic to solve this problem hai to commissioner SIM Example Here And As You Can See The Output Air It's With Wave In The Sense The One Is When User Active Minute One Writes Objective Minute 1213 Day Four Day 5 Near Detroit 125 Is Given Two Years And Have Given All The Activity Of Users Share In Law gives it's 8etude ring so you know a what they are going to your support well then calculate the and user active minutes for example user ID shift from one user ID to 0.50 kamo 510 comodo soft users who have made certain 0.50 kamo 510 comodo soft users who have made certain 0.50 kamo 510 comodo soft users who have made certain actions on second minute That in five minutes and 5 minutes if in duplication time just text only vansh you can take up and fascist hair to per abuse activity minute isro to avoid you know how to handle the duplication share fennel user ID one's user ID zero you can see Into Comma Five Solid c14 User ID One Wear Singh Activity admin2 Hand Minute 300 That's Why You For User ID One Will Have Set Up To Only Is Here A Software Going To Solve This Problem By Using His Map Website The Giver Winter And Its User ID and will have a set of interior and apps special here this is the question minutes for example user ID zero will have actions on two coma five year rights and two come 500 600 800 550 duplicate it will handle it will only Have One Interview Ajit Seth And IF You Look At The Use Vansh User ID Vidhvansh Porn Bittu And Three Years Will Have Set To Just Have A Year So Let's Just Have A Great Year To Come Atri And Will Have To Written In The Best All How Many Like Usages r-day Best All How Many Like Usages r-day Best All How Many Like Usages r-day Arvind Tuesday Active Minutes When You Can See Users Who Have User Active Minutes Two Rights of Michigan Minute 8 Minutes Service Portal 2 Minutes See Ujjwal Active Similar User ID One is Also Active for Two Minutes Which is the Second Minute and Third Minutes And Diesel Total To Minutes Soegi Sugar Syrup Effigy Group Name With All User Activity Minute Student Will Have To Use A Share Point To That 512 Enter Only Two Father For The Second Item Girl Picture Is Very Best Actually Shoulder Shul Printout Food And For Remaining Half Entries 304 pimple other is no user app from active minutes ago when your right nose or active minutes 1345 plight hui winters who hair show the same logic point implemented festival air ingredient implemented servi short of villagers define the recent visitors were going to you know how to Other member answer is a edit while elements with a verse and will find the map wear appropriate we of key interior and value from this top funders dry this video giving to capture user ID share and has stopped in teachers men's wear going to capture the user Active Minutes Year So You Know Like Users Active Force Second Minute Third Minutes OA Give Winners Other Software Into-Do Through The Like Other Software Into-Do Through The Like Other Software Into-Do Through The Like Share And We Are Going To Capture User ID And Minute Clear And Will Make Us Top Into The Map For The User ID This user is not dare will just create now new here state and will head for which day is active and will examine the entry into river map containing entry for the user ID shoulder specified dare devils retrieve the state from the map and wherever you Minute par and will again put the map of the entry back into the map heard and map ready day and Bihar police arrested to the map using a grater and they will get the entry of interior and safe in teacher a key and boy jewelery interest 10 And will get the size of the self just size of the set will give us a how many minutes lettuce were active for example here in Dishaon one in this case users active for 2 minutes side so let's get here and sincerity only one based Exam Hui Hai Business Tracking Vansh So Edit Arrangement Character Result BCom Result SUC The Results Starting From One Actually Mins User Activity Minute This One Heres And That's Why You Have To Subtract 1Share Yes And Will End In Just One Result So Let's Check The implementation of to the two examples and a systematic and it's Mexico that allergic works only examples of 108 giving us the correct answer so STRs on the discussion see the two is coming year default it's like and to activity for like to activity minutes For This User Security With Correct Result Español Discussion Should Submit This Solution That This Research Solution God Accepted So This Is The Way Can Solve All The Finding That Uses Active Minutes And Its Problem 1817 On Dilip Code Wikinews Them Samay Pendra Set To Solve This Problem IF You Like My Solution Please subscribe The Channel And Click On Like Button Also Put A New Problem Solution Notification I Don't Like The Poster Its Solutions To Problems Related Interview Questions And Answers You Are Interested In This Material Subscribe To This Channel Thank You
Finding the Users Active Minutes
calculate-money-in-leetcode-bank
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Math
Easy
null
1,361
hey everybody this is Larry this is me doing an extra prom on December 1st about 2022 I don't know if I have to think about the year but um all right let's do a medium one today because I'm kind of just warming up for the Advent of code let me know if you're doing the admin of code if you don't know what it is just Google admin of code I guess um okay so yeah let's and now that I premium it I might do a premium one so I my apologies if you don't have premium but you could you know we could all look at it together is this how this is actually not a premium one is it because I don't see a premium logo I don't know if that's true so I don't know but let me know uh if it is but anyway so today's bonus question from Larry is 1361 validate binary tree notes so you have n binary tree notes I'm zero than one you have a left child I why we don't show if only all given note from exactly one valid binary tree okay so what does this mean um okay so we have to figure out um what does it mean to be a binary tree is the root always zero note that the notes have already okay fine um but the wood always true zero I guess not in this case um and you can have a case where um I guess just three but copy this case where um yeah negative one and then that should be yeah okay fine that should return true right okay I just want to make sure so then now first of all we have to find the root of the problem get it but um yeah so what does it go negative one four um index left right and enumerate left child my child let me make sure that I'm recording okay uh okay so then if left um is equal to negative one and white is equal to negative one then root is equal to index um maybe um what I mean is that if root is equal to negative one whoops temperature is equal to index otherwise we have two roots and then you want to return Force right um otherwise wait don't mess that up no yeah huh wait I did mess that up because negative one means that yes so it means that it is a leaf not that it has no child so I messed that up okay uh let me actually put in the test case to um confirm what I said before so this is actually zero then confirmed that this is still true okay fine we turn one or two um oh I just needs to be a sip okay so this is still true I just want to make sure that's the case okay I think I messed up with the root um root is basically the one where there's no in degree right so we just have to maybe measure the in degree as well then um as you go to zero times N I like big ends and not lie um so yeah so okay let's rephrase this one so then in degree of left in command by one and degree of Right Where I'm on okay we didn't actually need index on this one forget um so let's take it out so we will need it again so yeah um maybe I don't know uh oh I had to do some checks on negative one actually but I but otherwise this is mostly good other than the tough cases uh this is other than the special case this is almost good uh okay so then now we just for um for index in range of n right so if in degree of index is equal to zero then root is equal to index if root is equal to negative one else return Force right meaning that we have two Roots okay so then now we have this rule then we just have to go um go down the tree right just a defrost search so yeah I mean I don't think that's bad so yeah just traversal Traverse um yeah and here we can just do you know current node and parents maybe or parent um and then basically a Traverse like a Spell correctly um left of node Traverse right no wait something like this um except for basically um you can go backwards but if you have seen the know that you're going and that's no bueno so let's kind of set it that way so basically we have a scene array um and you can pass it and be like I don't know it doesn't really matter times and right so scene of root is equal to true um and Damage Reverse negative one I guess we don't need the pound in that case I thought maybe we could prevent it from going upwards but it may just have a like a three node psycho or something like this right so we just have to make sure that this there's no uh no thing so yeah so if scene of left of foreign then we return force or something like this right um yeah if not then we return first um I guess we could have combined into one statement let's do that alone copy and paste you know otherwise this is good so let me just return this maybe um it's not quite yet I think that's mostly right but can you have multiple can you have notes where I guess notes could be off by themselves right so I think that's the other one um that's what I mean by so and or seem so if we've seen everything then that should be good I think a scene of love no just another no left child whoops foreign look n is 10 to the fourth it might not be the that's annoying oh well no that's I mean I don't know that this is good enough but it still this is still very well um because we forgot to um we forgot to set the scene thing okay so this is wrong still but um let's see why is that so I this is returning Force do I have a typo anywhere let's see I misunderstood it zero one two foreign why did I do it this way didn't I oh I mean so the answer is that I thought we I thought I checked for this did I checked for it somehow maybe I guess I checked for here instead whoops uh you know I just forgot to check for negative one okay so let's give it a submit uh it looks good um this is linear time linear space we look at every node once both in the traversal I mean that's just how traversos you know generally go I don't even complicate it so it looks every node once linear space because of the scene away and I think also the in degree away and of course this is linear we just look at each node once I was quick on that um so yeah um yeah linear time linear space that's all I have with this one so let me know what you think um yeah if you don't have enough good luck uh otherwise uh also just good luck in general I hope y'all have a great rest of the December so yeah come hang out with me stay good stay healthy to good mental health I'll see y'all later and take care bye
Validate Binary Tree Nodes
tiling-a-rectangle-with-the-fewest-squares
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem. **Example 1:** **Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\] **Output:** true **Example 2:** **Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\] **Output:** false **Example 3:** **Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\] **Output:** false **Constraints:** * `n == leftChild.length == rightChild.length` * `1 <= n <= 104` * `-1 <= leftChild[i], rightChild[i] <= n - 1`
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
Dynamic Programming,Backtracking
Hard
null