video_id
stringlengths
11
11
content
stringlengths
0
123k
datetime
stringlengths
19
19
leetcode_number
int64
1
2k
thumbnail
stringlengths
48
151
title
stringlengths
9
106
9vo9NgIXifY
Have Yes Anokhe Showk The Last Question Is What Is And Given String Guess You Are What Is And Given String Guess You Are Alone To Convert Into Your Pendrive Alone To Convert Into Your Pendrive Wedding Characters In Front Of Written Test Wedding Characters In Front Of Written Test For This Page You Can Perform In This For This Page You Can Perform In This Transformation Activist Arundhati Subscribe Subscribe To Ajay Ko Main Vihave the Vihave the Vihave the telegraph m&a singh neetu restore unit-2 telegraph m&a singh neetu restore unit-2 directors in front of latest ring to make directors in front of latest ring to make top and share and subscribe is top and share and subscribe is missing from hair soft straight judge david missing from hair soft straight judge david warner ne vivar jhal ka on that and no basis on distic comes up and and no basis on distic comes up and throne on that Before pickup intro for Before pickup intro for Before pickup intro for tailing will shoulder last and alerted in the forest similar to hair gel abcd term for 416 how to make a talent term for 416 how to make a talent from ap state unit to add car actors from ap state unit to add car actors in front of 800 mist this is the largest in front of 800 mist this is the largest river sand river sand river sand that unknown to quarter inch pct is notification place was 500 this question clear jhal that Anita out about this question Ajay got this cream ok 100 uneven part fast and jhal number wise post jhal number wise post jhal number wise post middle character husband is James and to reach the middle character in this tree again later you a Bluetooth settings at home I also tank process for door and speak only book which will have to front of to reduce 1.8 these 1.1 to reduce 1.8 these 1.1 to reduce 1.8 these 1.1 19 March we dandruff center point at which will 19 March we dandruff center point at which will move into a tight loot abcd hui all that this move into a tight loot abcd hui all that this whole numbers bar different back whole numbers bar different back side saw tve divya point mintu phir bhi now side saw tve divya point mintu phir bhi now papa par banner1 middle aged person's papa par banner1 middle aged person's nodal center of the spelling of kal subah movie.com hai honey letter even today notification no how to decorate a picture is worth a good example of a great 6162 ki a new 2019 add karo to 20 the ab to pakka yaar main bhi point to b ab to pakka yaar main bhi point to b Relative Center Director Around You And To Relative Center Director Around You And To Win Or Lose Weight Reduce's Nodal Center Of Win Or Lose Weight Reduce's Nodal Center Of Time Is Serious Bill Then 0.2 Now Inducted Time Is Serious Bill Then 0.2 Now Inducted Yes Or No A Message Can Appear To Center Of Problems Traffic Point To Absolutely Ki Abhi Ko Return Of Ek Abhinav Shyam Gupta And Long Span Ek Abhinav Shyam Gupta And Long Span Room By Going Through Each Not Every Digit Legs Jhaal Suno And Vinod Nishad Long Spiderman To-Do List Of The Day To-Do List Of The Day Network Restaurant Front Of This Video Network Restaurant Front Of This Video Shoaib button long distance from this riot Shoaib button long distance from this riot victims and related to edit and of the victims and related to edit and of the character of the greatest threat with me to character of the greatest threat with me to vs 801 Twitter The resources for the vs 801 Twitter The resources for the tractors fluid Yashwant Singh and tractors fluid Yashwant Singh and subscribe bf badhi hai subscribe bf badhi hai ki sunidhi to make cup me to find index ki sunidhi to make cup me to find index and it British Creating The Equal Pay For British Creating The Equal Pay For Equal String Fix Hai Equal String Fix Hai Yahaan Par Jam Par In Us Govind Desh Ne BBA And This This Yahaan Par Jam Par In Us Govind Desh Ne BBA And This This Is Not Equal To This And Is Not Equal To This And Effects Or It Will Be In This Again Effects Or It Will Be In This Again Devgarh This Is Mean Equal Spring Switch Devgarh This Is Mean Equal Spring Switch Mix Mix Mix but adams print click which is vansh drink in business meeting of electronics and after doing what ever that this witch mince in twenty-20 match that pinky is saroj hai ajay ko Samudra Approach Samudra Approach Samudra Approach Awadhesh Awadhesh Intense Pain In Different Awadhesh Awadhesh Intense Pain In Different Algorithm Typing Notification Maurya A Algorithm Typing Notification Maurya A This Suit Dress Algorithm Is Boot Age It Is This Suit Dress Algorithm Is Boot Age It Is Finding The Meaning Of Meaning Finding The Meaning Of Meaning That Assembly Interception Of Tractors That Assembly Interception Of Tractors Ideas Already Existing Udaipur And Ideas Already Existing Udaipur And Suez Not Reply Teacher Protest Against Suez Not Reply Teacher Protest Against The Solution Doing British Midlands Experiments The Solution Doing British Midlands Experiments Se Se 2019 News About What Is Pendu Shifted To 2019 News About What Is Pendu Shifted To Tomorrow Cricket Find Ujala Settings Match Play Ajay Ko Ki MP3 Jhal MP3 Jhal Ek Photo Fasting Sonu Nigam My Company Will Sell Ccl2ncl That C Triplets Loot Jhala Hai Because A Hai Because A That personal enmity is an example, That personal enmity is an example, scientific half, I became the subject of late, revolution and collector hanged setting on pass Mukesh WhatsApp if Justin Hayward Top 10 Hot Trend Map Stuart Broad Triangle Matching Kind Lattu Medical Tha Very Fast Lattu Medical Tha Very Fast Lattu Medical Tha Very Fast Track Court Constituted Talk About Okay Sorry This Track Court Constituted Talk About Okay Sorry This Plate Media's Rights Or It's More Plate Media's Rights Or It's More Clear To That Person's Life Character Clear To That Person's Life Character Witnesses To Start With Correct Apps That And Will Expand Around A The Correct Hai But Is Highlighted [ __ ] Will See That We Can not live for others like nothing one left stopped but dozens of this tempered glass option stopped Darauli this point not correct correct correct half of the Khas Khas Khas were the Indian left no who can provide no were the Indian left no who can provide no OK to the longest born in a correct Nov OK to the longest born in a correct Nov 21 my voice should wake up please like share my voice should wake up please like share address for 800 like but one should visit to be tried to address for 800 like but one should visit to be tried to know anything what is quora ok know anything what is quora ok then message this text call me on whatsapp subscribe channel like and share with oo loot This Position Images Dhan Dhana Dhan This Position Images Dhan Dhana Dhan This Position Images Dhan Dhana Dhan Goal of One Month Left End Images On Goal of One Month Left End Images On Handed Over to WB Board at This Point Handed Over to WB Board at This Point in Exams Page OK and Defeats in Exams Page OK and Defeats Pass Is Dam Good Baby Pass Is Dam Good Baby Mein Rake Vikas and Print Media 10 Point Mein Rake Vikas and Print Media 10 Point Ek Lagi Hai Be Continued Support and Go To Ek Lagi Hai Be Continued Support and Go To Special So first of all we single Special So first of all we single character and subscribe testing tools witch again in the character and subscribe testing tools witch again in the mid-1960s Subscribe Music] Music] Alarm clock off in cases in the crowd Alarm clock off in cases in the crowd control OK now we can apply this approach a done control OK now we can apply this approach a done Is That Is That Is That Across Introduced With First Character Across Introduced With First Character President Doctor Injection Always Been Looted President Doctor Injection Always Been Looted Light Subscribe With 100 Light Subscribe With 100 I Must Sanitary Napkin Rome Ok Business Check I Must Sanitary Napkin Rome Ok Business Check Water Left Most Wanted To Right In The Water Left Most Wanted To Right In The Middle Phase Considered As A Valid For Middle Phase Considered As A Valid For Android Starting With A Android Starting With A Torch Light Business Torch Light Business Torch Light Business inside a specific playlist them noida plot solar trusted usa it's absolutely a to whatsapp whatsapp first calculated sea voice character that den are you take two to credit the match loot reddy so that doctor left most Voor for Voor for Voor for B.Com 2nd ed B.Com 2nd ed ko call light to but ride point amazing ko call light to but ride point amazing edit ok ok sorry k not included in this edit ok ok sorry k not included in this app was left to enter into someone on app was left to enter into someone on half hour bcd on this occasion enroll 120 half hour bcd on this occasion enroll 120 prom left side but half but definitely not prom left side but half but definitely not to that its balance and this left or that its balance and this left or right is layer create new bank of baroda right is layer create new bank of baroda dance class 9 pass loop control dance class 9 pass loop control that tub that tub were correct in coordination settings pimples or before Deccan Odissi rise because they want readers with show Jaipur Via Back To Loot Quantum Wife In A Room Near Me That Area Difficult Kevin Question Is That You Find A Palindrome Date n't Forget And Inspector Mist Or Dying To Stop This n't Forget And Inspector Mist Or Dying To Stop This Thank You Need To Be The Thank You Need To Be The Scripters In Front Of You Scripters In Front Of You Scripters In Front Of You subscribe button more answers a ki yeh ko iodine se bhai dainik bbm surya surya ki england ke internet and dj dynamic ki england ke internet and dj dynamic please is dish answer because only for please is dish answer because only for starting index 8.2 all characters starting index 8.2 all characters hai android airtel mein se perfect ok to hai android airtel mein se perfect ok to lagne se lagne se lagne se cannot be considering a light yes your body diet.st that summer Ganesh Chandra Bose death in the attack took place Pandey AB Dhindsa Sudarshan Reddy Shiva Reddy channel subscribe also because so and Milegi keep repeating the because so and Milegi keep repeating the Repeating It Will Be Found What Repeating It Will Be Found What Is The Left And Right Wanted At Is The Left And Right Wanted At That Time So In This Case Too Left And That Time So In This Case Too Left And Right To Interact Which All Like It Back Right To Interact Which All Like It Back To Travels Remaining Spring And Reverse To Travels Remaining Spring And Reverse And Rooted In The Beginning Light On And Rooted In The Beginning Light On Shri Krishna Sudesh Ne Shri Krishna Sudesh Ne Shri Krishna Sudesh Ne Romes Long Span Ape And Giving Ka Stand Near The First Character Always Need To Bind Songs Control Beach Eliminate Toxins Defined In The Middle And No Like Joe Whats Is The Left And Right The Forest And Losers Okay To Dushman Possible approach for school project discuss was guava example guava example also talk about the bill river to river also talk about the bill river to river system text that this hai system text that this hai also has reverse swing also has reverse swing but right left side by side this is but right left side by side this is that 16 This is the first Indian river and you are that 16 This is the first Indian river and you are Member of an American Person First Springs River and Ganges Water Wasted Tuk Tuk Tuk On Hai What Is Whose And Sorry Is Happen Happen On So This Holy Shrine Server On So This Holy Shrine Server Introduction Like the first one I have this Introduction Like the first one I have this alarms alarms alarms explain notification comprehensive off pm meeting matching date seems like a pivotal practical what is the current spring collection spring is equal to that do it handed bf video of notes and matching where team take the Banner setting boyd sorry Banner setting boyd sorry Banner setting boyd sorry for example diff between for example diff between start with dr to the last date 8th of being start with dr to the last date 8th of being drafted in the western wear or drafted in the western wear or moving and point up in the independence moving and point up in the independence reverse swing or points its intention reverse swing or points its intention and police are investigating point is the and police are investigating point is the last second last point you amazon last second last point you amazon last second last point you amazon Matching The Best Friends Rotting Hormone Taste One To Three And Looked So What You Want To Say 0.2 A Literate Over The Given Spring Is Party But Their Time So Subscribe Subscribe To The Channel Withdraw From The Subscribe This Is Notified For The Giver Torch light in the match with the last character of the Torch light in the match with the last character of the river system is your performance correct the river system so let's lagi lights ago that when give in the match with java expand the screen to days dating the spelling of and one light of baghwa and boy Is the last Is the last Is the last that soldiers match topic Dabang Possible that soldiers match topic Dabang Possible answer is what happened track that in three districts will that 1000 bill deposit Clans lights S2 is done What is the servicing and matching twitter Jhaal ok to aap spring is black three torch light to middle egged in the last three character doubles match it is known that Bhojpur district which services roadways bus soul is taking Dashrath Singh from being a us soul is taking Dashrath Singh from being a us looking for years baby bluetooth is that looking for years baby bluetooth is that it is closed it is closed it is closed electrification will remain different wife husband ok to variety 6 sava me blazo cent and have a good intention quantity me three characters from the fastest growing in the last three crush beauty vs England test match hua to credit the Water Water Water portal's tech for tractors, portal's tech for tractors, remember that Salman gave Bollywood aspiring remember that Salman gave Bollywood aspiring directors directors a nod in his eyes, those directors are judgment from Amazon, yes gas laga hai 500 bhi tushar same to the gas laga hai 500 bhi tushar same to the best answer bhi contact AB this is ok and avoid best answer bhi contact AB this is ok and avoid concept character hai concept character hai to to to debit one bowling wash absolutely digit stay in match after match then this is the best answer divide of dedicated facility holy string into being elected testing lineage tractor time start with a good married with river spring from And Malefic And Malefic And Malefic Placement Can Also By This Time You Know What This Is The First Rain Day Gift A Look At The Bottom In Character Reverse Know What This Is The First Rain Day Gift A Look At The Bottom In Character Reverse Embraces This Is To Reversal Juice And Debit The Embraces This Is To Reversal Juice And Debit The Front After Seeing A Or Fax Suman Saurabh Kushwaha Approach To Comparing Subscribe To That Comparing Subscribe To That Comparing Subscribe To That Difficult Method I Will Tell RTI Difficult Method I Will Tell RTI Activist Disha Relative Reverse Yeh Ek Activist Disha Relative Reverse Yeh Ek Bittu Correct First One Electronic Bittu Correct First One Electronic Electronic Electronic And Tractors Okay So Let's Get Se The Length Electronic Electronic And Tractors Okay So Let's Get Se The Length Of The Best Of The Best Industrial Considering A That Industrial Considering A That Baalveer Matching Isk Ulp Pher Mein Baalveer Matching Isk Ulp Pher Mein Hai To Kis Jhaal Ko hua tha hello viewers comparing the loot ishq train meter loot pintu singh jo hair and 270 days on between like and two boys pesh kiya mein ruke so director lage bhatkne ka chalan se na ho how to take right the longest possible Rome Okay But Doctor Too Too Too Too That Rome Okay But Doctor Too Too Too Too That Rome Okay But Doctor Too Too Too Too That Substring But Bloody Were Given A String Is Substring In Difficult Words Have Sprung Is Present In A Given String And Just This Championship Candidate But Man Time Order Off And Time 11016 Camps For Attraction To Positive Approach Witch Positive Approach Witch Positive Approach Witch Mentions For The Longest Final Long Span Mentions For The Longest Final Long Span Job Taking Water Open Time Taking And One Job Taking Water Open Time Taking And One Character And Taking Into Practice Upside Down Character And Taking Into Practice Upside Down That Electrolyte Crown Under String That Electrolyte Crown Under String Stopped Candy Crush Totally Different Leo Stopped Candy Crush Totally Different Leo Championship Servicing K Play N Championship Servicing K Play N Flashlight Off Shifted To 10 Of Flashlight Off Shifted To 10 Of Springdales Matching Decimal Servicing Springdales Matching Decimal Servicing Springdales Matching Decimal Servicing message Character Directors' So So Let's Get Confused If Teams Read About Championship In Allocated for Discussion Quiet Let One Mode Turn to School Management Cell Turn to OK Vishal Gotan Se Used to Find a Longest Talent Rome Cook in Time of Death And that's the mp2 battu solution service that gives me a good thank you thank you
2024-03-22 10:36:52
214
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode [214] Shortest Palindrome
iBXFUP8p5RM
[Music] hey how's it going on race so in this hey how's it going on race so in this video discuss about this problem video discuss about this problem reconstruct I turn already given a list reconstruct I turn already given a list of airline tickets represented by pairs of airline tickets represented by pairs of departure and arrival airports of departure and arrival airports reconstruct the itinerary in order all reconstruct the itinerary in order all the tickets belong to a man who departs the tickets belong to a man who departs from JFK does the itinerary must begin from JFK does the itinerary must begin with JFK a couple of points to note over with JFK a couple of points to note over here is that the itinerary that we done here is that the itinerary that we done must have the smallest lexical order and must have the smallest lexical order and we need to use all the tickets only once we need to use all the tickets only once so let us consider one example first so so let us consider one example first so over here we are given a list of pairs over here we are given a list of pairs so if you see it means that there is an so if you see it means that there is an airport mu C and an airport la chart and airport mu C and an airport la chart and there is a direct flight from mu C to there is a direct flight from mu C to lhr similarly there is a direct flight lhr similarly there is a direct flight from JFK to MU C so if you consider from JFK to MU C so if you consider these airports as nodes and this pair as these airports as nodes and this pair as a directed edge so basically you will be a directed edge so basically you will be able to find a graph out of it and we able to find a graph out of it and we basically have to have done the Eulerian basically have to have done the Eulerian path of the graph so it's not given in path of the graph so it's not given in the question that we have to attend the the question that we have to attend the unit in path but basically this unit in path but basically this reconstruct the itinerary in order this reconstruct the itinerary in order this means you didn't but only I know means means you didn't but only I know means it's kind of a weird explanation that it's kind of a weird explanation that they gave but they are expecting us to they gave but they are expecting us to find that I didn't work find that I didn't work so first let us try to figure out what so first let us try to figure out what is either in path and how to compute it is either in path and how to compute it at in path photograph okay so this is at in path photograph okay so this is the definition of a written path I have the definition of a written path I have taken this definition from Wikipedia taken this definition from Wikipedia so in graph theory and either in trial so in graph theory and either in trial or rewritten path is a trial in a finite or rewritten path is a trial in a finite graph that visits every edge exactly graph that visits every edge exactly once allowing for division inverted Isis once allowing for division inverted Isis so let me take some examples first so so let me take some examples first so let us consider a simple graph this is a let us consider a simple graph this is a this is B and this is C so for this the this is B and this is C so for this the hidden path is a b c so if you follow hidden path is a b c so if you follow the Silurian path that is a to b and b the Silurian path that is a to b and b to c then you are able to cover all the to c then you are able to cover all the edges correct so this is what our edges correct so this is what our requirement is we have to cover all the requirement is we have to cover all the edges so let me just take a better edges so let me just take a better example as well let us consider this example as well let us consider this example we have a then we have B we have example we have a then we have B we have C we have D C we have D and we have and E is good over here and we have and E is good over here correct so for this the Eulerian path is correct so for this the Eulerian path is going to be something like a b e b c d going to be something like a b e b c d so just follow the spot a to b then we so just follow the spot a to b then we have b e there is we cover this edge have b e there is we cover this edge then e b this is we cover this part this then e b this is we cover this part this edge then to C so we think about this edge then to C so we think about this edge then to D so we cover this French edge then to D so we cover this French so we have covered all the edges on so we have covered all the edges on going through this route so how to find going through this route so how to find this route so what we can do is we will this route so what we can do is we will apply DFS only so let us consider the apply DFS only so let us consider the DFS is starting at this point correct so DFS is starting at this point correct so we have to apply DFS and we have to just we have to apply DFS and we have to just modify a DFS only a couple of modify a DFS only a couple of modifications are required to find the modifications are required to find the sealer in path correct so what we are sealer in path correct so what we are going to do is so let us suppose we are going to do is so let us suppose we are starting a DFS at this point so from a starting a DFS at this point so from a we will move to B now the modification we will move to B now the modification is so whenever you are visiting a edge is so whenever you are visiting a edge you have to mark that it basically you you have to mark that it basically you cannot visit any edge multiple times cannot visit any edge multiple times because it is given in the definition as because it is given in the definition as the left we have to visit every edge the left we have to visit every edge exactly once so somehow you have to mark exactly once so somehow you have to mark this edge that we have already with it this edge that we have already with it this is it into this edge so one thing this is it into this edge so one thing you can do is you can actually remove you can do is you can actually remove this edge from the graph so that you this edge from the graph so that you won't be able to visit this edge again won't be able to visit this edge again so so let us suppose that our DMS starts so so let us suppose that our DMS starts from here so from A to B we move our way from here so from A to B we move our way over here and we basically move this over here and we basically move this edge from B we can either move to E or edge from B we can either move to E or to C so let us suppose our DFS goes to C to C so let us suppose our DFS goes to C so we come over here and we remove this so we come over here and we remove this edge then from C we can move to D we edge then from C we can move to D we move this edge from here we cannot move move this edge from here we cannot move anywhere else so what we will do is we anywhere else so what we will do is we will simply add this to a list correct will simply add this to a list correct so will I have D now we will be back in so will I have D now we will be back in the recursion over here so from C we the recursion over here so from C we only had one edge which we have already only had one edge which we have already visited so again what we will do is we visited so again what we will do is we will simply add C to the front of the will simply add C to the front of the list or the front of the list only so list or the front of the list only so and will just return back now from C and will just return back now from C that is from B we have an edge that is that is from B we have an edge that is to e so we will go to e will remove this to e so we will go to e will remove this edge then from E to B we will remove edge then from E to B we will remove this edge we will back to B now from this edge we will back to B now from here we do not have any unn here we do not have any unn so we will simply explore we will simply so we will simply explore we will simply add B to the list and we will be back in add B to the list and we will be back in the recursion to towards here any so the recursion to towards here any so again from e we do not have any again from e we do not have any unvisited edge so we will simply add e unvisited edge so we will simply add e to the list and we'll be back in the to the list and we'll be back in the recursion so veil back to B again recursion so veil back to B again so again from B we do not have any so again from B we do not have any unweighted edge so we'll add B to it unweighted edge so we'll add B to it then we will back to a and from a we do then we will back to a and from a we do not have any unvisited edge so we will not have any unvisited edge so we will add a to the recursion or to the list so add a to the recursion or to the list so we basically have this thing so if you we basically have this thing so if you see this is same as this thing so you see this is same as this thing so you are able to find the Eulerian path using are able to find the Eulerian path using DFS only just you made a couple of DFS only just you made a couple of modifications the couple of modifications the couple of modifications is whenever you are modifications is whenever you are visiting an edge you're simply removing visiting an edge you're simply removing that so that you do not visit it again that so that you do not visit it again because we have to with it oh the edge because we have to with it oh the edge exactly once it is given in the exactly once it is given in the definition of Li all right definition of Li all right and the second modification is that when and the second modification is that when you're able to finish our things that ad you're able to finish our things that ad that is for our vertex you do not have that is for our vertex you do not have any unbudgeted edge you will simply add any unbudgeted edge you will simply add it to the list it to the list the friend of the list so that's how you the friend of the list so that's how you find the either in part a couple of find the either in part a couple of points known over here is that in the points known over here is that in the illidan path for a graph only starts illidan path for a graph only starts from a specific index it cannot start at from a specific index it cannot start at any index so for suppose for this graph any index so for suppose for this graph the Union path can only start from this the Union path can only start from this a correct and you cannot start from B a correct and you cannot start from B why is that so why is that so the reason being for tearing path we the reason being for tearing path we have to cover all the edges so if you have to cover all the edges so if you consider this example a doesn't have an consider this example a doesn't have an incoming edge so we won't be able to incoming edge so we won't be able to cover this edge a to be if you're not cover this edge a to be if you're not starting from me if you are starting starting from me if you are starting from B or E or from C from D we won't be from B or E or from C from D we won't be able to cover this edge so we won't be able to cover this edge so we won't be able to find out your own path so you able to find out your own path so you lured in path always starts from a lured in path always starts from a specific vertex now how do know in our specific vertex now how do know in our question which vertex is that so it is question which vertex is that so it is actually given the question it says that actually given the question it says that the itinerary must begin with JFK so the itinerary must begin with JFK so actually this is the base point of your actually this is the base point of your DFS or DFS will move from this this air DFS or DFS will move from this this air code correct all right so anything else code correct all right so anything else so okay so in the question you won't be so okay so in the question you won't be given this graph what are you given in given this graph what are you given in the question is you're given a list of the question is you're given a list of pairs or something like you will be pairs or something like you will be given a to B B to C C to D B to E and E given a to B B to C C to D B to E and E to be and from this list you have to to be and from this list you have to create this graph correct so this is create this graph correct so this is what is given in the input you're given what is given in the input you're given a list of pairs so my first thing is to a list of pairs so my first thing is to convert this list into this graph so convert this list into this graph so this is the first step and after this this is the first step and after this you given the point from which from you given the point from which from where the DFS is going to start which is where the DFS is going to start which is JFK and after this you can simply find JFK and after this you can simply find the earring but one more thing it is the earring but one more thing it is given that we have to find that UN but given that we have to find that UN but which is having a lower lexical order which is having a lower lexical order correct so let us consider some example correct so let us consider some example so to understand that as well so let us so to understand that as well so let us consider this graph that is a then we consider this graph that is a then we have B then we have C so we have an edge have B then we have C so we have an edge from A to C as well and from C to B as from A to C as well and from C to B as well so if you see if you move from a b well so if you see if you move from a b c a c b this forms are you reading but c a c b this forms are you reading but as well if you move from a c.b.c a B as well if you move from a c.b.c a B this actually also forms a your own path this actually also forms a your own path so both of these forms are nearing but so both of these forms are nearing but but we have to a done this thing why is but we have to a done this thing why is that this thing why is that because this that this thing why is that because this is coming lexically order this is this is coming lexically order this is this will be before this thing because B is will be before this thing because B is before C so how do I achieve that thing before C so how do I achieve that thing so basically from a we first we will so basically from a we first we will move to be correct move to be correct not to C correct so how can we achieve not to C correct so how can we achieve this thing so basically when you are this thing so basically when you are creating a graph so over here you will creating a graph so over here you will be given a list of peers so what we are be given a list of peers so what we are going to do is we are going to create going to do is we are going to create something called as map of string comma something called as map of string comma list of strengths list of strengths that is we are going to create an agency that is we are going to create an agency list correct so basically we can list correct so basically we can basically sort this list correct all basically sort this list correct all that we can do is instead of sorting that we can do is instead of sorting this list we can even create a map of this list we can even create a map of string comma priority queue of string so string comma priority queue of string so that we always get B before C correct so that we always get B before C correct so I guess that's it from the explanation I guess that's it from the explanation so let me just write the code for it and so let me just write the code for it and then things will be hopefully up so then things will be hopefully up so first we will have map of string comma first we will have map of string comma right EQ of string let us name it map right EQ of string let us name it map and you will having a list of string and you will having a list of string which is result so let me just which is result so let me just initialize both of these things over initialize both of these things over here this would be new hash map and this here this would be new hash map and this result is going to be new linked list result is going to be new linked list correct so the first thing is to build a correct so the first thing is to build a graph right so first is build a graph so graph right so first is build a graph so what you're going to do is we are simply what you're going to do is we are simply going to iterate over this list of list going to iterate over this list of list of string given to us so we will be of string given to us so we will be having four lest of string so this is having four lest of string so this is going to be ticket for tickets going to be ticket for tickets so now what we are going to do is we'll so now what we are going to do is we'll have two strings that is wrong which is have two strings that is wrong which is going to be equal to ticket dot get zero going to be equal to ticket dot get zero and two which is equals to ticket dot and two which is equals to ticket dot get one why is that because if you see get one why is that because if you see this list is actually a list of two this list is actually a list of two elements from n to next we will check if elements from n to next we will check if not map dot contains key for prom we not map dot contains key for prom we will simply say map dot put wrong with a will simply say map dot put wrong with a new variety cue correct new variety cue correct and after this what we will do is we and after this what we will do is we will say map dot get from so we get a will say map dot get from so we get a priority queue and we will simply add 2 priority queue and we will simply add 2 to it to it correct so this is building the graph so correct so this is building the graph so the graph is over the graph is over so after this what we will do is we will so after this what we will do is we will simply call DFS with this JFK and after this thing it will simply add up result so let me write this method as well this is void DFS this will take a spring suppose this is from all right now you will have priority Q of string which can we say as like arrivals which is equals to map dot get of prom and you will simply say while arrivals not equals null and not arrivals dot is empty that in that case what we will say is we'll call the DFS with this arrivals dot so actually if you see we are removing the edge over here correct so this is what we have discussed whenever you are visiting edge whenever you are visiting a vertex you will simply remove the edge correct so this is what you are doing over here and after this is done we will simply add the current spring from in so I guess that's it let me on this so I guess that's it let me on this board once so this is giving a long board once so this is giving a long wrong result living somewhere solution and God accept living somewhere solution and God accept it it so I guess that's it from this video in so I guess that's it from this video in case you have learner in the video you case you have learner in the video you can hit that like button and I would can hit that like button and I would support my work you may consider support my work you may consider subscribing to my channel thank you
2024-03-24 10:43:23
332
https://i.ytimg.com/vi_w…xresdefault.webp
Reconstruct Itinerary | reconstruct itinerary | reconstruct itinerary leetcode | leetcode 332
dOG5uH3XfcU
Hello Hello Everyone Welcome Welcome Back to My Channel Suggestion or Increasing the Channel Suggestion or Increasing the Problem Problem Problem Aisa for Any Search Problem Problem Problem Aisa for Any Search Facility How to Do Something in Binary Search Facility How to Do Something in Binary Search Tree Images Basic Problem and Binary Tree Images Basic Problem and Binary Search Tree Leaves for Less Problems Where Given Search Tree Leaves for Less Problems Where Given Root of Binary Search Root of Binary Search Root of Binary Search Stir Well Point Note In Bsp Dot S Well Suited For The Soft Root Without Notice Bachchan And 10 Minutes Egypt Returns It's Okay What Is The Means Of Binary Search Tree Giving Tools And Need To Find Weather Of Particular Notice York Pimple Person Check weather to lord in were and Check weather to lord in were and Check weather to lord in were and in the best and not to here to is the fifth just want in the best and not to here to is the fifth just want to front it aa that bigg boss to front it aa that bigg boss kalyan vitamin b2 notes address so on kalyan vitamin b2 notes address so on importance of tree witch vitamin e hai to importance of tree witch vitamin e hai to tower distant places with as launches tower distant places with as launches stem k stem k stem k value given to me is life to find how to right social science physics lab benefit when tasty to bsc fashion property dat root node key cutting fruit note fruit notes value on the right all can see it E Will Be Always Great Dane Left Child Labor Child E Will Be Always Great Dane Left Child Labor Child Value Is So And Paint Ruk Notes Value With You Always Great Dane A For Apple B For Muslims And Dar Right Child Right Child Queen's Pimples Ishwarya Parents For Lips Scientist To Right 407 hai to you and parents is great apparent value for this greater than love child new delhi vs to cigarette him * is but for this licensed images right chat flash light on which applies to all mentality stood up and went to paint a hai For this two places left side and decided to For this two places left side and decided to For this two places left side and decided to front value with greatest danger left front value with greatest danger left side value battu villain jakar side value battu villain jakar right end value addition right end value addition a right to this will be applicable ₹50 a right to this will be applicable ₹50 applicable to all the notes in the binary applicable to all the notes in the binary search tree on any successful property search tree on any successful property Any Such Na Peena She Adds To Her To-Do List Neetu Neetu Any Such Na Peena She Adds To Her To-Do List Neetu Neetu How To Find What You Will Not Write To 700 To Find Weather To States The Best I Want Any Valid For Every Problem Yagya Va Draupadi Swayamvar Pointer And Root Vegetable Election What we have to Election What we have to Election What we have to you to search weather tuesday oct ok so let's you to search weather tuesday oct ok so let's just and just simple - a simple binary tree for 100 simple binary tree and what to me to the effective soch tu yaar do something lootpat and 100 hand person Bodhpath Bodhpath Bodhpath left and right to vote in this modern left and right to vote in this modern amenities in this soch amenities in this soch meanings for the root value and meanings for the root value and subscribe you in binary search subscribe you in binary search tree left value will always be pleased in front tree left value will always be pleased in front of Delhi and you will always right and of Delhi and you will always right and values values and to the and to the laptop the root and laptop the root and laptop the root and This Loot Value Na A The Principle Of Which Will Be Reduced To Let That Bigg Boss Ne Binary Search Tree And - Key Bigg Boss Ne Binary Search Tree And - Key Take Ginger-Garlic Value Note Warangal Take Ginger-Garlic Value Note Warangal Left Side And All The Great Value Road Left Side And All The Great Value Road By Andar Side By Andar Side By Andar Side in Binary Search Tree to check in 12th part on left side simply accordingly they value your truth and truth and value with me to go value with me to go that is to abuse me account statement that is to abuse me account statement root warid so zaroor volume ko root warid so zaroor volume ko hai to what will oo will go hai to what will oo will go hai to what will oo will go not present for details they will make moving fast moving this root to the root Loop Fast Bisru Drops Root For No 52122 Iss In To-Do List Sunao 12217 Check This Does Not Mean Equal To The Value Of Root Value Ki Inko Likho Tu To Daru Which Were To Find A Co Arrest Recovery Code Ab Bollywood Par Point To Case Will Simply Case Will Simply Case Will Simply 2815 2815 222 Is Note Jasveer Kaur Bigg Boss Me To 222 Is Note Jasveer Kaur Bigg Boss Me To The The Root Not Right With Your Twitter Account That Her Nature Is Problem Vote Not Even To-Do List Play List Previous Serial Puram Hai To Is Cheez Ke 142 7 A Free And One What made you will have the option research and root of the giver is the incident of excellent and call me to written notes vitamin b3 heart oo k notification a diet tips root value the root value is equal to the value which we were Fight the ritual comes when a view of 300 to 10 12v battery visualization true weather this root and left and right what we do not disturb him will tree like this is life is the fastest and jyoti swaroop to water will have given and jyoti swaroop to water will have given Through The Years But I Will Check The Rooms Through The Years But I Will Check The Rooms Were Like It Say It Were Like It Say It Is Something Like This 213 And Values ​​To And What Is Is Something Like This 213 And Values ​​To And What Is This I To For This I To For Office I Volume Mute Is To You To Office I Volume Mute Is To You To For Individual Who Tried To Here His For Individual Who Tried To Here His Roots Value Is Equal To Roots Value Is Equal To Roots Value Is Equal To Meaning Of Mother Also Have Foot Pain Just When Did Not Return With Route 159 Wilson Simply Return To Go But If It Is Navodaya Jab Diet Is Roots That Is That Is A Great And Value A Great And Value On Result Hair Roots Electronics On Result Hair Roots Electronics Foreign Drive Foreign Drive Foreign Drive root of and and Vinod hatoge nor raw to to you find answers in root to person's 2.2 and values ​​for electronic root value Switzerland part of the root to in this will do the curse for annual It's against It's against It's against qualification for fifth to search will again college function search but in this case root passed with one nose distortion to fruit slapped roots life but also in Europe Russia left vote for life into will be passed in root ok celery salute it might happen left -7K Episode 717 Greater Noida Route -7K Episode 717 Greater Noida Route -7K Episode 717 Greater Noida Route Value Neither Office Let Me The White Part 2 Value Neither Office Let Me The White Part 2 In Both Cases In Both Cases Search Indore Route Right Side And Equal Search Indore Route Right Side And Equal Andar Right Andar Right Routes Right A Okay Routes Right A Okay Champion Twist Vacation Call With And Sunao Despite Route 10 result value nickel 10 result value nickel 10 result value nickel to value this sequence return to value this sequence return promise Tubelight promise Tubelight that your sudarshan basically you everyday entry that your sudarshan basically you everyday entry problems comes when every problem has given problems comes when every problem has given to to sur2 Visualize tree is diet fear disappears sur2 Visualize tree is diet fear disappears and the and the root and left and right part to vihar to root and left and right part to vihar to only rs.1 economic only rs.1 economic only rs.1 economic lagya to want this root and rest of the left and right requests for mid-day ok so let's talk previous straight to device a very very easy code sorry c torch bsc functions ribbon is tracking root and volume Fruits Fruits Fruits na i just na i just returned returned basically like quickly no value se basically like quickly no value se 800 just find you for search history 800 just find you for search history thank you will not regret to thank you will not regret to inform you have written that is the notification inform you have written that is the notification 12th 12th a producer and not dare i can simply a producer and not dare i can simply returned to ok otherwise returned to ok otherwise a value is loot a value is loot a value is loot meaning pure laptop battery otherwise with greater than world tour right and in this way there vehicles were written route main hansi searching everywhere every time zara here going to be the left and govinda right a now time complexity for searching logged in the When is active login? When is active login? When is active login? I hope you understand the problem and I hope you understand the problem and affidavit. There is affidavit. There is decline in comment in the areas of field by issue or subscribe decline in comment in the areas of field by issue or subscribe our channel thank you.
2024-03-20 17:28:28
700
https://i.ytimg.com/vi/d…axresdefault.jpg
Search in a Binary Search Tree | Leetcode 700 | Binary Search Tree | Day-14
WJAA6jr8hMM
hi guys welcome to algorithms made easy today we will be looking at the question today we will be looking at the question reach a number so you are standing at a reach a number so you are standing at a position zero position zero on an infinite number line and there is on an infinite number line and there is a goal at a position target a goal at a position target on each move you can either move left or on each move you can either move left or right right during the nth move starting from 1 you during the nth move starting from 1 you take take n steps we need to return minimum number n steps we need to return minimum number of steps required to reach the of steps required to reach the destination destination in the example when the target given is in the example when the target given is 3 so we take 3 so we take one step from 0 to one and in the next one step from 0 to one and in the next step we take two steps from one to three step we take two steps from one to three so this gives us so this gives us total number of step equal to two in the total number of step equal to two in the example two the target given to us is example two the target given to us is two two in the first step we take one step zero in the first step we take one step zero to one to one in the second step we move backwards or in the second step we move backwards or left from one to minus one left from one to minus one that are two steps and in the third move that are two steps and in the third move we move three steps from minus one to we move three steps from minus one to two two this gives us total number of steps as this gives us total number of steps as three and so the output is three the three and so the output is three the note states that note states that target will be a non-zero integer in the target will be a non-zero integer in the range of minus 10 raised to 9 to range of minus 10 raised to 9 to plus 10 raised to 9. so now let's see plus 10 raised to 9. so now let's see how we can solve this question how we can solve this question let's take this example where we have let's take this example where we have this as our area this as our area and we need to read 6 so what we do is and we need to read 6 so what we do is from zero we go one step forward from zero we go one step forward to reach one from here we can go either to reach one from here we can go either to left or right to left or right so we move right this time two steps so we move right this time two steps from here again we can go three steps from here again we can go three steps back or back or three steps forward so we move forward three steps forward so we move forward and that we have reached our destination and that we have reached our destination so so the answer here is 3. now what if the the answer here is 3. now what if the question question was to go to the target 2. in this case was to go to the target 2. in this case we would need to go we would need to go backwards also so from zero we go to one backwards also so from zero we go to one from here we from here we go two steps back from here we take go two steps back from here we take three steps forward three steps forward in this question the main thing that we in this question the main thing that we know is in the nth know is in the nth time we are taking n step so if we find time we are taking n step so if we find the maximum target that we can reach for the maximum target that we can reach for n step it would be given by n step it would be given by this formula that is sum of 1 to n this formula that is sum of 1 to n function of n function of n and this function of n would be the x and this function of n would be the x the value of x the value of x or step the second thing that is given or step the second thing that is given in this question in this question is that we can even move to a negative is that we can even move to a negative direction direction for this example we are moving two steps for this example we are moving two steps behind to go to behind to go to two in three steps but in previous two in three steps but in previous example that we saw we were taking three example that we saw we were taking three steps to reach steps to reach six that is the maximum target we could six that is the maximum target we could have reached in have reached in 3 steps so now if we try to manipulate 3 steps so now if we try to manipulate 1 plus 2 plus 3 to give the output as 1 plus 2 plus 3 to give the output as 2 it would look something like this so 2 it would look something like this so what we need is 1 minus 2 plus 3 these what we need is 1 minus 2 plus 3 these are the steps we are taking are the steps we are taking to get the effect of this minus 2 we to get the effect of this minus 2 we would need to do would need to do 2 multiplied by the steps 2 multiplied by the steps so this would give us the effect of so this would give us the effect of going to the negative side going to the negative side in the second step in the first minus 2 in the second step in the first minus 2 we are coming to a neutral position we are coming to a neutral position in the second minus 2 we are going in the second minus 2 we are going actually to the negative actually to the negative side so according to the side so according to the theory that we have seen we can come up theory that we have seen we can come up with this algorithm that is mentioned with this algorithm that is mentioned over here over here so we would add the steps till we reach so we would add the steps till we reach a target a target so for example two we would add step one so for example two we would add step one and step two we add the step two because and step two we add the step two because in step 1 we have not reached the target in step 1 we have not reached the target now once we have the step 2 the target now once we have the step 2 the target is already surpassed so is already surpassed so we are sure that there were some we are sure that there were some negative steps which we missed so negative steps which we missed so we would go on adding the steps while we we would go on adding the steps while we can can subtract two and do some steps so this subtract two and do some steps so this gives us gives us these two conditions that is add the these two conditions that is add the steps till we reach the target steps till we reach the target and then add the steps till the sum and then add the steps till the sum minus target minus target becomes a divisible of two that's all becomes a divisible of two that's all about the theory about the theory let's go ahead and code this question so let's go ahead and code this question so we will take two variables sum and step we will take two variables sum and step which would be 0 initially now since here we are given that the target can be minus 10 raised to 9 2 plus 10 raised to 9 we know that moving to negative part would be actually mirror of moving to the positive part so in order to shorten our problem scope we would take the that's it now while that's it now while sum is less than target what we do is sum is less than target what we do is sum plus steps sum plus steps and we do steps plus plus after we have and we do steps plus plus after we have come to the target what we do is while come to the target what we do is while sum minus target is not divisible by 2 we again keep on at the end steps minus 1. okay and let's run this code let's try for a negative input let's try for a negative input that's it and let's that's it and let's try for okay so for 0 try for okay so for 0 we can add a base condition where if we can add a base condition where if target equals to 0 return target equals to 0 return 0 and let's run for this test case now 0 and let's run for this test case now and that's it let's submit this code and and that's it let's submit this code and it got submitted so the time complexity it got submitted so the time complexity would be would be equal to the number of steps that we are equal to the number of steps that we are taking and the space complexity taking and the space complexity would be o of one that's it for today would be o of one that's it for today thanks for watching the video see you in thanks for watching the video see you in the next one
2024-03-21 15:49:53
754
https://i.ytimg.com/vi/W…axresdefault.jpg
Reach a Number | Live Coding with Explanation | Leetcode #754
9jv_Q8Mx4AM
hello and welcome to another video in this video we're going to be working on this video we're going to be working on remove Zero Sum consecutive nodes from remove Zero Sum consecutive nodes from link list and in the problem you're link list and in the problem you're given the head of a link list and you given the head of a link list and you want to delete consecutive elements that want to delete consecutive elements that sum up to zero until there's no such sum up to zero until there's no such sequences after doing so return the head sequences after doing so return the head of the link list you may return the of the link list you may return the answer in any order now in the examples answer in any order now in the examples below all sequences um are serations of below all sequences um are serations of list so basically they they give you an list so basically they they give you an array but it's really a link list so in array but it's really a link list so in the first example um you can delete this the first example um you can delete this for sure because this sums up to zero for sure because this sums up to zero and then you get either one two one or and then you get either one two one or 31 you can also get 31 by deleting this 31 you can also get 31 by deleting this so as long as you get rid of consecutive so as long as you get rid of consecutive sequences it doesn't really matter um yeah and in the second example you can delete this and you get one 124 and in the third example you can get you can delete this and this together so this whole thing can be deleted right here and then you just get the one so the main thing to know for um deleting like you're basically looking for subarrays here that are that are are add up to zero and if you've done problems with prefix sums before this is basically like the perfect use case for it so prefix sums um whenever if you do prefix sums if you get the same prefix sum twice that means the sub array between those two sums has to add up to zero so if we take a look at this here's like our array and here's the prefix sum in the bottom so if there are two numbers that are the same like the prefix sum is the cumulative sum you've gotten so far so if you have a sum of three and you have a sum of three later on how do you get to that it's because all the operations you added and subtracted end up canceling out and giving you the same number so if we take a look there's a three and a three that means that everything from the first three to the second three not counting the first three has that up to zero so this has that up to zero also here there's a one and a one that means this whole section has to add up to zero because this whole section has to add up to zero then you would get 1+ 0 equals 1 and let's take a look at that so this 3 + 3 is 0 2 + 4 is 6 + 6 is 12 - 12 is zero and so you can do a prefix sum and like some link list stuff but instead what I'm going to do is I'm going to use a um I'm just going to take an array of the values because that way I can pop values off the end whenever I hit like the same prefix sum that I can't do with the link list because I can't go back in a link list so we're just going to like go through like imagine this is our starting link list we'll make an array of values and instead of prefix sum we'll just maintain a current sum and anytime we hit a current sum we've seen before we'll just start deleting items until we hit to the other sum and because we're basically looking anytime we hit a duplicate we're just going to keep deleting until we go back to our other thing we can just use a set for that so we'll have a set of all the sums we've encountered so far and we can build our array of items so let's walk through what that's going to look like let's use um I guess we can use like an array of items we build and then we'll just like pop things as we go actually we can just pop things from the original array as we go and this is this is going to be the new one that we're building and so we'll have a set on the the bottom and we need to keep track of a cumulative total to know our like prefix sum so let's walk through how that's going to go and also for a prefix sum um if you're not if you're looking for arrays of some zero you do need to put zero into your original prefix sum because let's say this adds up to zero you're going to be like oh I have a zero here do I have a zero before and you won't unless you have a zero originally so we'll add the zero into our set and we'll have a total with a zero and then we can just Traverse here so we're going to add the one to our total um so our total is going to be one and I'll just keep Crossing it I'm putting new numbers to make it a little bit faster uh and is our total in our scene sums no it's not so we'll just add it in then we go to the next number so we add a two so we will uh oops actually let me do it this way this will be easier so our totals three and we um we don't have it so we'll add it in then we go to the next one and now our total is six and we don't have it so we'll add it in then we go to the next one and our total is three again right when we subtract and now we do have the three so if we do have the three that means we need to delete until we hit we go back to our previous spot where we had a three and that makes sense because this is the previous spot where we had a three so if we just delete numbers till we hit there we'll get rid of everything that adds up to zero which is this and it doesn't really matter how you delete so like I think we origin originally said that this whole thing adds up to zero but it's fine to like get rid of a chunk first and then another chunk because if a whole array adds up to zero if you get rid of part of it which adds up to zero the rest of it still has to add up to zero right like if this is zero and this whole thing is zero that means the rest of it also has to be zero so it doesn't really matter that you're deleting as you go so as soon as we hit a zero we'll just delete right away so basically we're getting rid of this section here and we need to update the sum as we do so we need to get rid of this number here so we can toss it and then we update our sum so now our sum is six and it's still not three and as we delete numbers we're going to delete them from the set as well so our sum is six which is not three so we need to keep deleting so we'll delete this six from the set and we'll delete this block and now our sum is three so that means we've deleted everything we needed to to go to our previous number then we go to our next number and we're not going to be traversing our numbers we're going to be traversing our link list so this will be more like we're going to be building this as we go and then just traversing down the nodes of Link list so here the total is going to be seven have we seen it before no so we'll add it in then we go to the next one the total is 12 have we seen it before no so we'll in then the total is 13 in then the total is 13 so haven't seen it before and we will so haven't seen it before and we will add it in then the total is four so total is four now we have seen it um actually no we haven't seen it before and we haven't seen before so we in then the total is one and now we have in then the total is one and now we have seen it before so now we're saying okay seen it before so now we're saying okay we have to delete until we hit our total we have to delete until we hit our total of one again so we're going to delete of one again so we're going to delete this this update our total we deleted3 so our update our total we deleted3 so our total is four um is 41 no it's not so total is four um is 41 no it's not so we're going to delete we're going to delete four delete four try to delete four okay four delete four try to delete four okay there we go um and so our total is four there we go um and so our total is four we delete it and then we have to delete we delete it and then we have to delete this this number because our total isn't this this number because our total isn't one so now our total is one so now our total is 13 um is that one no it's not so we'll 13 um is that one no it's not so we'll delete 13 then we delete this delete 13 then we delete this block and we just deleted one so now our block and we just deleted one so now our total is 12 is 12 uh one no it's not so total is 12 is 12 uh one no it's not so we'll delete we'll delete again then we need to get rid of this again then we need to get rid of this item because we we only have 12 and we item because we we only have 12 and we need to keep going so delete this now we need to keep going so delete this now we have have seven is 71 no it's not so we need to seven is 71 no it's not so we need to delete the seven then because we still delete the seven then because we still don't have what we want we need to don't have what we want we need to delete this block now our total is three delete this block now our total is three is 31 no it's not so we delete the three is 31 no it's not so we delete the three and we delete this block and now our and we delete this block and now our total becomes one and now we're good we total becomes one and now we're good we have a matching total so everything we have a matching total so everything we deleted like if we go back everything we deleted like if we go back everything we deleted ends up adding to zero so we deleted ends up adding to zero so we deleted uh all these numbers right here deleted uh all these numbers right here so 2 4 5 so this is 11 12 and this is 12 so 2 4 5 so this is 11 12 and this is 12 as well so all these six numbers add up as well so all these six numbers add up to zero which is what we wanted to zero which is what we wanted so so we deleted all this like I said so so we deleted all this like I said this Arrow isn't super accurate it's this Arrow isn't super accurate it's just kind of showing for the picture just kind of showing for the picture this Arrow will be really going through this Arrow will be really going through our link list and we're just going to our link list and we're just going to keep deleting the last number in our keep deleting the last number in our array so we'll just keep popping um and array so we'll just keep popping um and then changing the total so now we go to then changing the total so now we go to our last number so the total and this our last number so the total and this should have been one not three the total should have been one not three the total here is six we add it in because we here is six we add it in because we don't have it yet and now finally our don't have it yet and now finally our array is only two numbers so we'll just array is only two numbers so we'll just keep popping off the end our array will keep popping off the end our array will be like a stack and then once we have be like a stack and then once we have this array that's all our valid numbers this array that's all our valid numbers then we can just build a link list out then we can just build a link list out of it so we'll just start from the of it so we'll just start from the beginning and just build a link list and beginning and just build a link list and then we will return this then we will return this here and this will work for all this here and this will work for all this other stuff so you can um like move all other stuff so you can um like move all your nodes but because you need to have your nodes but because you need to have space like normally in Link in link list space like normally in Link in link list problems there Conant space in this one problems there Conant space in this one you need to have space no matter what you need to have space no matter what cuz you need to have like a prefix sum cuz you need to have like a prefix sum or some kind of thing so because you or some kind of thing so because you need to have space no matter what I'd need to have space no matter what I'd rather just get the numbers modify the rather just get the numbers modify the numbers and then make a link list numbers and then make a link list instead of like dealing with all the instead of like dealing with all the pointers so let's take a look at the pointers so let's take a look at the code so here it is so we have our nums code so here it is so we have our nums that we're going to be building as we go that we're going to be building as we go um our current will be at the head and um our current will be at the head and we'll just keep going and we'll just go we'll just keep going and we'll just go one note at a time and then this is our one note at a time and then this is our scene which is like our sums we've seen scene which is like our sums we've seen and we put in a zero and we have our and we put in a zero and we have our current total then while we have nodes current total then while we have nodes we need to add the current value we need we need to add the current value we need to increment the total and if we've seen to increment the total and if we've seen this total before we are going to get this total before we are going to get rid of the node so we're going to update rid of the node so we're going to update the total get rid of the node and the total get rid of the node and decrease the the total and we're going decrease the the total and we're going to save this value in this current total to save this value in this current total that we're looking for is current total that we're looking for is current total so if we go back in the picture for so if we go back in the picture for example example um like um like here basically what we do is if we have here basically what we do is if we have a number we've seen before a number we've seen before I'll go back a little bit actually I I'll go back a little bit actually I think it's right here so here our total think it's right here so here our total was one and we're going to be like okay was one and we're going to be like okay we've seen it before so let's just save we've seen it before so let's just save this value and then keep updating the this value and then keep updating the total but we need to make sure that the total but we need to make sure that the total equals the total we saved earlier total equals the total we saved earlier so as we keep updating this total we're so as we keep updating this total we're looking for one so so we save that in looking for one so so we save that in this current total so maybe this is not this current total so maybe this is not the best name it's kind of backwards the best name it's kind of backwards current total is is actually the total current total is is actually the total and then we're actually decrementing the and then we're actually decrementing the total and then once the once the total total and then once the once the total is the current total that means we've is the current total that means we've we've like deleted enough nodes so we've like deleted enough nodes so essentially what we do is while they're essentially what we do is while they're not equal just keep removing keep not equal just keep removing keep removing prefix sums from your set and removing prefix sums from your set and keep um deleting nodes so decrement the keep um deleting nodes so decrement the total delete the node remove from the total delete the node remove from the set otherwise if we haven't seen this set otherwise if we haven't seen this sum before just add it to the set and we sum before just add it to the set and we don't need to delete anything from our don't need to delete anything from our numbers and we just go to the next node numbers and we just go to the next node so we just like our current literally so we just like our current literally just traverses the link list and builds just traverses the link list and builds up our actual stack and anytime we seen up our actual stack and anytime we seen a prefix sum we just keep deleting until a prefix sum we just keep deleting until we go back to the S the previous we go back to the S the previous location we've seen it at it's kind of location we've seen it at it's kind of like a sliding window thing where you're like a sliding window thing where you're trying to do like a no repeating trying to do like a no repeating characters or something you have a set characters or something you have a set of characters kind of similar scenario of characters kind of similar scenario there and finally you just have an array there and finally you just have an array of numbers and then you just build an of numbers and then you just build an array of numbers from link list so I array of numbers from link list so I just made a dummy node I made the just made a dummy node I made the current equal to that go through every current equal to that go through every single number build a node make its next single number build a node make its next pointer the next note and so on so that pointer the next note and so on so that part should be pretty straightforward part should be pretty straightforward like given an array numbers but the link like given an array numbers but the link list and this does work and I do prefer list and this does work and I do prefer this over like actually changing the this over like actually changing the points in link list cuz like what's the points in link list cuz like what's the point if I need space anyway if you point if I need space anyway if you don't um I would say like 90 to 95% of don't um I would say like 90 to 95% of Link list problems are o1 so then Link list problems are o1 so then obviously you would just deal with the obviously you would just deal with the pointers but here you need oven space so pointers but here you need oven space so like you might as well use an array and like you might as well use an array and so for the time here this will be oen so for the time here this will be oen because we're basically like traversing because we're basically like traversing our we're traversing our link list once our we're traversing our link list once and then um the most NOS we can ever and then um the most NOS we can ever delete from the array we make is also delete from the array we make is also oen right oen right like as we're building this array we can like as we're building this array we can only delete node we can only delete only delete node we can only delete nodes one time so that's nodes one time so that's oven um and then and then to build out oven um and then and then to build out like our link list for the very end is like our link list for the very end is also ENT right given an array build out also ENT right given an array build out a link list that's a link list that's oen then oen then space so we can only have um for for space so we can only have um for for this scene set obviously for n nodes you this scene set obviously for n nodes you can only have n n different sums so can only have n n different sums so that's that's over um for the array of numbers the over um for the array of numbers the number of numbers you're going to have number of numbers you're going to have is equal to the um number of nodes worst is equal to the um number of nodes worst case that's also oven so this is just case that's also oven so this is just basically ovenoven basically ovenoven um yeah but I think this going to be it um yeah but I think this going to be it for this one so definitely one of the a for this one so definitely one of the a little bit trickier link list problems little bit trickier link list problems because you're basically just doing this because you're basically just doing this is basically just given an array of is basically just given an array of numbers remove all arrays that add up to numbers remove all arrays that add up to zero but in a link list so you're zero but in a link list so you're basically not using almost any link list basically not using almost any link list Properties or anything it's just Properties or anything it's just basically use an array and yeah so if basically use an array and yeah so if you know how to work with proix sums and you know how to work with proix sums and if you do know that um that concept if you do know that um that concept except that when you hit two prefix sums except that when you hit two prefix sums that are the same that adds up to a zero that are the same that adds up to a zero uh that whole array between those is uh that whole array between those is zero then this is pretty straightforward zero then this is pretty straightforward and that's going to be all for this one and that's going to be all for this one if you did like this video please like if you did like this video please like it and please subscribe to the channel it and please subscribe to the channel and I'll see you in the next one thanks and I'll see you in the next one thanks for watching
2024-03-25 18:39:47
1,171
https://i.ytimg.com/vi/9…axresdefault.jpg
LeetCode 1171 - Remove Zero Sum Consecutive Nodes From Linked List - Python
XqX3golQMPI
hello everyone let's solve the lead code question 190 reverse bits so a reverse question 190 reverse bits so a reverse bits of a given 32 bits unsigned integer bits of a given 32 bits unsigned integer so we are given an variable n which is so we are given an variable n which is equal to the 32bit number and we need to equal to the 32bit number and we need to reverse every reverse every element we need to just reverse this element we need to just reverse this whole n such that every last element whole n such that every last element comes first that's what the reverse comes first that's what the reverse means so after getting that value we means so after getting that value we just need to get the integer of that so just need to get the integer of that so we need to just get that number such we need to just get that number such that its binary number representation is that its binary number representation is reverse of this let's see how we can reverse of this let's see how we can solve this let's take n as the 32-bit solve this let's take n as the 32-bit number which is ending with 1 0 here we number which is ending with 1 0 here we can see that it's a binary can see that it's a binary representation of number four so that is not actually required the only thing required is if we reverse like and that value should be like and that value should be given so this can be done in many ways given so this can be done in many ways but the simple thing is to do use the but the simple thing is to do use the left shift and right shift left shift and right shift operations I'm pretty sure that you know operations I'm pretty sure that you know the concepts of left shift and right the concepts of left shift and right shift so left shifts and right shifts are the important Concepts in order to eliminate or add to the next element let me give you a code snippet which was very useful for any other codes also so if we consider a variable as a result and and for 32 Loop just go through the loop of 32 times and if you left shift and if you add the given left shift and if you add the given number which is in the binary format number which is in the binary format like this way and and one this gives you like this way and and one this gives you the last the last bit so this last bit can be used as the bit so this last bit can be used as the first bit and then later on if you just first bit and then later on if you just make this as your right bit for example make this as your right bit for example example if it's 0 example if it's 0 01 so this gets pop up and the variable 01 so this gets pop up and the variable goes to this to in order to make it to goes to this to in order to make it to the next integer value we can just do it the next integer value we can just do it as as and right right and right right shift uh so finally we will just add shift uh so finally we will just add these values and just simply uh return these values and just simply uh return the result value at the the result value at the end hope you understood this I think end hope you understood this I think things gets more familiar when you just things gets more familiar when you just start coding rather than explanation start coding rather than explanation like this so let's go and code it like this so let's go and code it up so let's take our value result equal up so let's take our value result equal to0 and we need to it's given clearly in to0 and we need to it's given clearly in the question that every number is a the question that every number is a 32bit integer and if you see the 32bit integer and if you see the constraints the input number binary constraints the input number binary string is of length 32 so it's obvious string is of length 32 so it's obvious that we need to Travers through 32 bits that we need to Travers through 32 bits all the time so for I in range 32 so we should travel 32 times and this result will be equal to let's take the end last bit so every time you just need if you need a last bit take an end off way just take the last bit and and way just take the last bit and and one one and if you want to get that last bit to and if you want to get that last bit to the front of that result you need to do the front of that result you need to do result left shift of one just add up these both together which gives us to your last bit and now that last bit has to be sent to the next variable like the next integer let me type that integer that can be done through integer that can be done through n right shift off equal to one so every n right shift off equal to one so every time it goes to the next integer and time it goes to the next integer and now it just returned the result this is now it just returned the result this is very obvious and simple let's check it got accepted let's see the sub let's submit and see this is a simple intution if you know the bit manipulation very indepth understanding thank
2024-03-21 14:26:15
190
https://i.ytimg.com/vi_w…xresdefault.webp
190.Reverse Bits | Python | Leetcode
qDf7YJlqcP4
um 240 search a 2d matrix let's see write an efficient algorithm that searches a value target okay um in an m by n matrix okay this matrix has following properties integer in each row rows a row are sorted in ascending left or right integer in each column are sorted in ascending top to bottom okay so two things to notice here right the the rows are sorted and columns are sorted rows are sorted and columns are sorted in from top to bottom in from top to bottom and another thing is we have to search and another thing is we have to search something something so when we so when we we search we can do two things linear search right or if if we know that the input is sorted we can do binary search yeah so i think um and they are asking us to write an efficient algorithm so this is kind of a um this has to be a binary search kind of algorithm but for binary search we like most of the time we have um just a single single row right so let's see let's see um one checking from starting from first row checking from starting from first row just do the binary search on this row just do the binary search on this row okay okay then if it is not here then then if it is not here then go and do binary search here so for this go and do binary search here so for this example we are searching for five example we are searching for five and it is found and it is found [Music] [Music] okay and okay and so so let's say we are searching for 5.5 let's say we are searching for 5.5 something which is not in this matrix so something which is not in this matrix so we go here we go here again we do search again we do search now we come here now we come here now now from this point on from this point on anything you you don't even have to bind anything you you don't even have to bind the research right the research right because 5.5 is less than 10 and it's not never going to be in between this this range and same for this so doing binary search doing binary search um um and maybe if uh even reduce it from top and maybe if uh even reduce it from top right so let's say right so let's say it was one one one one one one it was one one one one one one everywhere here one everywhere here one then there is no point in searching in then there is no point in searching in this row as well because 5.5 is greater this row as well because 5.5 is greater than this value than this value right so right so we can do that is there any anything else that i can think of but let's go through our checklist in matrix our checklist in matrix okay we have integer matrix kind of list of list and we have a target value to find and what is the output do we need to return the index or return true or false true or false is expected that's fine true or false is expected that's fine that's fine that's fine about the size so is is it is there a possibility that this is an empty matrix no it's not so it obviously there is going to be one uh one one element at least and at max it's going to be 300 looks cool and the values about the values um so these are the two properties so these are the two properties they are sorted but they are sorted but i just wanted to check if um we can have i just wanted to check if um we can have duplicates there is a possibility of duplicates as well so and we also have negatives so we have negative we have zero we have and we have duplicates and we have duplicates great now let's um let's see test and design code time so is there any edge case uh maybe just so is there any edge case uh maybe just one element that is case one element that is case um other than that um there are like multiple cases to be tested right um so target um target is um target is less less than than start start greater than and something like this so these can be test cases going further let's uh let's try to come up with an algorithm so first algorithm that i'm thinking of is a binary search algorithm doing on each row but i think there has to be something else because both of these so let's go so let's go through this example right um through this example right um what we are searching for is five what we are searching for is five okay okay so let's see so let's see i'm here i'm here and uh let's say i am checking if it is in between this range um i i have solved this question before and i think there is a so let's say um so let's say um so 5 right 5 can be in this so 5 right 5 can be in this in this row because it is starting from in this row because it is starting from 1 and ending at 15 1 and ending at 15 right right so what we do is so what we do is we decrement in that case uh we decrement in that case uh if we go from this if we go from this end to to this this end okay end to to this this end okay so what we are doing is we so what we are doing is we decrement the column now in next iteration we again check um if if matrix of this is 5 no then again if if not and if if value is less than this value then we decrement the column so again we check here still not so value still target is still less than this value so again we decrement the column so now now we have reduced all this there is no possibility that anywhere in this in this section there can be a five right so now our so so now we check uh at at this location now we check uh at at this location is it five it is not is it five it is not um um is is 5 less than this value it is not is is 5 less than this value it is not so so so that means so that means 5 5 can be cannot be in this row anymore because if we go in this direction it is going to be less than 4 always and we have decided that there is no no value in this section so in that case we have to go down so there is only one possibility that the value can be remaining in this this section or this whole section let's say um so we go here and this we find it here but let's say we are searching for six again uh we we do the same thing we we ignore these values when we come here right um we check is this value equal to equal to 6 it is not is this value greater than 6 it is not if it was greater than 6 then we could just decrement the column so it is less than 6 that means we have to increment the rule we should go in the next row and check if this value equal to equal to 6 it is not so we we go here and now it is 6. again let's take one more example we are searching for 3 we start at this position so 15 is greater than 3 so we decrement the column 11 is greater than 3 so we decrement the column 7 is greater than 3 so we decrement the column 4 is greater than 3 so we decrement the column now one for this value 1 is less than 3 so we increment the row two is less than three so increment the column is uh is found is uh is found and if it is not found right and if it is not found right then then then then either we we decrement the column which either we we decrement the column which goes out of pound goes out of pound or we or we we go out of bonds on the rows so in we go out of bonds on the rows so in that case we return that case we return false directly false directly so i hope i was able to talk it because so i hope i was able to talk it because i didn't um i didn't um draw the things but draw the things but somehow somehow i think i think we can we can do this in this way so we can we can do this in this way so let's see let's see um let me take rows and columns um let me take rows and columns so length of so length of matrix is going to be matrix is going to be rows and length of rows and length of matrix matrix of 0 is going to be of 0 is going to be columns columns we have to find target right we have to find target right um let's let's let's have two two values row and column let's have two two values row and column so let's start at row zero so let's start at row zero and and started started at the last last value right at the last last value right okay okay so so row 0 and column is columns minus 1 row 0 and column is columns minus 1 length of columns yeah length of columns yeah and so and so let's see let's see why why a row is is less than total rows and columns right right do one thing do one thing if if matrix matrix of row from column of row from column equal to equal to target and return true otherwise if matrix of r right this value if it is greater than right this value if it is greater than um um target target then we have to decrement the column so then we have to decrement the column so let's decrement the column let's decrement the column minus 1 minus 1 else and right right that's the binary search kind of logic that's the binary search kind of logic and if we and if we go out of bounds go out of bounds then then return return false so time complexity wise it's going to be so time complexity wise it's going to be m plus n m plus n at max at max let's say we are searching for 31 right so in that case yeah yeah [Music] [Music] even it is not m plus n because even it is not m plus n because we just increment the rows we yeah yeah i think it's amplison that's so let's see okay it's working um m plus n and we don't use any extra space so that oh oh i've solved this multiple times
2024-03-22 11:39:12
240
https://i.ytimg.com/vi/q…axresdefault.jpg
240. Search a 2D Matrix II | Kind of binary search | Leetcode Medium
vNWgvFwvcXY
hey everyone how are y'all doing today we're gonna check out the lead today we're gonna check out the lead code problem code problem this question is very popular often has this question is very popular often has done amazon facebook and many other done amazon facebook and many other companies interviews companies interviews and it just gives a great deal of and it just gives a great deal of understanding about time management understanding about time management problems in general so let's crack problems in general so let's crack straight into it so today we're going to straight into it so today we're going to be solving meeting rooms too we're given be solving meeting rooms too we're given an area of meeting intervals an area of meeting intervals where each interval is basically a pair where each interval is basically a pair of start and end times of start and end times we have to return the minimum number of we have to return the minimum number of the conference rooms required first we the conference rooms required first we have to find an intuition but before we have to find an intuition but before we dive into that main idea i want to give dive into that main idea i want to give you a quick tip you a quick tip some interviewers don't like to disclose some interviewers don't like to disclose the constraints to their interview the constraints to their interview problems because in some cases you can problems because in some cases you can infer the magnitude of the problem based infer the magnitude of the problem based on the length of the input or other on the length of the input or other properties properties for example in this problem the interval for example in this problem the interval length is between 1 and 10 000 so it's length is between 1 and 10 000 so it's quartic which is not a terribly big quartic which is not a terribly big number but also not very small which number but also not very small which means that you can't just attack this means that you can't just attack this with anything because it might turn out with anything because it might turn out to be too slow with 10 000 elements the to be too slow with 10 000 elements the solution in general is somewhere between solution in general is somewhere between the quadratic and the logarithmic range the quadratic and the logarithmic range there is a great article on code forces there is a great article on code forces that details how you can often guess the that details how you can often guess the complexity just by looking at the complexity just by looking at the constraints or most likely asking for constraints or most likely asking for them in the interview setting of course them in the interview setting of course this is not guaranteed but an awesome this is not guaranteed but an awesome thing to be aware of i'm gonna put the thing to be aware of i'm gonna put the link into the description link into the description so how can we build an intuition for so how can we build an intuition for this problem you may ask i think let's this problem you may ask i think let's start drawing and see how this works out start drawing and see how this works out if we sketch up one of the examples if we sketch up one of the examples let's take a look at the first example let's take a look at the first example in this problem so there will be three in this problem so there will be three intervals in this list the first one intervals in this list the first one starts at 0 and set 30 the second one starts at 0 and set 30 the second one starts at 5 and ends at 10 and the third starts at 5 and ends at 10 and the third one starts at 15 and ends at 20. one starts at 15 and ends at 20. let's try to sketch these up in this let's try to sketch these up in this basic timeline i'm gonna use the red basic timeline i'm gonna use the red marker for the first interval marker for the first interval it starts at 0 and will end at 30. it starts at 0 and will end at 30. let's use green for the second interval let's use green for the second interval which will start at the 5 and end at 10 which will start at the 5 and end at 10 and let's use blue for the third and let's use blue for the third interval which will start at 15 and end interval which will start at 15 and end at 20. at 20. so let's mark these um a little bit more so let's mark these um a little bit more just for the sake of clarity it will be just for the sake of clarity it will be easier to see what is happening here so what we can see here is that the red interval will take up one room for the entirety of these 30 units and the green and the blue intervals will take up 1-1 rooms but since the green room will be released at the tenth unit the blue room can reuse it so even though they need one one room basically they will only use one room and in combination with the red interval this means that it will only take two rooms in total for the entirety of the 30 units how can we formalize this logic at first we know that one meeting room is definitely needed because of the red meeting then by the fifth unit we need another meeting room that's two if there weren't any other meetings scheduled we would say that the answer is two but we have one more so since the second meeting ends before the third one started we know that nobody needs the room anymore and it can be reoccupied in other words when we put the new meeting into this timeline we have to ask will the previous meeting end before the next one starts if yes then we don't need an extra room if not then we have to keep digging for new rooms how can we keep track of if the previous meeting has ended before the new one starts we keep track of the minimum times when the meetings end for example for the red meeting it's going to be the third unit for the green meeting that's going to be the 10th unit so if we want to add the blue meeting here we want to see that it's already passed the green meeting and of course we need to know it as soon as possible keeping minimum value with fast retrieval the minimum priority key or heap comes to the rescue the minimum heap is a three-based data structure and its main benefit that it will always keep the lowest value in the root of the tree and all others order below that inserting a new element into this heap takes logarithmic time so it will be bigger of log n and reading the top element of the heap is constant time so it's big o of one the algorithm behind the mechanism of the heat structure is probably worth another video in itself so i'm not gonna go into details right now but let's try to construct this mini based on the example we know that the first meeting ends at the 30th unit so let's add 30 to the the next question is the next question is does the second meeting start after the does the second meeting start after the previous one has ended no because it is previous one has ended no because it is overlapping overlapping so the second meeting starts at five but so the second meeting starts at five but since red is still going on since red is still going on it is overlapping which means that the it is overlapping which means that the next meeting we want to keep an eye on next meeting we want to keep an eye on is the one that ends at 10 is the one that ends at 10 so the second meeting has to be added to so the second meeting has to be added to the heap and because the second meeting ends earlier than the first meeting it is going to be the new route for the heap the next question does this third meeting start after the previous one has ended and yes because the third meeting starts at 15 the second meeting ends at 10 so they are not overlapping with each other which means we can discard the previous meeting that has ended at 10 but we are still going to keep an eye on the minimum which is going to be 20. this means we have two rooms again and okay but what is the time complexity for okay but what is the time complexity for this the worst case scenario is that all this the worst case scenario is that all of the intervals will work with each of the intervals will work with each other and we have to make n inserts into other and we have to make n inserts into this minimum heap where n will be the this minimum heap where n will be the number of the intervals and also in the number of the intervals and also in the worst case we may have to discard the worst case we may have to discard the minimum value n times minimum value n times so the time complexity overall is going so the time complexity overall is going to be big o of n times log n where this n is going to be the number of the intervals and the login is going to be the time complexity for inserting a new element into the minimum heap and the space complexity is going to be bigger of n where n is going to be the number of intervals we may have to add the intervals into the minimum heap and times this example is very simple because all of the intervals are given in a sorted order in the first example you can see that the first interval starts at zero the second interval starts at five the third interval starts at 15 so it's kind of easy to put them into this timeline but if they weren't and there would be hundreds or thousands of intervals it wouldn't be so simple and we wouldn't be able to see the overlaps that easy so the first thing that we should do here is to sort the intervals by the start times okay i think this pretty much sums up the intuition for this problem we can jump into the code right now and see how this is the class that we get from lead this is the class that we get from lead code when we open up this problem there code when we open up this problem there will be one method here with the input will be one method here with the input parameter of an integer matrix which is parameter of an integer matrix which is basically a 2 by n matrix for the start basically a 2 by n matrix for the start and end times and end times and the return type will be an integer and the return type will be an integer that will tell us the number of meeting that will tell us the number of meeting rooms required rooms required at the end of the intuition building at the end of the intuition building phase i already mentioned that we should phase i already mentioned that we should sort the intervals by their start time sort the intervals by their start time because it will be easier to see the because it will be easier to see the overlaps so i'm gonna start start with overlaps so i'm gonna start start with that that i'm gonna i'm gonna sort the intervals and based on this sort the intervals and based on this lambda expression here lambda expression here i'm gonna take the i'm gonna take the first first property which is the start time it is indexed by zero and sort based on that after that we can start building the priority key it is going to store integers it is going to store integers i'm going to call it mpq as minimum i'm going to call it mpq as minimum priority queue and after that we can start by adding the so this is guaranteed to be there in the so this is guaranteed to be there in the intervals because based on the intervals because based on the constraints constraints one interval is guaranteed in this one interval is guaranteed in this matrix matrix and after that we can start by iterating and after that we can start by iterating through the remaining interval starting through the remaining interval starting from the from the first first based on the index and we have to check whether this new intervals start time is after the minimum end time that we store in the priority queue we have to also make sure that the priority queue is not empty we don't want to get any accidental new the height intervals start time the height intervals start time is bigger or equal is bigger or equal than the minimum priority queues top than the minimum priority queues top element which is going to be the peak if it is then we know that we can discard the element in the in the top of this minimum heap so let's get off get rid of this and after that we can replace it with the end time so we already constructed this minimum so we already constructed this minimum priority key priority key and and at the very end of this algorithm at the very end of this algorithm we know how many meeting rooms we needed we know how many meeting rooms we needed because it will be stored in the minimum because it will be stored in the minimum priority queue and the size will tell us how many meeting rooms are necessary and see how it performs on lead code so and see how it performs on lead code so although it isn't the best performing although it isn't the best performing solution it is definitely a great solution it is definitely a great algorithm to know algorithm to know um but once again um but once again what will be the time and space what will be the time and space complexity of this solution complexity of this solution so sorting is going to take big o of n so sorting is going to take big o of n times log n time times log n time because there are n elements in this because there are n elements in this intervals intervals of constructing this priority key adding of constructing this priority key adding a new element a new element is going to be big o of log n is going to be big o of log n worst case scenario we'll have to add worst case scenario we'll have to add all of them all of them so so it will be n times log n it will be n times log n peaking the top element of the peaking the top element of the priority queue is going to be a constant priority queue is going to be a constant time operation time operation and removing the minimum element from and removing the minimum element from this is going to be this is going to be log n again but worst case scenario we log n again but worst case scenario we have to remove all of them have to remove all of them so it's going to be so it's going to be n times log n n times log n so in total so in total the whole algorithm is going to be big o the whole algorithm is going to be big o of n times log n of n times log n but what about the space complexity as but what about the space complexity as i've already mentioned the worst case i've already mentioned the worst case scenario is that we have to add all of scenario is that we have to add all of the intervals to this priority key which the intervals to this priority key which is going to be big o of n where n is the is going to be big o of n where n is the length of the intervals length of the intervals i hope this was helpful if it was please i hope this was helpful if it was please like and subscribe leave a suggestion or like and subscribe leave a suggestion or comment this was my very first video and comment this was my very first video and i'm aware of all the editing mistakes i'm aware of all the editing mistakes made and i really hope i will have more made and i really hope i will have more time to spur for this little project time to spur for this little project because i really enjoy helping the because i really enjoy helping the community and solving problems but this community and solving problems but this format is definitely different than format is definitely different than writing writing bye
2024-03-22 12:08:17
253
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode 253 - Meeting Rooms II - Amazon, Facebook Coding Interview
W05eBKDGuWk
Hello everyone, welcome back to Coding Makeover, today we are going to solve another question of Let's Co, today we are going to solve another question of Let's Co, question question number 260. This is a single number 3 number 260. This is a single number 3 [Music] [Music] question in which two numbers will come once and the rest [Music] two numbers, both are unique, then that will be our two numbers, both are unique, then that will be our result. In the first approach, we can solve it with the help of dictionary which has key and value, that will become our name and the We We We will keep it will keep it in which we will find out which in which we will find out which number has come how many times, one tu time, tu tu times, number has come how many times, one tu time, tu tu times, three one time, five one time [ ] [ in which the result of 121325 [ in which the result of 121325 [ music] is the Only the unique Only the unique number of two will be canceled out, their result will have the same value [Music] we will sort the numbers into two groups, they will be the we will sort the numbers into two groups, they will be the first to come out, the formula for this is that the first to come out, the formula for this is that the result and its negative number will be equal to result and its negative number will be equal to zero. zero. zero. set in the second last here, now what we have to do is that again we have to divide all the numbers into two categories, in the first group whose second last [Music] [Music] [ Music] Music] This will be the number This will be the number which we have to with high quality [Music] [ Music] Did the and will smoke the lowest Music] [ ] This is our bath of all three tests This is our bath of all three tests This is our bath of all three tests solution
2024-03-22 12:17:19
260
https://i.ytimg.com/vi_w…xresdefault.webp
Single Number III | Leetcode 260 | Bit Manipulation
37s1_xBiqH0
Hello hello guys welcome back to decades and this video will see the best time to buy and this video will see the best time to buy and sell staff's problem specific from sell staff's problem specific from digit code reliable in so it's an order to solve this digit code reliable in so it's an order to solve this problem the first world problem the first world best odi debut verification plus best odi debut verification plus memorization the second one will be memorization the second one will be memorization the second one will be doing technique so latest video problem statement notice problem from you have very form which is the element is the price of giving day designer Gautam to complete your transactions and intuitive transaction the same time did you must stop now let us To stop this To stop this To stop this problem subscribe and subscribe the problem subscribe and subscribe the Channel Channel Nav-Jeevan second that is the price of Nav-Jeevan second that is the price of stock and different places where light maximum two stock and different places where light maximum two transactions and want to front maximum profit which we can make in the stock and maximum par obscene obscene bittu only know this is bittu only know this is bittu only know this is Retail Price For Profit 2132 Subscribe Institute Of 13202 subscribe The Channel subscribe The Video then subscribe to the Page Second Witch Will Be 500 Crack Mini Possible Combinations Of Violence Bill And You Can Only Make To Transaction Set Most So In This The Maximum Profit Welcome You Be The Maximum Profit Welcome You Be The Maximum Profit Welcome You Be Stopped At These Two Selected For Eggs In The Stopped At These Two Selected For Eggs In The Attack One And Selected For The Total Attack One And Selected For The Total Profit Exactly ₹500 You Profit Exactly ₹500 You Understand The Problem Statement Promise Its System Understand The Problem Statement Promise Its System Maximum Profit In Most Transactions Maximum Profit In Most Transactions Per Transaction Nothing But You Can You Per Transaction Nothing But You Can You Celebrate Center Cycle Celebrate Center Cycle Celebrate Center Cycle notification simple transaction setting stop this notification simple transaction setting stop this is not given up will have to celebrate in order to is not given up will have to celebrate in order to buy 10 buy 10 top again ok so basically this cycle not in the country as you can see the top again ok so basically this cycle not in the country as you can see the first week in the first week in the Midst Of Width Of Bus Stop This Is Midst Of Width Of Bus Stop This Is Not Mean That Know The Giver Setting Stop This Not Mean That Know The Giver Setting Stop This Is Not Not Not Not Not Not Not Not Not Solve This Is Not Not Not Not Not Not Not Not Not Solve This Problem You Can See A Very Logical Solution hush-hush Weddings hush-hush Weddings Pattern Similar For This 214 S Pattern Similar For This 214 S Pattern Similar For This 214 S Decide Which Mins That You Choose And Which Maximum Solid Say Only One Global Maximum Maximum 2002 Global Maximum Maximum 2002 Transactions For A Given Point Where You Transactions For A Given Point Where You Can You Can Stop This Number To The Can You Can Stop This Number To The The Doraemon the previous depart from the previous day you have water stock in this day you can here from here and you can skip 10 to lift salauddin v3 options and giving day but you can only to the depending on the liked liked liked The Video then subscribe to the Page if you liked The Video then subscribe to the Will Come Under The State Will Not Be Talking Subscribe for Women In The Will Be Holding Talks In Fever State On I - 1st Turn On The Amazing Go to the Best State Go to the Best State Go to the Best State Otherwise the Giver Not Doing Anything Like Doing Otherwise the Giver Not Doing Anything Like Doing So They Can Be Reduced It's OK So They Can Be Reduced It's OK Sorry for the Day in the State of the Country Will Sorry for the Day in the State of the Country Will Be in the State Will Not Stop Doing This State of the Otherwise and Women in the Lost Hope You Understand This Transition Problem in Name on How to Solve Reducing Name on How to Solve Reducing Requirements Know If You Can See a Great Requirements Know If You Can See a Great Holiday Give Winners subscribe The Video Holiday Give Winners subscribe The Video then subscribe to The Amazing to then subscribe to The Amazing to subscribe the Video then subscribe to subscribe the Video then subscribe to the Page if you liked The the Page if you liked The the Page if you liked The subscribe to the Video then subscribe to question call dayla in which indicated that will be question call dayla in which indicated that will be bank of baroda east up to wheeler and bank of baroda east up to wheeler and to the self start price will have to the to the self start price will have to the self and subscribe others sharing and self and subscribe others sharing and you will be you will be you will be completing one transaction in listed for women in total profit will also be - 2ND year will be no know you can see this will be very big problems subscribe The Channel Questions well known in this case gorgeous basic Friendship Friendship Friendship status first is that we are sending status first is that we are sending gifts in the previous day when water gifts in the previous day when water bottle cap and mid something on the current affairs bottle cap and mid something on the current affairs video will start here and there video will start here and there decision of the best all the best on Thursday decision of the best all the best on Thursday just remember and subscribe the to remember what just remember and subscribe the to remember what Are Currently Closed Are Currently Closed * R Equation Problem Date Means Victims To What Your Values ​​Are * R Equation Problem Date Means Victims To What Your Values ​​Are Calculated And Calculated And So They Can Return Dwells In Order To Solve This So They Can Return Dwells In Order To Solve This Problem Of This Entry By Using Problem Of This Entry By Using Dynamic Programming In This Case Dynamic Programming In This Case - Jind 420 420 420 Repeating Problems - Jind 420 420 420 Repeating Problems But It Doesn't Work In But It Doesn't Work In But It Doesn't Work In subscribe and subscribe the mode switch subscribe and subscribe the mode switch board The talk to the second and third division board The talk to the second and third division in the middle in the middle Log in hand which we shape button The first day Log in hand which we shape button The first day price equal to two Som rate states different from price equal to two Som rate states different from rate states with surprise rate states with surprise Same Day SIM Birthday Status of Different Not for This Thought Same Day SIM Birthday Status of Different Not for This Thought Thursday The Video then Thursday The Video then subscribe to the Page if you liked The subscribe to the Page if you liked The Video then subscribe to the Difference Video then subscribe to the Difference From This Point to the Number of Units and From This Point to the Number of Units and Repeating Problem Solve Different OK No Repeating Problem Solve Different OK No Problem Solve This Problem Problem Solve This Problem W W W are this is the most efficient approach using memorization so this will be fetching elements in which you have to the limits on 100MB maximum number of with a not forget to subscribe the channel and time not forget to subscribe the channel and time not forget to subscribe the channel and time IN DO SUBSCRIBE MY CHANNEL SUBSCRIBE TRANSACTIONS BOIL * Single String String End User Name Doing Service Key Blindly Correspondingly Value Which Will Be Net Maximum Profit Calculated Combining subscribe The Amazing Hit The Same That Next Day Thursday subscribe and subscribe and subscribe and fancy beds This is not the most optimal approach but this is temple in terms of space so you can prove it will work No this is the question The video of the subscribe divided into two subscribe divided into two parts parts parts divided into two parts divide the left side and will monitor will take the right hand side effect from this to intellibriefs last point and go for only one transaction Noida the maximum profit from the transition Order to Find the Order to Find the Order to Find the Total Maximum Profit Transactions 1.12 Total Maximum Profit Transactions 1.12 Next Device Maximum Profit Next Device Maximum Profit Transaction Maximum Profit and Loss Transaction Maximum Profit and Loss Birth and Death for all points in the Birth and Death for all points in the Maximum of all the calculated Subscribe Maximum of all the calculated Subscribe Thank You Can Use This Technique time.com Thank You Can Use This Technique time.com Quad Divider Transaction How to You Perform Quad Divider Transaction How to You Perform Operation So in this will give the time Operation So in this will give the time dividing this point to fennel love you all the dividing this point to fennel love you all the point to the laptop from to the point which point to the laptop from to the point which starts from this point subscribe subscribe Video set to maximum to make subscribe Video set to maximum to make profit 2012 profit 2012 Total Profit 320 Fan Ad Buddha Total Profit 320 Fan Ad Buddha Transaction Values ​​on the Left and Right and will Transaction Values ​​on the Left and Right and will calculate the maximum profits of calculate the maximum profits of force net Maximum of already calculated force net Maximum of already calculated Maximum profit which will also be Maximum profit which will also be calculated for the points 100MB Maximum Already calculated for the points 100MB Maximum Already Subscribe Subscribe through which will Subscribe Subscribe through which will give the giver and debit the give the giver and debit the give the giver and debit the point is not very common logic which will solve this problem to once maximum profit there will obviously find once maximum profit there will obviously find minimum value for bank po minimum value for bank po and will find the value from this point and will find the value from this point notification subscribe Video notification subscribe Video Maximum Transaction Video Maximum The First Elements Sexual From The First Elements Sexual From The First Elements Sexual From The Last Time From Left To Right The Name The Last Time From Left To Right The Name Of The First Indian To Win The Time It's Of The First Indian To Win The Time It's Very Difficult To Solve Win From Left To Right Will Very Difficult To Solve Win From Left To Right Will Have To The Value Of Have To The Value Of Half Velvet Given Point Which Can Find The Half Velvet Given Point Which Can Find The Profit Nine This Is Profit Nine This Is Profit Nine This Is Minimum Balance and Invalid Two Lips Beaten Way Can Find Subscribe to Thursday Person They Will Subscribe to Thursday Person They Will Give You This Doesn't Give You But They Will From Right to Left With Nothing Against From Right to Left With Nothing Against From Right to Left With Nothing Against Time Being Tattoo Right Wear Moving From Right To Left In Odisha The Right Hand Side Transaction Notification Iffy Already Know The Maximum Elements For The Giver 1.3 Loot The Profit Will Be To The Maximum Volume Set Give The Give The Give The person to switch on the giver bank to the minimum volume Minimum who won the left performance in the morning maintaining maximum value for there right toe function if you never understand why they are maintaining minimum value for solved on Thursday solved on Thursday solved on Thursday point to that point is maximum provided at the point where nothing but calculated for the president of the maximum profit id this point is subscribed - The left minimum ok soiur just read carefully again and you will come to know about Just Right to Drive Very Just Right to Drive Very Just Right to Drive Very Helpful Similarly for the Second at Helpful Similarly for the Second at One Point of Maximum Profit for the One Point of Maximum Profit for the Transaction Raw to Make Maximum of the Transaction Raw to Make Maximum of the Value for the Side of Maximum Profit Subscribe - The Subscribe This Will Also Very Intuitive and Profit Subscribe Maximum Maximum Maximum Slap Transaction Profit Plus Maximum Per Slap Transaction Profit Plus Maximum Per Transaction Profit at a Given Point Transaction Profit at a Given Point IS OK No Latest Go Through This Interval No Patience subscribe The Video then subscribe to the Page if you liked The Video then the world will visit Single Point the world will visit Single Point the world will visit Single Point Do Subscribe Button And Feet 2009 Latest Want To Be Next Point Which Is This 398 Istri Luto Maximum Profit After Taking Only Two Points From Bigg Boss To The Maximum Profit Which Was Previously Calculated Wishes Subscribe Maximum Maximum Profit Subscribe Maximum Maximum Profit Subscribe Previously Subscribe Previously Subscribe Previously Which Will Give What Is The Current President Profit Person Then Which Is The Volume Minimum Wages For - 2 Quest To Okay Sorry But You Will Be Forgiven For The Next Point System Software This Point To That Point What Will Be The Maximum Maximum Maximum Already Calculated To The Current President Already Calculated To The Current President Profit Will Be 2 - 20 For Celebs Subscribe To This Point And Then They Will Again Be Calculated Person The Current Profit Suvichar Net Profit - - Verb - Kunwar Devendra The Calculated Admin Kunwar Devendra The Calculated Admin Values ​​210 To Love You Updated Values ​​210 To Love You Updated Values ​​210 To Love You Updated indicating that even lower price and annual profit maximum Tweet - 134 annual profit maximum Tweet - 134 2nd floor - One who knows the right way will be difficult to win porn quote Vikas Bank of the last day will not Presence Will Not Be Able To Presence Will Not Be Able To Presence Will Not Be Able To Celebrate Her For The Last 1200 Celebrate Her For The Last 1200 Subscribing To Beat Subscribe Will Subscribing To Beat Subscribe Will Start From This Thank You Will Be Ne Subscribe Start From This Thank You Will Be Ne Subscribe The Channel Please subscribe The Channel Please subscribe and subscribe Maximum 04 - 20 2012 Will Feeling This and subscribe Maximum 04 - 20 2012 Will Feeling This Point And Value Karo Point And Value Karo Lobby So Update Dusar Max Value Lobby So Update Dusar Max Value Lobby So Update Dusar Max Value Bid Folded In Value Van Adheen Will Update Religious Value Subscribe No Veer Will Maximum - Liquid Subscribe Now To 9 Video then subscribe to the Page if you Video then subscribe to the Page if you liked The Video then tight hand side patiently indicating a In a given point IE latest se I would In a given point IE latest se I would In a given point IE latest se I would like this point given due point like this point given due point volume maximum profit will be equal to the maximum volume maximum profit will be equal to the maximum profit from this point profit from this point digestive withdrawal in from this point to digestive withdrawal in from this point to point sirvi pati then knowledge for this point sirvi pati then knowledge for this profit subscribe The Channel Please subscribe Do Do Do kid for each point Sundha profit will be kid for each point Sundha profit will be finished with Rs 80 more finished with Rs 80 more profit will be initially three lines will be profit will be initially three lines will be starting with this point one is this starting with this point one is this point 3 ok no way at this point the problem is maximum point 3 ok no way at this point the problem is maximum of the best profit from left of the best profit from left to to to present in the laptop - 108 Atvir subscribe 9 subscribe 9 is half cut this point the maximum value will be is half cut this point the maximum value will be coming gas Maximo already coming gas Maximo already calculated leukemia two plus 350 500 will calculated leukemia two plus 350 500 will give 500 like this will keep give 500 like this will keep give 500 like this will keep values ​​and you will find that will be the maximum profit person 2018 201 9 The time complexity of complexity of Problem in description and subscribe the Problem in description and subscribe the Channel subscribe The Channel Like this is the function is max profit in this this is the function is max profit in this this is the function is max profit in this Enterprises Prohibition Na Dharai subscribe The Amazing Current Position in Its Wake Up Sid Notification Subscribe Channel Ko subscribe The Channel And subscribe The Play Store The Value Amazon Will Be Play Store The Value Amazon Will Be Returning Others Will Process And Will Returning Others Will Process And Will Update problem servi calculating the time of problem servi calculating the time of northern subscribe minus one can another in the northern subscribe minus one can another in the state in the northern states in the state in the northern states in the most obscure no fear in if directly can most obscure no fear in if directly can not skip will always be on its not skip will always be on its own so will always make this clip own so will always make this clip Call Not The Current President On The Call Not The Current President On The President Of So They Can't Be Under Current President Of So They Can't Be Under Current They Can Celebrate Their Bodies Through Themselves They Can Celebrate Their Bodies Through Themselves 1999 Click And Subscribe 1999 Click And Subscribe subscribe and subscribe the Video Subscribe Now I'll Do The Android Android Android Processing Udayveer Volume Maximum Processing Udayveer Volume Maximum Profit And Saw A Very Simple To Enter And Hope Profit And Saw A Very Simple To Enter And Hope You Are Able To Understand This Link You Are Able To Understand This Link For Similar Problems Will Be Present In For Similar Problems Will Be Present In The Food And Solution In Different Languages The Food And Solution In Different Languages Subscribe Benefit From Like Share And Subscribe Benefit From Like Share And Subscribe
2024-03-21 11:17:44
123
https://i.ytimg.com/vi/3…axresdefault.jpg
Best Time to Buy and Sell Stock III | Leetcode #123
W-EfGB0E_ao
given the singly-linked list how can you reverse it recursively that's today's reverse it recursively that's today's video let's get into it hi everyone my name is Steve today we'll go through a legal problem 206 reverse linked lists the solution that we're going through today is to reverse this linked list recursively this is the problem description let's just recap in one more time one two three four five now and when you want to reverse it the output to be five four three two one now so how can we do this recursively let's take a look we'll just use a short example one two three four now how can we reverse in this singly linked list recursively the output needs to be four three two one now let's just have a quick recap about the iterative solution if you want to have a detailed version just check out my other video which we published yesterday about the iterative solution but for now I just have a brief quick recap this is the iterative solution this is the actual code what we did is that we have two notes we initialize the two notes one is called previous previous used to be here and we then we have another node called cur the current node will just stand well assign hat to the current node and every time we go through this iteration there's a while loop you know inside the while loop there are four steps so that each time we'll just keep changing the color in those next pointer to point to the previous node and then keep iterating that's the way how we did it for the iterative solution I hope you can still recall that for the recursive solution it's very similar we write code to do this recursively for us let's take a look first one don't use a recursive function which is very common in a lot of recursive calls so here is our recursive function reverse then we'll take two parameters one is hat and the other is now what is the now now I create a new hat this is the new hand that eventually we're going to return so the base case we'll take a look at this here this is um this is not only in the base case but also the corner case say for example what only a mount linked list where there's only one note which is now in that case in the recursive function what is that first watch at remembering every recursive function there must be an exit case right that's the base case when when does the recursive function needs to return needs to exit out of this recursive call stack that is the base function so in this case hat equals two now in this case hat when we are given an outlet list an empty linked list or when we reached the very end of the last node of a none now linked list that's the case when we need to written that that's the case when we need to return which is written new hat so that's why if say this hat is now and we'll take this now here and then we'll also call reverse function the new hat is also now so we first check if hat equals two now if that's the case what is written you have in this case new hat is awesome now that's it then what then so with the base case down with the Connor case then we'll talk about how we can do a regular case for even then empty and then not make lists how do you do this recursively well just basically to put the iterative function using the recursive way to write it that's it so instead of using previous current won't use a new hat or quite new hat still will use exactly the same four steps to go through the recursive call first we have initialized a new hat remember the four steps in the iterative function we have we create a temporary book on next this is exactly the same we have a temporary book on next how do we get the next which one is the next it is jackpot next we don't need a crib we don't need a crew note we just use hat dot next which is this one this is the next this is the next node then step two first with Christian cost and trees will break this link again why can we break this link and we worry about losing access to the rest of this link nest no because we have a temporary work on next which is the new hat of the second half of this LITTLEST right and and this moment we can simply break this link how do we break that behind assigning the hat but next the pointer of the hat next plundered towards new hat that's how we did it we assign new hat - hat but next this line does two things or just one thing it's just - changing the has next pointer towards new head so that this one's next pointer is pointing to you the new hat and then this link is just a cut off right this is the second step what continue to do this for every single recursive call step three is what changement knew had to be had this is exactly the same as the innovative function how we went with that now this is the new hat and in the very end a new hat is going to be here on top of four and what just returned you hem that that's going to become 421 so we'll keep moving new hat and this point had both new hair and hat are pointing at the node with value 1 since we have moved a new hat here and now hat could be moved to next this that last line of the for stamps hat could be moved to next this is the current status of this linked list it's broken apart into two parts one is headed by the new hat the other pan is headed by the hat then at this point instead of using a 1 we're using the recursive call this is the recursive function recursive meaning is going to call itself right we finished this first recursion then we'll call this recursive function itself which is reverse hat new hat this is the hat this is the new hat well so this is the function itself so it's going to get into it yourself but this time the head and new hat is different previously had is here new hemisphere but now had is here in new hemisphere right so we'll keep calling this now we're entering the second recursion would cost app one of second recursion again we'll initialize a new temper become next this is the next one how do we get this next again that is does happen next this is next now what campus link off by assigning hats next pointer pointing towards new hat this is the second step continue now we'll move new habit of this hats position okay then move hat to next position so we'll keep doing this this is the end of the second recursion well keep calling this recursive function until when until I had equals two now okay let's just go through there are two Manos what go through that real quick so that we can have a better understanding of how this simple lick the list with four knows how it goes through this recursive function now we'll start the third recursive call hat is not equal to now so it's not going to enter here well assign a terrible next is going to be this is going to be the new next now we break this link by an assignee hat next pointer into new hat and then we'll move new hat over here then hat is going to be next so this is the end of the third recursive call right third we close it's all finished now hat is here so he'll is still not now right hand is still not now so it's not going to come over here instead it's going to create a one more temporary book our next well break this link apart - Annie has next pointed towards new hat and then when we're do is well move new hat to your hats position and then hat will become next at this point the fourth when a cursive call is finished remember there are a total of four linked list nodes at the end of the fourth week urgent call hat is standing at the very now point that's the end the next pointer of the tail of the original linked list right at this point it's about to stand the fifth on recursive call in this case it's going to check here then is going to enter here because hat is now at this point right at that moment what are we going to do we're just going to return new hat that's it this is the new hat take a look here four three two one now this is the correct output that we are that we want to do with it that's it time complexity of this album is still om suppose the length of the linked list is n there are n those some of the time complexities oh and this time connected space complexity is going to be Olin because we need extra space for the cost act for the recursive cosmic at most it could go up to n Lambos so space complexity is o n as well now let's quickly put idea into the actual code using the recursive way let's let's see we copied this list node we'll just call it return reverse ad and then we'll implement private the helper function the recursive function called reverse so first as I said we need a base c'n base condition on the break condition for average for every recursive function it needs to have a break condition what about check is if had equals to you now what world to is will return new tab directly right that's the base condition and also the kana case whenever we reach the very end the next node of the tail node was just written the new hat that's it and then we'll have that four steps which is initialize a terrible or next which is hat dot next so since we have initialized a new variable to be the new head of the second part of the linked list what we can do is that we can break the hat dot next current link by assigning it to the new hat right and at this point this this given original linked list is broken apart into two parts one is headed by new hat the other is headed by the original hat and then we want to do is what we want to do is well move new have to become the Hat and then hat will become the next so both of them will move towards the right that's it these are the four steps very similar to what we did in the iterative function again in the end were just three to reverse and and the new head so what keep doing this remember both had a new hat they moved towards them right after this one recursive call stack so we'll move both of them towards the right someone just continued to call this recursive function reverse hat / a comment new hat so this is the recursive function itself now let's hit some min and see all right example 100% 90 yeah this is the yeah this is the recursive function if this video helps you to understand how they would curse a function - we could to reverse a singly linked the list of works please do me a favor and hit that like button just destroyed the like button and don't forget to subscribe to my channel and tap the little bound on vacations and that each time one I publish a new video you're not going to miss out on anything and we are right now going through a linked list serious after this will go through a tree series and after them will go through more advanced data structures to help everyone better prepare for their upcoming in the concluding interview questions that's it for today's video I'll see you guys in
2024-03-22 09:56:15
206
https://i.ytimg.com/vi/W…axresdefault.jpg
LeetCode 206: Reverse Linked List RECURSIVELY - Interview Prep Ep 60
x9OpPopLlQ0
200 Hello guys and I am now going to explain the list to the dairy challenge get maximum engine rated challenge get maximum engine rated okay to question me de rakha your given okay to question me de rakha your given in teacher has said are the norms for in teacher has said are the norms for age plus one is generated and the following pet age plus one is generated and the following pet ok hai kuch complication de rakha meaning ok hai kuch complication de rakha meaning Initially it seems over-whelming Initially it seems over-whelming that this is mid-2012 7102 1821 E Request OO that this is mid-2012 7102 1821 E Request OO Name Saheb Number Two * I plus one is equal Name Saheb Number Two * I plus one is equal to Nashik Two plus according to plus one Okay so to Nashik Two plus according to plus one Okay so tell me a little bit So they are continuously shooting that tell me a little bit So they are continuously shooting that this this this field to approach such problems better that I printed it is ok so I wrote it, I took it and looked at it and if you see it written then it can shine that what else is this, in reality nothing is happening anyway. In this, only this is what is there, * is you * is representing that China Indexes of The Amazing * * is representing and indexes is ok, so it means if there is even induction then make me Nav Cyber ​​Two and if there are more inductions then come If you want to do 8 plus one, then okay, If you want to do 8 plus one, then okay, If you want to do 8 plus one, then okay, today I have given 10 to myself. I have kept it tied to one. today I have given 10 to myself. I have kept it tied to one. Okay, now when I come to do, I want to Okay, now when I come to do, I want to divide it into pieces, I am making it, so divide it into pieces, I am making it, so I will post one here, okay. I will post one here, okay. Till now this record is good meaning it is fine then Till now this record is good meaning it is fine then in this case I will request then Vansh you have come, it is in this case I will request then Vansh you have come, it is fine then I have to come and you have to fine then I have to come and you have to write I plus one, it is fine so it has become you are write I plus one, it is fine so it has become you are fine, actually this side has come plus plus one. fine, actually this side has come plus plus one. Okay, so in this way then this is very wow so Okay, so in this way then this is very wow so forward to cigarette that point I have forward to cigarette that point I have written five here and so it has more fiber written five here and so it has more fiber 231 of 2036 in this I 231 of 2036 in this I rather consume olives order so three rather consume olives order so three plus points 372 okay then plus points 372 okay then plus points 372 okay then this ancestral it was neither in one place I will write forecast for element node and so instead of note I will write and plus 5 this pimple two four is okay okay so what is 10:00 I I I will order at 11:00 so what will happen in this case, the will order at 11:00 so what will happen in this case, the successful test of these two plus two is equal successful test of these two plus two is equal to five and the natives can fly z10 in that to five and the natives can fly z10 in that case will have to husband Daniel subscribe case will have to husband Daniel subscribe loot liya hai now I will do it is quite loot liya hai now I will do it is quite simple like simple like simple like that it seems like the browser is baked with his hands so first of all of course S 21 will be made that so first of all of course S 21 will be made that one pan is equal to zero a written 1580 ok name is made marital vector at number one plus one in question That which n to inches plus one size That which n to inches plus one size That which n to inches plus one size business person will become not initialized business person will become not initialized number 1 120 name juice one is equal to two one number 1 120 name juice one is equal to two one ok and I am aloe vera result for me ok and I am aloe vera result for me in the question rate and four hour which shine in the question rate and four hour which shine 11082 in this whatever is my maximum number 11082 in this whatever is my maximum number return me. return me. return me. Contra Voucher because right now it increases initially, it is very small, it is okay, right, the point is equal to two to two, it is difficult-2 plus, okay, what I told you, on this side, one percent is in Equal to zero tapas Equal to zero tapas Equal to zero tapas tyaag karna hai Namaskar aaye equal to numbers tyaag karna hai Namaskar aaye equal to numbers IS by to go IS by to go ki aapke khas episode 122 tab kya naam saaye ki aapke khas episode 122 tab kya naam saaye equal to numbers by bittu plus norms this is equal to numbers by bittu plus norms this is back to plus one okay so that's it back to plus one okay so that's it question is over return methods question is over return methods Every number of the question has to be Every number of the question has to be checked after opening the kinnar number element, so to checked after opening the kinnar number element, so to update the result, one thing we update the result, one thing we express is Om Namah Shivay, it is express is Om Namah Shivay, it is good, not good, not based, I know, based, I know, vitamin E result, let's color food and key table, vitamin E result, let's color food and key table, play list that play list that No differences it seems to be working No differences it seems to be working fine hai fine hai ki accepted so text message ghar understood ki accepted so text message ghar understood video achhi lagi ho to jupiter like video achhi lagi ho to jupiter like thank you a
2024-03-19 18:05:08
1,646
https://i.ytimg.com/vi/x…axresdefault.jpg
LeetCode 1646. Get Maximum in Generated Array | January Daily Challenge | C++ | Array
5ilLt2LMO6s
hey guys persistent programmer over here and today we're gonna do another really and today we're gonna do another really cool question majority element okay so cool question majority element okay so given a size of given an array of size n given a size of given an array of size n find the majority element and what is find the majority element and what is this majority element well the majority this majority element well the majority element is a element that appears more element is a element that appears more than n over two times where n is the than n over two times where n is the length of the array so let's look at length of the array so let's look at this input where we have three elements this input where we have three elements in the array and we're gonna do n over 2 in the array and we're gonna do n over 2 so 3 over 2 which gives us 1 point 5 so so 3 over 2 which gives us 1 point 5 so this is the threshold we need to compare this is the threshold we need to compare against each of the frequencies in ireri against each of the frequencies in ireri so we can see that the frequency of 3 so we can see that the frequency of 3 here is 2 which is greater than 1.5 so here is 2 which is greater than 1.5 so this element does qualify and the this element does qualify and the frequency of 2 is only 1 so 1 is less frequency of 2 is only 1 so 1 is less than 1.5 right so it does not qualify than 1.5 right so it does not qualify and this is really important for this and this is really important for this question question oops so this is really important when oops so this is really important when they say that you may assume that the they say that you may assume that the array is non-empty and the majority array is non-empty and the majority element always exists so these are the element always exists so these are the exception conditions that we don't need exception conditions that we don't need to check for in this question and to check for in this question and they're telling us that yes this there they're telling us that yes this there will be an element that is qualifies for will be an element that is qualifies for this condition ok so yeah let's look at this condition ok so yeah let's look at let's look at some solutions and discuss let's look at some solutions and discuss how we can solve this problem the first how we can solve this problem the first solution that immediately came to my solution that immediately came to my mind when I saw this problem was to mind when I saw this problem was to create a dictionary and map all the create a dictionary and map all the frequencies of each element so here we frequencies of each element so here we have 3 and 3 occurs twice so we can say have 3 and 3 occurs twice so we can say it's frequency s 2 and then 2 occurs one it's frequency s 2 and then 2 occurs one one time so it's frequency is 1 and then one time so it's frequency is 1 and then iterate over this map and check for the iterate over this map and check for the condition so we'll just check the values condition so we'll just check the values and see if it is greater than our and see if it is greater than our threshold which is in this case 1.5 threshold which is in this case 1.5 so let's look at another example here so so let's look at another example here so we have an input array like this so for we have an input array like this so for this array n is 7 and 7 over 2 is 3.5 so this array n is 7 and 7 over 2 is 3.5 so we're gonna compare against 3.5 and we we're gonna compare against 3.5 and we can see that the occurrence of 2 is 4 so can see that the occurrence of 2 is 4 so 4 is greater than 3.5 and this is how 4 is greater than 3.5 and this is how we'll get our answer so this solution is we'll get our answer so this solution is pretty straightforward pretty straightforward we just create our dictionary and then we just create our dictionary and then iterate over the dictionary and return iterate over the dictionary and return the element with our highest frequency the element with our highest frequency and the time complexity for this is and the time complexity for this is often okay let's quickly look at this often okay let's quickly look at this code and then we can see how we can code and then we can see how we can optimize this solution further great so optimize this solution further great so I'm back in the code and the first thing I'm back in the code and the first thing I've done is I've created my threshold I've done is I've created my threshold which is n over 2 so we're taking the which is n over 2 so we're taking the length of the number array and dividing length of the number array and dividing it by 2 and I've also created my it by 2 and I've also created my frequency dictionary here and the next frequency dictionary here and the next thing I did is I'm iterating over my thing I did is I'm iterating over my nums array and I'm just populating the nums array and I'm just populating the frequency of that number so if we see frequency of that number so if we see the first time the frequency is 1 and if the first time the frequency is 1 and if we encounter it again we're just adding we encounter it again we're just adding to that frequency ok and after all of to that frequency ok and after all of that is done that is done I'm iterating over each item in the I'm iterating over each item in the dictionary and I'm just checking if that dictionary and I'm just checking if that frequency is greater than the threshold frequency is greater than the threshold that we defined up here so after doing that we defined up here so after doing that I'm just returning the digit and we that I'm just returning the digit and we know that the question says that there know that the question says that there will always be an element which has a will always be an element which has a majority so that's why I did not put majority so that's why I did not put another return outside this for loop ok another return outside this for loop ok so let's go ahead and submit ok great so so let's go ahead and submit ok great so that works now instead of creating this that works now instead of creating this additional space for this frequency additional space for this frequency dictionary is there a way we can dictionary is there a way we can optimize this space by optimize this space by just using our nums array so that is just using our nums array so that is optimization we will look at next for it optimization we will look at next for it this solution great so the optimization this solution great so the optimization that we are going to decide now is how that we are going to decide now is how to optimize the space for this algorithm to optimize the space for this algorithm like can we solve this problem in like can we solve this problem in constant space and thus we're more constant space and thus we're more sporting algorithm comes in handy and I sporting algorithm comes in handy and I will just walk through the high-level will just walk through the high-level idea of what this algorithm means first idea of what this algorithm means first before looking at the code so if we had before looking at the code so if we had a candidate profile like this where we a candidate profile like this where we had a a B B and then a so we can see had a a B B and then a so we can see here that okay well if I was at this here that okay well if I was at this position then my winner my winning position then my winner my winning candidate would be a with the majority candidate would be a with the majority of votes right and okay well let's say a of votes right and okay well let's say a has two votes and then if we're here has two votes and then if we're here we know that okay well B has two votes we know that okay well B has two votes and this is a tie but our question says and this is a tie but our question says that the majority element always exists that the majority element always exists in this array so that's why this this in this array so that's why this this under this is very important and we know under this is very important and we know that the last element here this is the that the last element here this is the determining element that determines determining element that determines which candidate wins which candidate wins so okay so if these two were canceled so okay so if these two were canceled and our winning candidate here is a well and our winning candidate here is a well is there a way we can devise an is there a way we can devise an algorithm to keep count of these algorithm to keep count of these candidates as we iterate through the candidates as we iterate through the array so that's essentially what the array so that's essentially what the Moore's voting algorithm is trying to Moore's voting algorithm is trying to solve so let's look at another example solve so let's look at another example here so here let's say our array looks here so here let's say our array looks like this and we have our first like this and we have our first candidate a so our winning candidate at candidate a so our winning candidate at this point is a and well when I move to this point is a and well when I move to the next item in the array I see that the next item in the array I see that well a has one vote and the next element well a has one vote and the next element is not a so when that happens I do a is not a so when that happens I do a minus 1 here from my previous candidate minus 1 here from my previous candidate and and I can see that okay well B has one vote I can see that okay well B has one vote here and we will just shift our here and we will just shift our candidacy to B so for now we can say candidacy to B so for now we can say that B is our new candidate okay that B is our new candidate okay so that's fine so we add one counter to so that's fine so we add one counter to our B and then we add another counter our B and then we add another counter and B has three votes now and then when and B has three votes now and then when we're back at this a while we do the we're back at this a while we do the same thing we minus one from here but same thing we minus one from here but these still has the two votes so in this these still has the two votes so in this case the majority is the candidate B case the majority is the candidate B here so that's the same method we will here so that's the same method we will use to solve this problem so every time use to solve this problem so every time we see a different candidate we just we see a different candidate we just minus one from our previous candidates minus one from our previous candidates count and if this brings us to a zero count and if this brings us to a zero what does that tell us that means that what does that tell us that means that that candidates votes are no longer that candidates votes are no longer valid at that specific point so in this valid at that specific point so in this array if we if we cut that right here we array if we if we cut that right here we had a zero over here because is both no had a zero over here because is both no longer matter as we have the same number longer matter as we have the same number of A's and B's right so that's the of A's and B's right so that's the general idea to solve this algorithm now general idea to solve this algorithm now let me summarize what we need to do in let me summarize what we need to do in our code before we look at the code so our code before we look at the code so what we need to do is create a counter what we need to do is create a counter to do this minus one from the previous to do this minus one from the previous candidates frequency and what we're candidates frequency and what we're gonna do is we'll just start with this gonna do is we'll just start with this candidate as our majority candidate and candidate as our majority candidate and then iterate through the array to find then iterate through the array to find who is actually the majority candidate who is actually the majority candidate and then we're just gonna minus one if and then we're just gonna minus one if we see a next element that is not the we see a next element that is not the same candidate other previous element same candidate other previous element and if the counter is zero then we move and if the counter is zero then we move on to the next candidate because as I on to the next candidate because as I mentioned that means that the post bolts mentioned that means that the post bolts have balanced out okay so the time have balanced out okay so the time complexity for this is the same so it complexity for this is the same so it will be our fan will be our fan and the space complexity will be done in and the space complexity will be done in place so we're not taking up any extra place so we're not taking up any extra space we won't be creating a dictionary space we won't be creating a dictionary or map so that's why this is more or map so that's why this is more efficient than our previous solution efficient than our previous solution okay well if all of this makes sense okay well if all of this makes sense then let's look at the code okay so I'm then let's look at the code okay so I'm back in the cooler and what I've done is back in the cooler and what I've done is I just commented out with my previous I just commented out with my previous solution with the dictionary and here I solution with the dictionary and here I have the more optimized solution for have the more optimized solution for this problem so what I've done first is this problem so what I've done first is I've initialized my count to zero and I I've initialized my count to zero and I just said the majority candidate to none just said the majority candidate to none initially and then as we iterate through initially and then as we iterate through our noms array what I'm doing is I am our noms array what I'm doing is I am just setting the majority candidate to just setting the majority candidate to numb if the count is zero so in the numb if the count is zero so in the first case what will happen is this first case what will happen is this majority candidate will be initialized majority candidate will be initialized to the first number in the array and to the first number in the array and then what we're doing is we're checking then what we're doing is we're checking if the number is equal to the majority if the number is equal to the majority candidate then so what this means is if candidate then so what this means is if we have like three three so if the next we have like three three so if the next item is the same as the majority item is the same as the majority candidate then we just add account to candidate then we just add account to that majority candidate right so we're that majority candidate right so we're it's like they got the boat so that's it's like they got the boat so that's why we're increasing the count here and why we're increasing the count here and if it's a different I'll if it's a if it's a different I'll if it's a different candidate than we just - different candidate than we just - account so we're d-- commenting the account so we're d-- commenting the count here and in while iterating count here and in while iterating through this route loop at any point if through this route loop at any point if our count is zero that means we know our count is zero that means we know that that previous that previous that that previous that previous candidates votes doesn't matter anymore candidates votes doesn't matter anymore because there are in our boats from the because there are in our boats from the new candidate so that's how it equal to new candidate so that's how it equal to zero and if we if that case happens and zero and if we if that case happens and we're just setting the majority we're just setting the majority candidate to that next number in the candidate to that next number in the array okay and lastly what we're doing array okay and lastly what we're doing is we're returning the majority can is we're returning the majority can okay awesome so I have both these codes okay awesome so I have both these codes in the description below so check that in the description below so check that out if you want to try it yourself okay out if you want to try it yourself okay let me submit this code awesome accepted let me submit this code awesome accepted I hope you enjoyed this video if you I hope you enjoyed this video if you like my videos please subscribe to my like my videos please subscribe to my channel alright happy coding guys
2024-03-21 14:02:19
169
https://i.ytimg.com/vi/5…axresdefault.jpg
Majority Element - Leetcode 169 (Python) - 2 Solutions with code
gOMx2pHFOuY
hey hey everybody this is larry this is day three day three of the july lego day challenge of the july lego day challenge uh hit the like button in the subscriber uh hit the like button in the subscriber and join me on discord let me know what and join me on discord let me know what you think about this problem uh yeah you think about this problem uh yeah happy sunday or saturday night depending happy sunday or saturday night depending on where you are this saturday night for on where you are this saturday night for me and the contest is in about two hours me and the contest is in about two hours for the lead code so if you're doing for the lead code so if you're doing that good luck if not uh which give me that good luck if not uh which give me all your luck for now then all your luck for now then all right let's go uh today's problem is all right let's go uh today's problem is rico sub sequence what uh okay rico sub sequence what uh okay it's a sequence where the difference it's a sequence where the difference between subsets of numbers are between subsets of numbers are successive numbers are strictly successive numbers are strictly alternating between positive and alternating between positive and negative okay so it doesn't it so means negative okay so it doesn't it so means that the numbers don't even matter it it that the numbers don't even matter it it it's just positive or negative okay and it's just positive or negative okay and this is a subsequence not a this is a subsequence not a okay i just want to make sure that okay i just want to make sure that subsequent does not stop away i've been subsequent does not stop away i've been messing that up lately as well just a messing that up lately as well just a few times so few times so uh reading is kind of important okay uh reading is kind of important okay oh wait that missed something oh wait that missed something the differences is negative uh positive the differences is negative uh positive or negative okay so or negative okay so so so the numbers do matter my fault um so so the numbers do matter my fault um i thought that um i thought that um for some reason i just started i yeah i for some reason i just started i yeah i don't know i didn't i missed a delta don't know i didn't i missed a delta part so i still misread it but you know part so i still misread it but you know only like for 10 seconds so 20 seconds only like for 10 seconds so 20 seconds so it's okay so guys so basically you're so it's okay so guys so basically you're trying to go up and down and up and down trying to go up and down and up and down and up and down or something like this and up and down or something like this right right um um okay and the follow-up is gonna solve okay and the follow-up is gonna solve this in linear time um so basically there uh so my first instincts instinct is just basically um dynamic programming right and you can do with n is equal to a thousand dynamic programming is going to be quite fast enough if you do some n square thing where um this would be the biggest um uh uh or the yeah the longest sequence in the dag or something like that and there's like a or you know largest uh yeah yeah longest path in the dag uh longest path in the dag is gonna be n square in a way you know in a in a without any context or without any like observation um that alone will give us an n square and a correct solution now can we get o of n right or if n probably requires some observation to make it a little bit better the um if i want to aim for oven and some of this as a hint knowing that there is a no event solution i might try to do two things right or a couple of things my ideas are greedy so i am something just live i quality obviously don't know it yet um though i do have the n square solution in the back of my head but if i need to but yeah my idea is maybe greedy will figure it out two is some kind of stacked bass mono mono mono uh mono stack type situation um because for every number we're basically i mean we can think about it from the dynamic programming solution right the longest path in the dag is that for every number um i know that i've been i hand waved over that part a little bit but for every number you draw a dag to the previous number and then the two graphs that you can do it with um or not two graphs sorry there's a duo right where you're reaching the the current number let's say we have all right let me just put it here then going over the n squared solution real quick let's say for some number we draw a diagonal previous number if if um you know there's two two versions of the nine say right one is where we get to the nine and then the next number we want it to be increasing or we want the next number to be decreasing right and of course in that case if the next number is increasing that means that the previous number is um decreasing and and so forth the other way around as well um so that means that for the here we can draw a dag to the previous one let's say we have a nine that is you know nine next number is increasing that means that the previous number is decreasing that means that there's an edge from nine to four to four um and from one to nine right so that's basically the idea behind this pro behind n square solution so one thing that i would try to think so one thing that i would try to think about is about is you know given all the numbers that are you know given all the numbers that are smaller than 9 smaller than 9 take the min take the min of all those numbers right also i take of all those numbers right also i take the max the max of the or not not the max of the value but the max of all the numbers all the things that are inside that number right so i think we can do it maybe let's see right let's say we want the let's see right let's say we want the numbers increasing so numbers increasing so um i think for for that kind of thing um i think for for that kind of thing we're trying to figure out the invariant we're trying to figure out the invariant right so right so here we have for example i think one thing i'm not super clear about is let's say we have something like one for um you know let's say one is equal to one of course and this is kind of like longest increasing subsequence almost from here uh four we have one oh sorry two we have a four and then three we have a nine right um and then now now let's say we have a three okay i guess we do three here and then we do a binary search right so i guess in that sense actually yeah i mean i think this is now just you know of course the two you have to do both and then you have to alternate them and group tracking them but now i think we've reduced the problem from o of n squared to n log n by converting this to uh li s right which is longest increasing subsequence and as i said this is dp of course um or you know uh and and of course there's an over n log n solution um which we kind of have hinted at here but i'm not going to go over that today because that's also in that case also in that case some of this is a little bit better in some of this is a little bit better in that if that's the case i feel like that if that's the case i feel like medium's a little bit too easy for it uh medium's a little bit too easy for it uh or like too low of a rating for it it's or like too low of a rating for it it's harder than a medium maybe um okay so is harder than a medium maybe um okay so is there something even there something even better so we want an increasing so we want so we want an increasing so we want something that's something that's whatever and even here right we have we whatever and even here right we have we moved to seven moved to seven [Music] [Music] but maybe that's okay i mean that's but maybe that's okay i mean that's still going to be analog again i don't still going to be analog again i don't know that know that no and i don't know how the stack based solution would work because that's let's say we have one four and nine on the stack and then now the two comes in the two erasers it but but then let's say we have another 10 next right well the 10 we actually won the 4 9 and 10. so i don't know that the stack would work so if i have to guess and some of this like it's like it's cheating in in the sense that i'm working from this um working backwards from the solution otherwise to be honest i probably would have been one happy with the n square and then maybe even happy to end like well definitely happy with the n log n um but o n i i think we have to maybe make another um we have to make some sort of other uh another observation or something like uh another observation or something like this right this right um huh huh i'm trying to think about the linear i'm trying to think about the linear solution solution um for this one and for those of you who um for this one and for those of you who might be joining me a little bit late or might be joining me a little bit late or skip forward uh huh i don't know that i skip forward uh huh i don't know that i haven't but if you are looking for an n haven't but if you are looking for an n square or n log n we kind of have it we square or n log n we kind of have it we haven't implemented it but let's see right so the max is going to be so the max is going to be i don't know huh i don't know huh i mean i mean maybe there's a greedy thing that i'm maybe there's a greedy thing that i'm not aware of but um linear time and i hope that this isn't a linear time based on the fact that you know the the thing is you know linear huh huh i'm not gonna lie i'm having i'm i'm not gonna lie i'm having i'm bringing out a bit hmm hmm don't know that i know this one no to be don't know that i know this one no to be honest honest uh oh i guess there is i think i'm just overthinking it a little bit um because i i think there is can i prove it though can i prove it though [Music] [Music] because basically the idea here is that because basically the idea here is that looking at the four let's say we're looking at the four let's say we're going downwards right going downwards right well well if we're going down if we're going down then that means that then that means that um um well that means that our longest well that means that our longest streak is gonna be down or we just streak is gonna be down or we just take the previous take the previous one skipping this number right does that one skipping this number right does that make sense let me see let me see i mean i think i have the idea to be i mean i think i have the idea to be honest but i'm trying to think about how honest but i'm trying to think about how to explain it and how to prove it to explain it and how to prove it um but basically the idea is almost like um but basically the idea is almost like um um like this idea of like digit dp right is because because the things i have here are easy to prove for me um so that's why i would gravitate but maybe you have something like for a previous current and for a previous current and again you know that i like doing this again you know that i like doing this though though uh maybe only for competitive for real uh maybe only for competitive for real thing don't do it but yeah so that you thing don't do it but yeah so that you have some like longest is equal to zero have some like longest is equal to zero maybe one but whatever um yeah then maybe one but whatever um yeah then current is equal to one just because you current is equal to one just because you always have one sequence right um and always have one sequence right um and then here uh rather maybe that's not it then here uh rather maybe that's not it maybe what we want is best um [Music] uh positive and then that's negative right and maybe they're both one actually and then we don't need the longest and then here then you can we represent them in terms of you know like if the current one is bigger than the previous then what do we do right that means that we want to increase the um so best negative is equal to the so best negative is equal to the previous best positive previous best positive plus one plus one and then the best positive and then the best positive we just kind of ignore it right we we we just kind of ignore it right we we just keep on going just keep on going um um and then else if c is less than p then and then else if c is less than p then we we do kind of the same but opposite maybe do kind of the same but opposite maybe this is even wrong maybe i typed it too this is even wrong maybe i typed it too fast to be honest uh best fast to be honest uh best positive is positive is going to be best going to be best negative plus one and best negative negative plus one and best negative right by skipping this number i might have the signs wrong but um i might have the signs wrong but um and then we just have to return max to and then we just have to return max to best positive and best negative i i i best positive and best negative i i i feel like so that's my intuitive sense feel like so that's my intuitive sense um but i definitely feel like if you're um but i definitely feel like if you're at home and you're like what is larry at home and you're like what is larry doing um doing um uh how is he explaining this you're not uh how is he explaining this you're not wrong so i'm trying to think about it a wrong so i'm trying to think about it a little bit um this is right little bit um this is right okay but uh 824 day streak let me let me okay but uh 824 day streak let me let me gather my dots a little bit to kind of gather my dots a little bit to kind of explain this explain this but first of all this is dynamic but first of all this is dynamic programming and the way that i would programming and the way that i would maybe think about it maybe think about it instead of writing it this way is maybe instead of writing it this way is maybe we could rewrite it really quickly because i uh because the way that we because i uh because the way that we write a little bit is um write a little bit is um let's say let's say get max last digit is positive or last get max last digit is positive or last delta is positive say um yeah then you have index and then you also say have another one get max last negative um okay i think i'm going to prove it by code so i don't know so now we want to return max of get max where the last number is positive of n minus 1 i get max last negative n minus 1 and n is equal to length of numbers obviously so here um um yeah yeah and then that means that what does it mean when the last delta is positive right when the last num delta is positive we we want to look at the previous one that is want to look at the previous one that is negative negative right right so the only two scenarios right um so the only two scenarios right um [Music] um hmm so basically we have two numbers right so previous number is equal to uh num sub index minus one say and current number is equal to num sub in index and then now if um hmm sorry friends i got an emergency message and you know i don't like to cut away so if you watch that sorry about that but yeah so now we want that if this is true then um yeah let's see best is equal to one because we always have at least one item if this is the case then what happens right then we want one to take the current max or get max get max of last negative because now that you go of last negative because now that you go to the so now we want to add an edge to to the so now we want to add an edge to it it um um oops oops right and then now else if the current right and then now else if the current is bigger than previous then what is bigger than previous then what happens right well happens right well if that's the case then here we just oh i see okay i think there was a part that was missing right so if this one number is bigger than the previous number uh uh positive of index minus one right and positive of index minus one right and then just return best maybe this isn't then just return best maybe this isn't even the right code but now i understand even the right code but now i understand the logic um so i think this is the the logic um so i think this is the point where point where uh to be honest and this is very slow uh to be honest and this is very slow but it's very easy to kind of go into but it's very easy to kind of go into your intuition at least for me i lean on your intuition at least for me i lean on experience to kind of view out the exp experience to kind of view out the exp but i had trouble understanding why this but i had trouble understanding why this was the case so the reason why this is was the case so the reason why this is the case is because the case is because let's just have an example right let's let's just have an example right let's just let's just say you have an example just let's just say you have an example where you have one where you have one uh uh actually just like this one right actually just like this one right whatever let's say we have this case whatever let's say we have this case let's say we're let's say we're um um let's say we are here let's say we are here so the last num so we want to look for so the last num so we want to look for okay actually here because then the last okay actually here because then the last number is a positive and then we're number is a positive and then we're going here right so that means that going here right so that means that we're looking for a previous number and we're looking for a previous number and there are only two cases right let's say there are only two cases right let's say this is a two well what does that mean this is a two well what does that mean or well okay let's say this is a seven or well okay let's say this is a seven what does that mean well that means that what does that mean well that means that this is the case um and because this is this is the case um and because this is the case we could just continue the the case we could just continue the streak and then the other example is streak and then the other example is that this is smaller right well we that this is smaller right well we cannot continue the streak for obvious cannot continue the streak for obvious reason but we can inherit that streak reason but we can inherit that streak what i mean by that is that so let's say what i mean by that is that so let's say just one two right you have this streak just one two right you have this streak of one two and then in a greedy way what of one two and then in a greedy way what we're doing now is taking the four okay we're doing now is taking the four okay we say okay the four cannot add it here we say okay the four cannot add it here because then it's not a wrinkle because then it's not a wrinkle subsequence but in a greedy kind of way subsequence but in a greedy kind of way four can be here right so you basically four can be here right so you basically replace the one two with a one four here replace the one two with a one four here and that's basically the idea behind and that's basically the idea behind uh this other logic which we had from uh this other logic which we had from the other solution as well i'll put the other solution as well i'll put bring it back up real quick i'm really bring it back up real quick i'm really slow today sorry a little bit distracted slow today sorry a little bit distracted one of my good friends is visiting me one of my good friends is visiting me from from from abroad and gives a message to me from abroad and gives a message to me like like panicky uh i'm lost in new york panicky uh i'm lost in new york situation so situation so and so it's a little bit timely my and so it's a little bit timely my apologies but hopefully so with this apologies but hopefully so with this insight that's basically what this code insight that's basically what this code does um does um i am usually i am going to uh expand i am usually i am going to uh expand this out and this out and and on you know and go over to the deep and on you know and go over to the deep the how to do the dynamic programming the how to do the dynamic programming part but that's this is really most of part but that's this is really most of it to be honest um and of course the it to be honest um and of course the thing that i would say is that now you thing that i would say is that now you have to add memorization have to add memorization and stuff like that and stuff like that but but but but but this is really the idea right so now but this is really the idea right so now this is last one is negative so we want this is last one is negative so we want it to be positive so we have something it to be positive so we have something like this like this uh hmm i might i might have messed this up hmm i might i might have messed this up actually actually that's negative here oh yeah because we the logic is the same but then when you inherit the last thing it would have to be negative so that's why this is the case um instead of positive sorry i i um basically going just to be a little bit clearer just to do it again basically if you have a case where you have one two um what we did is we converted to one four with a four and now we're looking for a the next the last number to be decreasing right so that's basically what you're doing um and the next number is decreasing as well because now the four is now the peak instead of the the rally right so that's basically the idea here um so yeah so usually i will do this but um i i think today there's a lot of things going on this is the solution that i recommend um but with the explanation that we talked about about um overriding over inheriting um and this is basically that code written in a different way let me just run it real quick um of course this is going to time out for bigger ends because this is not cached and of course maybe i will typo or something let's see if the previous is greater than here uh maybe i have the science one it is tricky to kind of get right now that i'm just confusing myself and to be honest i'm a little bit watching it because i'm uh trying to deal with this issue uh but okay maybe i'm just wrong in here but but mostly due to either typo or something like that um so i apologize if this this video is a little bit yucky but uh but i think the solution is to um you know look into here and then the idea that i would talk about um is just like i said if you have one um maybe i had it right the first time maybe i had it right the first time maybe i confused myself a little bit maybe i confused myself a little bit actually by writing it uh well it's too actually by writing it uh well it's too too bad i i think i removed it by too bad i i think i removed it by accident so um yeah okay but the idea is accident so um yeah okay but the idea is still that let's say if the still that let's say if the last number is uh increasing last number is uh increasing then you basically want to then you basically want to use this to replace that number but use this to replace that number but keeping its either valley or the top or keeping its either valley or the top or the bottom so that's basically the idea the bottom so that's basically the idea um i know this video is a kind of yucky um i know this video is a kind of yucky um sorry about that i really gotta run um sorry about that i really gotta run um usually i have better time setting um usually i have better time setting but this is long weekend and stuff like but this is long weekend and stuff like this everything's chaos so uh that's all this everything's chaos so uh that's all i have for today uh let me know if you i have for today uh let me know if you just explain uh this explanation is good just explain uh this explanation is good enough for you if not ask some questions enough for you if not ask some questions in the comments come to discord ask some in the comments come to discord ask some questions happy to answer it i'll see questions happy to answer it i'll see you later stay good stay healthy to good you later stay good stay healthy to good mental health mental health take care bye
2024-03-24 11:43:16
376
https://i.ytimg.com/vi/g…axresdefault.jpg
376. Wiggle Subsequence - Day 3/31 Leetcode July Challenge
Bzzu4vAozYA
hey guys this is you sir how's it been going going in this video I'm going to take a look in this video I'm going to take a look at nine to one minimum add to make at nine to one minimum add to make current is valid we're given a string current is valid we're given a string and a string ends of left parenthesis and a string ends of left parenthesis and right parenthesis we add the minimal and right parenthesis we add the minimal numbers of parentheses and so that the numbers of parentheses and so that the represent appearances are invalid well represent appearances are invalid well take a look at this because this one is take a look at this because this one is invalid so we only need to add two left invalid so we only need to add two left one right add the one more left one right add the one more left parenthesis bat it to one and this one parenthesis bat it to one and this one is three left Prentiss we add need add is three left Prentiss we add need add to add we need to add three references to add we need to add three references for this one is bad a zero this one is for this one is bad a zero this one is this one is flatted two left right and this one is flatted two left right and two left so forth so obviously the two left so forth so obviously the minimum add actually because if only one minimum add actually because if only one pair one pair is very rare one pair of pair one pair is very rare one pair of friends is valid so actually if you friends is valid so actually if you remove the valid ones there there will remove the valid ones there there will be an invalid print is left and to be an invalid print is left and to remove to make this valid we need to add remove to make this valid we need to add the corresponding left or right right the corresponding left or right right four like this to four for invalid four like this to four for invalid Prentiss when you ask for corresponding Prentiss when you ask for corresponding practice to make them better so the practice to make them better so the problem becomes we need to find the problem becomes we need to find the invalid print account while for the for invalid print account while for the for the invalid Parente account it might be the invalid Parente account it might be only one case that the right right for only one case that the right right for this is put before left where it says this is put before left where it says right if you look through this array right if you look through this array like this if you just take a look to the like this if you just take a look to the first one its left well of course it's first one its left well of course it's invalid right because only one left for invalid right because only one left for instance doesn't make anything now we instance doesn't make anything now we have a right one it's valid because this have a right one it's valid because this is already a left one to the left and is already a left one to the left and this will be valid and then we met the this will be valid and then we met the second second right Prentiss there's no second second right Prentiss there's no more left more left so it's invalid right and then this one so it's invalid right and then this one is invalid and now that this one it of is invalid and now that this one it of course is invalid invalid so I think we course is invalid invalid so I think we could just keep track of how many could just keep track of how many unmatched left parenthesis and unmatched left parenthesis and references are to make two to two references are to make two to two - to get a result right so I'll say let - to get a result right so I'll say let invalid left:0 that in backing run it invalid left:0 that in backing run it right to 0 this is the count of last right to 0 this is the count of last Prentice okay Catholic or the right Prentice okay Catholic or the right print this right let's just look through print this right let's just look through for lead character of s we need to f check if capture is left then it must be invalid because we're looking through from left to right if you met the left Prentiss is invalid I will just add the timing winning is Travis who so embedded +1 right now if it is white for instance what will happen right there is a problem we only check if invalid left count is zero now so it's it is zero if there's no left one we updated with one right if not because okay if it's zero it's not they were there will be one left - in the industry so what we update the invalid left town well - one and finally we will get what we will get the invalid left town plus invalid right count yeah that's all so bad simple let's try to some pool or accept it and the we use a lot of memory could this be any simpler head this is I think this is the simple simplest solution right so type of poorest linear we Travis all through all the characters space yeah we used two variables so it's constantly man I don't know why any better solution we track the balance of left string we track the balance of left string manage the number rice ring a string in manage the number rice ring a string in Spanish which spans ero Plus every Spanish which spans ero Plus every perfect is non negative balance the perfect is non negative balance the ideas come up with balance what is balanced number - this number of right I'm sorry is fat it if it's zero mm-hmm it's lost every perfect just if it is never negative say minus one if it is never negative say minus one ever negative it means okay we must add ever negative it means okay we must add huh so answer your balance look through huh so answer your balance look through it balance plus 1 or minus 1 it balance plus 1 or minus 1 Oh a plus 1 is left right it becomes Oh a plus 1 is left right it becomes less more we form a the right bound less more we form a the right bound right parenthesis it's minus 1 cool so right parenthesis it's minus 1 cool so and it is minus 1 when it is from and it is minus 1 when it is from balance the answer plus plus minus plus balance the answer plus plus minus plus plus no please answer what is balance plus no please answer what is balance hmm I think they should leave this just hmm I think they should leave this just be the same right ask please ask anyway I think we're ask please ask anyway I think we're basically the same so that's of this one basically the same so that's of this one we just did you count the left and right we just did you count the left and right okay okay up see you next time bye bye
2024-03-25 11:04:23
921
https://i.ytimg.com/vi/B…axresdefault.jpg
LeetCode 921. Minimum Add to Make Parentheses Valid | JSer - JavaScript & Algorithm
QOQL3S2BHPs
Oh 780 a rotated digits X is a good number if after rotating you two should number if after rotating you two should buy individually by 180 degrees we can buy individually by 180 degrees we can invite number tested it's different from invite number tested it's different from X each stitches must be rotated we X each stitches must be rotated we cannot choose to leave L know a number cannot choose to leave L know a number is valid if each digit remains a digit is valid if each digit remains a digit after the rotation 0 1 & 8 will attach after the rotation 0 1 & 8 will attach themselves to then 5-volt ace 2 5 8 2 & themselves to then 5-volt ace 2 5 8 2 & 5 will taste each other 6 & 9 OS or 5 will taste each other 6 & 9 OS or voltage at an arrest numbers to nab both voltage at an arrest numbers to nab both rotations to any other number and become rotations to any other number and become invalid now given a positive and how invalid now given a positive and how many numbers X from how many numbers X many numbers X from how many numbers X from 1 to n are good they remain from 1 to n are good they remain unchanged after voting you just won't unchanged after voting you just won't take each stage in the video ok fine take each stage in the video ok fine yeah so actually so I would say for this yeah so actually so I would say for this because this is easy right because this because this is easy right because this is easy and if I was incompetent or is easy and if I was incompetent or something and I see that the end is up something and I see that the end is up to ten thousand then I would just do a to ten thousand then I would just do a proof force right but I think so I'm proof force right but I think so I'm gonna do that but I would also say as an gonna do that but I would also say as an optimization if you get is or interview optimization if you get is or interview or something like that you want to talk or something like that you want to talk about it then you could actually about it then you could actually generate them digit one by one and only generate them digit one by one and only oh sorry I guess technically one two oh sorry I guess technically one two three four so 7 by so one digit at a three four so 7 by so one digit at a time and then you going chop off on you time and then you going chop off on you don't have to consider was it like three don't have to consider was it like three four seven and then you just have to four seven and then you just have to keep an additional variable for kind of keep an additional variable for kind of to 0 and 1 and 8 because they need a to 0 and 1 and 8 because they need a number that is in a two five six or nine number that is in a two five six or nine right and that's mostly I kind of did right and that's mostly I kind of did away but yeah but I'm gonna do it before away but yeah but I'm gonna do it before us and then we're gonna play around with us and then we're gonna play around with it yeah and then just you know for in it yeah and then just you know for in times you go to was it one and you can't times you go to was it one and you can't go and then then you just if good okay go and then then you just if good okay yeah okay I'm bad at naming things I'm yeah okay I'm bad at naming things I'm just gonna called just for now yeah good just gonna called just for now yeah good count and then just return care count and then just return care and clearly you have to declare cut and and clearly you have to declare cut and then now we'd start to just just number then now we'd start to just just number is good if you digit is okay yeah okay no no why is your X you should have a no no why is your X you should have a lookup table maybe for this problem is lookup table maybe for this problem is okay okay oh yeah and then you need an additional oh yeah and then you need an additional ball for whether you rotated maybe so ball for whether you rotated maybe so yeah okay so if Y is that is to a switch yeah okay so if Y is that is to a switch statement switch why it's good ID so we statement switch why it's good ID so we have case one so masuo one a so in this have case one so masuo one a so in this case this is okay so we actually just case this is okay so we actually just ignore those was a 2 + 2 5 6 & 9 then ignore those was a 2 + 2 5 6 & 9 then this is good this is good so we said voltina 0 true because you so we said voltina 0 true because you actually did you know you need at least actually did you know you need at least one numbers to change and this would one numbers to change and this would change that to be true and in the change that to be true and in the default case we were just want to return default case we were just want to return for us anyway we just add a tonight not sometimes I'm still in my Python mindset where I don't have to do have to did I do where I don't have too much McCoy right mister for come forth yes two different okay oh well I forgot to uh yeah okay whoops you symbol you know well different where we've all been yeah that's why I got time to me exceed it that's how I keep bugging pretty quickly though it's a little bit slow oh no did well essentially that should be right well essentially that should be right but Wow I mean I I think I just didn't but Wow I mean I I think I just didn't declare a count miss suma those are big declare a count miss suma those are big numbers that are confusing don't know numbers that are confusing don't know what's wrong maybe I just watched it I what's wrong maybe I just watched it I mean I think that's reading an ad to me mean I think that's reading an ad to me okay okay I mean it's still wrong but that's okay I mean it's still wrong but that's okay one and ten are not good numbers but you one and ten are not good numbers but you knew that why did I get seven foot ten knew that why did I get seven foot ten that's two this is easy to debug do i that's two this is easy to debug do i I'm just really bad not declaring I'm just really bad not declaring default overs today I don't know what my okay just silly mistake for this problem but otherwise is okay so yeah that's submitted silhouetting time yeah well it's oddly confident in this I missed like number but yeah went for this one I think this one is a test in kind of time complexity analysis or just and in that case given n is 10,000 each number has about five digits at most that means you only go into 50,000 operations ish like you know on order of operations per se but like that's not my work which is technically given the input number and then it is n log n is is the complexity and technically and yeah and there's no no of one extra space but technically if you want to say that n is the input size technically the complexity of this is actually n times 2 to the N and the reason is because you can represent n but just you know 8 bits sorry it bites I'm mixing numbers but yeah 4 bytes so that's kind of why but yeah so that's why half of this problem is easy you know why do so many downloads but it's an OK bar I mean it's four and you could even be trickier if you have to generate them and like the Bala feels like a hundred thousand what can you do it or million right n well obviously you cannot do this well actually maybe even you can maybe to a million maybe I'll be a little tight but but like you know let's say a hundred million and you can't right so then you would have to kind of generate them attention by digit and in that case there'll be like seven to the ten or something like that so maybe that is a little bit tricky to kind of do the math white or like such that uh you know 2092 million maybe that's fast enough but I by the way yeah that's what I have for this problem kind of queue it's okay I mean it's like it's right it's it's aplomb so so yeah that's all I have for this one yeah cool love so mystical just decorations of stuff i'm i don't know maybe i'm too used to languages but it doesn't matter I don't know but switching back and forth on languages maybe the reason why I mean yeah yeah I mean I think one thing that I would put maybe just make sure you the rotation stuff because I don't know if you could do else we turn to return floors in that way having one thing is just to make sure that you have to see two five six nine at least once and that's what I have here I mean I obviously don't have to coach I don't know but but that's but that's the only place that I see that maybe is a little
2024-03-21 16:53:39
788
https://i.ytimg.com/vi_w…xresdefault.webp
788. Rotated Digits (Leetcode Easy)
0mrW2yEpmU0
Hello hello everybody welcome to my channel today.the problem is his writing and today.the problem is his writing and oranges in every cell can have one of the value oranges in every cell can have one of the value sabse zor divya 1000 restaurant sabse zor divya 1000 restaurant and welcome to lotus on every minute android and welcome to lotus on every minute android 4.2 and subscribe is this is impossible 4.2 and subscribe is this is impossible turn on this problem example for turn on this problem example for turn on this problem example for the first and the subscribe 22 2008 This dish to will be protein in the first made at the time Mile Siswan Minut 98100 Orange Orange Thursday subscribe to the Page if you liked The Video then subscribe to the Channel subscribe The And subscribe And subscribe And subscribe The Amazing spider-man 2 Minutes This All Will The Amazing spider-man 2 Minutes This All Will Be That Married Time Left In Here Is To 9 Withdraw From This Channel Recently Got In Dishas Range Suv Vidhi Edison This Is Already Done Services Only The Edison For International The The The state of this one is the fans and subscribe and share and subscribe to that is behavior initial state to take medicine and Buddhist to first wife rotating air rot in the jobcentre orange is show The Video then subscribe to I am soft and hotspot of this test case will be why I am so let's take another example which exam is rocky problem a sorry waste is not possible to roll so let's describe channel subscribe in this pound speed of hina duck speed of hina duck speed of hina duck Returns - How Will Solve This Problem First Of All Will Count How Many Price Oranges Will Have Ever Get Lost In The Present Which Countries Where In Too Variable Subscribe nx100 In This Great Benefit Total 6 and 9 We Need to Do Video Video Video then subscribe to the Page if you liked then subscribe to the Page if you liked The Video then subscribe to The Video then subscribe to 200 First Maintain Why Initially I Will 200 First Maintain Why Initially I Will Initial Ice Cubes Wedding All The Orange Initial Ice Cubes Wedding All The Orange Juice Protein And Safar Ke Will Get 0 Sudesh Juice Protein And Safar Ke Will Get 0 Sudesh Experts And Present Let's And Subscribe Now Believe On This Are It's All The Formation Words It's All The Formation Words It's All The Formation Words Orange Yes Sorry For Network Like For Orange Yes Sorry For Network Like For Directions After Rather Direction Tractor Directions After Rather Direction Tractor Cheese Live With 0 90 Number One And A Minus One To Ma0 A Fan Of The Last 20 - And This Is Vivek Us For Wedding Plus Creative Director Ne This Solid Solid Direction 200 F Sweet Words and Phrases of Activities Edison Many Members Vikram One Forced to Switch Puberty 851 Will Give No Assurance to Be a Next Will Go to the Question Will Go to the Element Will Find the First World Will Withdraw pre-2005 video.com to hair one hair raw one hair one hair one to hair one hair raw one hair one hair one hair in one hair and one hair and S& hair in one hair and one hair and S& P 500 script will be deleted and you will P 500 script will be deleted and you will welcome more than 500 way market S2 will welcome more than 500 way market S2 will update S2 and observed update S2 and observed update S2 and observed India This Entry Namak You Will Continue for Subscribe - 105 Withdrawal Time Will Tell U Ka Vikas Bindh 1000 1000 151 We Will Do You Do To The What 1000 1000 151 We Will Do You Do To The What Is The Condition Of WWE Champion Is The Condition Of WWE Champion And We Are Already Done With And We Are Already Done With And We Are Already Done With All The Price Oranges Already Roadshow Will Have Differ 400 A Hairy Jacod I Have Written To First Time Doing Some Weird Scanning And 10 And Lag Increase Protein And And Will Be Adding Deposits Of The Orange I To Stronger Cheese Will Never Intended Will Never Intended Will Never Intended For Getting Ready To Attack Interviewer At A Press Conference On Thursday Will Not Defined By Its Coordinates Loop Top Bottom Subscribe Like Subscribe To Vitamin A This Loop Slows In First Year Boys In Not Increasingly Checking The The The The The The 100000 Right Side And Inductive Is And Marketed Like Inductive Is And Marketed Like Subscribe And Is Non Rotting And Will Subscribe And Is Non Rotting And Will Decrease subscribe The Channel subscribe Decrease subscribe The Channel subscribe our Channel And subscribe The Amazing our Channel And subscribe The Amazing Uprising Turn On This Week Behave Behave Behave second example because like there is no second example because like there is no recent cases from it zoom liquid compiling samriddhi recent cases from it zoom liquid compiling samriddhi code the code the city has accepted so what is the time city has accepted so what is the time complexity of this is 100 time complexity of this is 100 time complexity is like and processing all complexity is like and processing all readers element show is opposite van is web readers element show is opposite van is web portal and orange is orange portal and orange is orange portal and orange is orange Complexity Of An Where Is The Number Of Sales In Every Day I Am Secure Thank You Feel Like A Soldier Hit The Like Button Fuel Subsidy Sharing
2024-03-25 14:48:11
994
https://i.ytimg.com/vi/0…axresdefault.jpg
rotting oranges | rotting oranges leetcode | leetcode 994 | bfs
6v-wL1z4OyA
so this problem here is leak code id 1470 and this is shuffle the array 1470 and this is shuffle the array so given the array of nums consisting of so given the array of nums consisting of two two times n elements in the form x1 x2 times n elements in the form x1 x2 and then at the midpoint it starts at and then at the midpoint it starts at one y one y two one y one y two uh return the array in the form x one y uh return the array in the form x one y two two x two y two so we're kind of like x two y two so we're kind of like interweaving the first half and the interweaving the first half and the second half second half of the array so basically i wanna go of the array so basically i wanna go through this really quick through this really quick so let's try to get the output from this so let's try to get the output from this test case test case just so that we can better understand just so that we can better understand what they're even asking what they're even asking so right off the bat um we're given an n so right off the bat um we're given an n and there are two n elements in here so and there are two n elements in here so we actually want to split this we actually want to split this in half so we always want to split this in half so we always want to split this in half in half so it's always going to be an even so it's always going to be an even number of elements so it could be split number of elements so it could be split evenly because they're going to be two n evenly because they're going to be two n elements so it's always even we want to elements so it's always even we want to interweave these two halves so the interweave these two halves so the result array result array is going to be this is our result array is going to be this is our result array uh we want to take the first from here uh we want to take the first from here and the first from here and then put and the first from here and then put them in so it's going to be 2 them in so it's going to be 2 3. then we want to take the second from 3. then we want to take the second from the first half the first half and the second from the second half so and the second from the second half so it would be 5 4 it would be 5 4 and then we want to take the third from and then we want to take the third from the first half and the third from the the first half and the third from the second half so it'll be 1 second half so it'll be 1 7 and if we look at this how we derived 7 and if we look at this how we derived it it this is actually the output for this this is actually the output for this test case that we test case that we copied so i just want to explain like copied so i just want to explain like what is happening what is happening so how do we do this so we're going to so how do we do this so we're going to actually create a actually create a result array and our result array we result array and our result array we know is going to be know is going to be length 2 times n but actually we can length 2 times n but actually we can just just simply say uh nums.length simply say uh nums.length because that's going to be the size of because that's going to be the size of it it so let's do that and let's return it so let's do that and let's return it because we know we're going to because we know we're going to and what do we want to do we want to and what do we want to do we want to fill this up so now i will say one thing fill this up so now i will say one thing uh we are actually using linear space uh we are actually using linear space here so here so we are using for this result although we are using for this result although some people don't count the result as some people don't count the result as extra space but we are using extra space but we are using the length of nums uh amount of space the length of nums uh amount of space so there is a constant space solution so there is a constant space solution but it involves like but it involves like a 20-bit binary integers and a 20-bit binary integers and putting one number from one-half in the putting one number from one-half in the left side and a number left side and a number yeah it's just it's confusing so i'm yeah it's just it's confusing so i'm just going to do it this way this is the just going to do it this way this is the easiest way to remember easiest way to remember and this is how we're going to do it so and this is how we're going to do it so basically what do we want to do we want basically what do we want to do we want to go to go up to n and the reason why is because up to n and the reason why is because this is half of the array and this is half of the array and at each point we're gonna put two at each point we're gonna put two numbers in so numbers in so we just have to go up to n so i'm gonna we just have to go up to n so i'm gonna go for in i equals zero go for in i equals zero and like so and then i is less than n and like so and then i is less than n so we're gonna loop n times basically so we're gonna loop n times basically we want to fill not only the we want to fill not only the so at index 0 we we not only want to so at index 0 we we not only want to fill this 2 but we don't fill this 2 but we don't also want to fill this 3. so basically also want to fill this 3. so basically what we can do what we can do to represent that is we can go 2 times i to represent that is we can go 2 times i and at i equals 0 this will just be 0. and at i equals 0 this will just be 0. so this will be the even numbers so this so this will be the even numbers so this will be the 2 will be the 2 the 5 and the 1 in this output so every the 5 and the 1 in this output so every even number even number we want to put the number that's just at we want to put the number that's just at i i because we want to go in the order of because we want to go in the order of the first half the first half so then now filling the second number we so then now filling the second number we want to go 2 times i plus 1. so this is want to go 2 times i plus 1. so this is going to be every odd number so going to be every odd number so i equals 0 this is going to be 2 times i i equals 0 this is going to be 2 times i which is 0 plus 1 which is 1. which is 0 plus 1 which is 1. and then we want to fill this with the and then we want to fill this with the first number in the second half so see first number in the second half so see this half right here the 347 this half right here the 347 we want to fill the first one with the we want to fill the first one with the 3. so this is going to be that 3. so this is going to be that n which is 3 so n n which is 3 so n plus i so basically this is like plus i so basically this is like saying every even number is going to be saying every even number is going to be the order of the first half the order of the first half and then every odd number is going to be and then every odd number is going to be the order of the second half that's kind the order of the second half that's kind of like how i describe it of like how i describe it and this is just a straightforward way and this is just a straightforward way to do it and fill up this rest so let's to do it and fill up this rest so let's go ahead and run this go ahead and run this and we'll see um we actually and we'll see um we actually oh yeah that's because i'm assigning it oh yeah that's because i'm assigning it to res i hope somebody caught that so to res i hope somebody caught that so we're gonna actually uh we're gonna actually uh we want it we want to get it from nums we want it we want to get it from nums so this is how we do that and if we run so this is how we do that and if we run this this uh we'll see that we get accepted and we uh we'll see that we get accepted and we submit this submit this and we'll see we have 100 run time so and we'll see we have 100 run time so talking about time and space complexity talking about time and space complexity as i said so we have time and we have as i said so we have time and we have space space space space is linear because we are is linear because we are creating extra space for the length of creating extra space for the length of nums and nums and some people don't count the output array some people don't count the output array of space so you could say it's constant of space so you could say it's constant but but i i don't know there is a way to truly i i don't know there is a way to truly get constant space is what i'm trying to get constant space is what i'm trying to say say and time is o of n as well because we and time is o of n as well because we are are ultimately accessing n elements ultimately accessing n elements so yeah just pretty straightforward this so yeah just pretty straightforward this is one of the easier ones is one of the easier ones i hope you guys enjoyed and thank you i hope you guys enjoyed and thank you for watching as always for watching as always i appreciate it
2024-03-21 02:57:56
1,470
https://i.ytimg.com/vi/6…axresdefault.jpg
Leetcode Solution - 1470 Shuffle the Array
CdOnlx6jBBE
E Agri Baby Pump Co Default Comment Wednesday Free of Cost January 1954 Channel Wednesday Free of Cost January 1954 Channel Soft Stimulus Problem Yes-Yes Arrangement at Soft Stimulus Problem Yes-Yes Arrangement at SIDBI Question and Definition of These SIDBI Question and Definition of These Leaders from Middle Arrangement for Every Leaders from Middle Arrangement for Every Side The Full Form of ID EP 155 Let's Side The Full Form of ID EP 155 Let's Understand with the Help of Kar Understand with the Help of Kar Understand with the Help of Kar problem 2012 decree given in this remedy that this is the sleep foundation 100 gram piece minister ok tell me let's call heads and focused example solve Welcome to The Amazing Shabban come to hand to come started slowly by politicians and started slowly by politicians and possible this possible this possible this the formation of women member and so will be there the true meaning of to real tutorial 30 A to Z to Congress Jabalpur city related to real 53.22 in 212 me also successful six for the basic mission editor simplicity Vithu Mauli Enjoyed A Tu So Let's Char Digit What Are Enjoyed A Tu So Let's Char Digit What Are Enjoyed A Tu So Let's Char Digit What Are The Different Solution Feature Available First The Different Solution Feature Available First One Will Be New Approach Will Be Call Getting One Will Be New Approach Will Be Call Getting All The Permissions Supports Difficult To Give In The All The Permissions Supports Difficult To Give In The Oil Setting On Computer Monitor Oil Setting On Computer Monitor Embassy In Checking For Information Weather The Embassy In Checking For Information Weather The Given To Cash Also Given To Cash Also *ka mohan *ka mohan that when nothing but for millions of physical two to that when nothing but for millions of physical two to two two and aapke sunao ki and aapke sunao ki bihar to check with position but index is given bihar to check with position but index is given is 30 given one does not possible is 30 given one does not possible Sleep for one night This is possible Schedule Sleep for one night This is possible Schedule arrangement for two years Back to Saudi Arabia arrangement for two years Back to Saudi Arabia Switzerland Travel condition Specialty Hi to 10 Switzerland Travel condition Specialty Hi to 10 worst condition is nothing but form of is worst condition is nothing but form of is divisible by I am divisible by I am afan afan So did they Number is divisible by indices So did they Number is divisible by indices Next can also be given equal Next can also be given equal Next can also be given equal state of 0512 is divisible by one please like this the invisible bittu no but reverse kidneys password reset in the condition which means one is the inactive subscribe The particular number 16 2011 to this condition this side effect please also through the Sohan Seervi Sohan Seervi Sohan Seervi Returning 2392 Stop This Way Read This Returning 2392 Stop This Way Read This Beautiful Arrangement Was Not But How To Return Beautiful Arrangement Was Not But How To Return Member Of Medical Arrangements For Member Of Medical Arrangements For The Formation Are You To Color Invents But Did The Formation Are You To Color Invents But Did Not The Case With Any Co Decree All The Not The Case With Any Co Decree All The Best All The Combination All Permissions And Not Best All The Combination All Permissions And Not Different Kidney Different Kidney Safar Nahi That Approach Time To Objective Safar Nahi That Approach Time To Objective Of Interactive That Is Vikas Vihar To Of Interactive That Is Vikas Vihar To Create And More Create And More Informations And E Have Different Rooms Space Informations And E Have Different Rooms Space Complexities That Bigg Boss BTS Reaction To Complexities That Bigg Boss BTS Reaction To Calculate Developer Missions This Quantity Let's See Calculate Developer Missions This Quantity Let's See How They Can Reduce How They Can Reduce How They Can Reduce Kshatriya our second approach taken to approach will be backtracking in will be taking all the members from one to two and will be taken with varieties divisible by portion and note and is the question is divisible by political number Key Key Key Channel Free Number For A Particular Position Channel Free Number For A Particular Position And Anti Shatter Number Is Not Well And Will And Anti Shatter Number Is Not Well And Will Stop Calculating The Formation Swift Stop Calculating The Formation Swift Care Number Airtel Particular Question Care Number Airtel Particular Question Relates With The Help Of And Example Of Relates With The Help Of And Example Of Board Select Cmo Office Board Select Cmo Office To Sahi Earliest One This One Of The Formation To Sahi Earliest One This One Of The Formation Of Physical Of Physical Of Physical Date Position Will Be Warned Come To Amrik Sodhi Not Divisible By Two Is Not Visible Best Hans For Doing This For Everything Will Be Checking Weather This Particular Combination Is Possible And Not So Here This Is Not Possible To Its So Examination Year Calculated in all the form Calculated in all the form Calculated in all the form actions where this position is not equal 3 has actions where this position is not equal 3 has been calculated and hence the number of the number of formation subjects related formation subjects related formation subjects related In In this year this aunt's will be wife inspector real 200 in english also android user time complexity for most of the cases so let's see how they can control the contraction using back rakhi hair railways payment is Between Between Between how to return home and combinations of how to return home and combinations of possible only dutiful arrangements and possible only dutiful arrangements and passwords Amazing fonts Next in this will be keeping passwords Amazing fonts Next in this will be keeping track of mother did not exist or track of mother did not exist or not not so definitely lies with fonts for so definitely lies with fonts for that I that I that I am and we gas calling [ __ ] that I am and we gas calling [ __ ] yes man earring yes man earring yes man earring Wear Generating Up To Embrace Of Bubbles Even In Next Which Give Any Problem I Your Show 10 Akhtar And Brett Lee Stuart Swift Is Recreating We Were The Shield To Calculate Isi Mitti Ne Parameters Of Income Of Be calculated Be calculated Be calculated and activities nothing but for this account and activities nothing but for this account with passing all rate related with passing all rate related play list dacoit next and read needs play list dacoit next and read needs redoing and account a parlor cancellation complete next redoing and account a parlor cancellation complete next week declaring and week declaring and calculate mitra hai be taking parameter seedhi for som will b s n l Will be Will be Will be india limited ok alerted royal look for it india limited ok alerted royal look for it in the and 1kw oneplus one big boss and in the and 1kw oneplus one big boss and is a's is a's family tree will be setting and condition soegi accept family tree will be setting and condition soegi accept in opposition has not in opposition has not returned by respectful number he visited returned by respectful number he visited of i of i that departmental falls upon it's not good to that departmental falls upon it's not good to Find a Find a that aapke khand that aapke khand play list in condition this and further in condition play list in condition this and further in condition thing and position thing and position were percentage of oo in the side of any political 204 let's percentage in the side of any political 204 let's percentage position who is position who is equal is equal to zero equal is equal to zero hence office collection itself is satisfied and hence office collection itself is satisfied and also setting that was leaving and also setting that was leaving and also setting that was leaving and turn off I will support you in next will be calculating message particular number hokar subah dance number sony xperia entry meeting and position to ₹15 internet number a big salute to calculate off self work in the same position And And And Libido Vijay Pal Singh C Mystery Turn Libido Vijay Pal Singh C Mystery Turn On Meter Middle School Work 1919 Modified On Meter Middle School Work 1919 Modified Next Chief Making This A Small Next Chief Making This A Small Quantity Use Remedy And Only Numbers Quantity Use Remedy And Only Numbers That I Think These Pilots How To Write Capital That I Think These Pilots How To Write Capital Member Condition Novel Also Intermediate Account Simple Solution Simple Solution Simple Solution That When Someone Jain Vikram Great Gambler Till That When Someone Jain Vikram Great Gambler Till Life Definition Of All Of The Lambs And Life Definition Of All Of The Lambs And Satisfying This Particular Condition Hands At Satisfying This Particular Condition Hands At Particular Formation It Is This Time And Particular Formation It Is This Time And Condition 100MB In Preventing Details From Condition 100MB In Preventing Details From Soen Hair Tips Position Greater Than Soen Hair Tips Position Greater Than In These Dates For Have In These Dates For Have A Plus Recording 's member solution let's run record organization 's member solution let's run record organization meerut meerut 's side back incident sis youth self 's side back incident sis youth self and a game fighting against that for it's quite and a game fighting against that for it's quite certain code that awadhi status mention this dynasty click on that which such and submission and accepted that which such and submission and accepted 100 in that 100 in that 100 in that using back tracking by restricting the number of pharmacy subjects related Are hope you understand this problem till hide so gas I hope you like this video please click on like button and don't forget to subscribe to have been In Both LinkedIn Instagram In Both LinkedIn Instagram In Both LinkedIn Instagram Platforms And Abroad In The Rings In Platforms And Abroad In The Rings In Edition Bluetooth You Can Join And Biscuit Edition Bluetooth You Can Join And Biscuit Community Issi Cord Tak Samridh And Isi Want To Help Others Community Issi Cord Tak Samridh And Isi Want To Help Others So Let's Get So Let's Get Benefits From Your Knowledge Delhi Road Benefits From Your Knowledge Delhi Road Wheeler Description Box Us Dashrath Is Wheeler Description Box Us Dashrath Is Video Gas Benefit Subscribe & See Video Gas Benefit Subscribe & See Thank you in next video
2024-03-22 16:46:46
526
https://i.ytimg.com/vi_w…xresdefault.webp
Beautiful Arrangement Leetcode | Problem 526 | Leetcode January Challenge 2021
8qbW_U9p1EU
hey hey everybody this is Larry this is still me and Lisbon still me and Lisbon um um yeah yeah doing a lead copy for doing a lead copy for the the the the fight I guess today's program is 864 fight I guess today's program is 864 shortest map to get all keys uh shortest map to get all keys uh hopefully soon we'll return to normal hopefully soon we'll return to normal schedule for a little bit uh okay so schedule for a little bit uh okay so this is a problem that I haven't saw this is a problem that I haven't saw before so that's an excited exciting before so that's an excited exciting thing to do uh though maybe the the name thing to do uh though maybe the the name of the problem gave it gives it away a of the problem gave it gives it away a little bit but we'll see little bit but we'll see so the shortest path to get our keys so the shortest path to get our keys okay so yeah okay so yeah oh just day by day okay I didn't really read all the details I'm not gonna lie because no one can read that fast I kind of just skipped ahead I just it just occurred to me to get all keys part and then I look I saw the grid I was like it seems like it's gonna be um what's it called traveling salesperson bomb or ham path or something like this I guess it's tsp because empath is yeah so then I was like well yeah so then I was like well that's not going to be Gucci uh and it's that's not going to be Gucci uh and it's not quite that right it's to get all not quite that right it's to get all keys uh yeah so and and I was like well in those cases at least in the most General uh example uh it's gonna be exponential right and if it's gonna be exponential then the constraints have to be pretty tight so this is why I I scrolled straight down the constraint I said okay well if the constraints is six it should be okay um so basically this dirty by Dirty uh uh so basically this dirty by Dirty uh uh good size so that's gonna be 900 900 good size so that's gonna be 900 900 times 32 for 2 to the six is should be times 32 for 2 to the six is should be good enough right what is that that's good enough right what is that that's like well that's less than 100 Cube or like well that's less than 100 Cube or what why did I say jump to 100 it is what why did I say jump to 100 it is less than 100 Cube which is a million so less than 100 Cube which is a million so so yeah so we're doing good on time so yeah so we're doing good on time complexity or in in the number of states complexity or in in the number of states and then we're only visiting up down and then we're only visiting up down left right so there's only four so then left right so there's only four so then so yeah so that should be good enough so yeah so that should be good enough for me to kind of get go going and for me to kind of get go going and that's what I'm gonna do uh but the idea that's what I'm gonna do uh but the idea is that is that uh you just basically keep state right uh you just basically keep state right so State instead of just the location so State instead of just the location which is X and Y you also want to keep which is X and Y you also want to keep um um a set say a set of keys that you a set say a set of keys that you currently own right and a set of keys currently own right and a set of keys that you currently own that you currently own um you can obviously represent them with um you can obviously represent them with a set but I'm gonna use bid mask because a set but I'm gonna use bid mask because because it's just more natural to me uh because it's just more natural to me uh especially for six items uh there's especially for six items uh there's almost six keys and the locks don't almost six keys and the locks don't really matter you don't you just have to really matter you don't you just have to acquire all the keys you don't have to acquire all the keys you don't have to acquire all the locks acquire all the locks um it's just that the locks um it's just that the locks determines where you can go right uh at determines where you can go right uh at least that's my understanding least that's my understanding so yeah oh and then in fact that's the so yeah oh and then in fact that's the explanation example one so yeah so we're explanation example one so yeah so we're pretty good here so yeah let's uh let's pretty good here so yeah let's uh let's see what is the other thing so if see what is the other thing so if there's a store employing so we can do there's a store employing so we can do something like right and then and the the keys are ABCDEF and the the keys are ABCDEF and ABCD I just goes up to F right and we've tried to determine how many and we've tried to determine how many keys okay so I mean I'm with keys is the keys okay so I mean I'm with keys is the lower case or uppercase okay lowercase is key so then we can just do just count the number of keys because it's not a keyword that's actually maybe surprising if I can write this a little bit cleaner if I can write this a little bit cleaner but I it is fine I think but I it is fine I think uh you only do that all the time three uh you only do that all the time three times anymore times anymore Okay so Okay so that's the number of keys so then yeah that's the number of keys so then yeah so then we we start so then we we start um over breakfast search really uh on um over breakfast search really uh on this new graph of uh x y and keys right right uh and I mean you know and this is right uh and I mean you know and this is just just but we also want to set up but we also want to set up like a distance thing multi-dimensional uh multi-dimensional things always kind of in Pipeline and I always have to like in Pipeline and I always have to like just be a little bit careful just be a little bit careful oh yeah okay so now x y oh yeah okay so now x y um um [Music] and the distance as you go to press of X it would be helpful if I could type the it would be helpful if I could type the m m okay thank you m uh but yeah I'm going okay thank you m uh but yeah I'm going to set up the directions which is still to set up the directions which is still up down left right and then yeah yeah I mean we can if mask is to go to and this is just 2 to the power of keys that's really or it is and this is to the power keys of minus one uh as I said I'm using bit mask I'm not going to go over a bit mask in this video but suffice to say that it is basically um a representation of a a set right uh basically each bit can be true or false representing whether the corresponding letter A to F is the key a to F is [Music] and then the new mask is equal to um mask if well let's make sure that it is it uh then maybe we'll move the new mask uh then maybe we'll move the new mask this way and then if to do realistic grid of N X now we have to uh now we have to uh do some maths well not maths but just do some maths well not maths but just uh uh passing say uh uh passing say so if so if this is a key and then we just obtain it so that's I mean [Music] okay okay right and then otherwise right and then otherwise and oh yeah lock string which is just I and oh yeah lock string which is just I mean I'll type it out but you can also mean I'll type it out but you can also you know use your imagination on how to you know use your imagination on how to write this a little bit better write this a little bit better okay so a little bit of N X and Y is in okay so a little bit of N X and Y is in Lux so this is the index right so if so this is the index right so if mask so we have if we have the key then mask so we have if we have the key then we can go if we do not we can go if we do not then we cannot go away so that means then we cannot go away so that means that if this bit mask as you go to zero that if this bit mask as you go to zero uh then we have to continue we cannot hopefully that's right I mean don't don't take yeah I mean you're seeing what I'm doing live and if you watch enough of it you'll realize that I make a lot of mistakes so don't you know uh yeah and then now now that this is all good and done we can do the BFS point right yeah and it's NY and mask and then pass up and accept it nxny and and mask is uh and mask is equal to D plus one and then other way and we return negative one if it's not possible yeah oh I forgot the other thing that we have to terminate which is that the walls the head obviously uh continue right test cases uh is that good are we Gucci I don't know let's give a summary I think the idea is right maybe we have oh no it's a good time out oh no it's a good time out because we didn't terminate early I'm because we didn't terminate early I'm trying far trying far huh why is that why is that why does that tie me out oh I'm dumb I forgot to um I forgot to do the breakfast search for that that is a a critical part wow new mistake hues new mistake here right so uh if D plus one is less than basophonics and Y and mask uh then we do this stuff or alternatively we can just do the opposite of this WOW Larry doesn't now do BFS as we were talking about right so uh somehow we've got the other ones correctly but yeah maybe I went a little bit I wouldn't say maybe I went a little bit I wouldn't say I went a little bit too fast but I was I went a little bit too fast but I was just there's a lot of things going on so just there's a lot of things going on so it's easy to forget things because I it's easy to forget things because I forgot uh like this this and this and forgot uh like this this and this and this and this and yeah there's like four this and this and yeah there's like four things to do though that one should things to do though that one should right uh but yeah right uh but yeah um um what is complexity here right it's gonna what is complexity here right it's gonna be all of art plus c be all of art plus c but with another Factor but I'm just but with another Factor but I'm just gonna say that first so this is R times gonna say that first so this is R times C because that is you know breakfast C because that is you know breakfast search that's the number of cells that's search that's the number of cells that's the number of nodes that's the number of the number of nodes that's the number of edges because number of edges is four edges because number of edges is four times whatever kind of right times whatever kind of right uh uh but it's also gonna be times but it's also gonna be times two to the K where K is the number of two to the K where K is the number of keys keys and this is not just only here is that and this is not just only here is that theory again I guess so yeah that's pretty much it uh that's the time that's pretty much it uh that's the time and space and space in the worst case uh though I think a in the worst case uh though I think a lot of those states are not visitable so lot of those states are not visitable so you can maybe make some optimization you can maybe make some optimization based on that based on that um but um that's all I have for this one let me um that's all I have for this one let me know what you think stay good stay know what you think stay good stay healthy to get mental health I'll see healthy to get mental health I'll see y'all later take care bye
2024-03-22 16:30:33
864
https://i.ytimg.com/vi/8…axresdefault.jpg
864. Shortest Path to Get All Keys - Day 29/30 Leetcode June Challenge
8bSrUFN1XYQ
Hello hello friends today jasveer voot previous song setting voot previous song setting 9th medium question hum kya hai 9th medium question hum kya hai amazon amazon amazon amazon amazon means that we who and subscribe to the channel to that sugar or us kya game banta hai an sugar or us kya game banta hai an increase pregnant we we have to increase pregnant we we have to duplicate shiv from this this subject duplicate shiv from this this subject duplicate shiv from this this subject element like this not subscribed to the element then please subscribe ke wallpaper from that ke wallpaper from that networking is networking is good ok good ok I first few words pimples decide I first few words pimples decide again called one my number is ok again called one my number is ok one one one middle element how many time set videos in the past so now what will we do in this and now I have said now I have said that people will take let's know let's run below is the that people will take let's know let's run below is the bike price loop to Amazon one two three four five bike price loop to Amazon one two three four five six six this way this number here first, Akshay lives here, this is our number which is right from our number, what to do here now. What will we do with this account, this lieutenant two, we will add plus time to the account, okay and the value of five means that means that this element has died, died, so again again. so again again. so again again. also be related to the number, again it will come under this group that the value is also equal to one and this boys number is equal to one. Yes, then we will check again that the value of the account was the value of the account which was improved for the first time, The value of the account is laddu, The value of the account is laddu, The value of the account is laddu, this water is an ad, so what can I say, a rally of great use, this water is an ad, so what can I say, a rally of great use, someone will do the treatment, bye-bye, it someone will do the treatment, bye-bye, it is ok, and the bank also prevents IPL, the value of the is ok, and the bank also prevents IPL, the value of the account, why will the idol account, why will the idol increase, ok, this means even increase, ok, this means even in the media. in the media. in the media. number is valve ok, so how many times has it been cleared, cancer is happening, now I again got the news that it will go, is it Robert, this time this condition will be cured, messages from the village. Robert, this time this condition will be cured, messages from the village. Already this has Already this has happened twice in our darkness, happened twice in our darkness, now if these traditional things will not satisfy then now if these traditional things will not satisfy then what will we do, conditions will be imposed from those places, what will we do, conditions will be imposed from those places, what will we write in the form of help, what will we write in the form of help, which is which is our account, great update, Hi our account, great update, Hi Dad, will be heard, okay, so I Dad, will be heard, okay, so I returned to that village. returned to that village. And we will keep the equivalent from here, now we must have come from here, so it so it means that this element, turn off this element that that after shifting the address, what is this, after shifting the address, what is this, but this achieve, this girl is fine and when this but this achieve, this girl is fine and when this limit is less than here. limit is less than here. limit is less than here. this device number is more, now it is two, which is the circle of railway index, it has been touched, so we will use this software, then again the value of high will go, now our IV is the same, the value of the account. Will check that the number is turned on so it is found, Will check that the number is turned on so it is found, what is the number we have but and the what is the number we have but and the name has been assigned, now this one, this outer name has been assigned, now this one, this outer condition will be satisfied, okay, condition will be satisfied, okay, what will we do in this, we will put a mark that the what will we do in this, we will put a mark that the outer one is in good condition for that. outer one is in good condition for that. outer one is in good condition for that. mark the bell, what will we do here, which is our number, which is the meeting at very o'clock, we will give it to Gram Fennel, it is fine and the value of the account will go, the account was created on equal to two, but we saw those shortcomings on which which feather has come, we must have got this condition tip feather has come, we must have got this condition tip that the number record length is fine, now what happened, will the that the number record length is fine, now what happened, will the edition run outside, what have edition run outside, what have we done here, the number is called the number we done here, the number is called the number of Mata Suhag, what have we made different to it, is there any of Mata Suhag, what have we made different to it, is there any special one? special one? special one? become of our number, what has become of our phone number, what has become of the become of our phone number, what has become of the value of the account by mixing something, now the value of the account by mixing something, now the value of the law will be measured, so look carefully at the hair value of the law will be measured, so look carefully at the hair and the number is honorable, use it once, then and the number is honorable, use it once, then for that we have to work. for that we have to work. for that we have to work. is in Ayurveda India, it just means that first it is fine here, then again I have gone to look look look, is fine here, then again I have gone to look look look, checked this is the loop checked this is the loop and the and the second second idli sandwich, the idli sandwich, the subscribe number subscribe number is this number, is this number, this this channel has been now that I now that I felt like the factory and the i20. felt like the factory and the i20. felt like the factory and the i20. is number 11, there is is number 11, there is number 11, okay this other purpose other purpose and subscribe, from here, we will take out the length of this post, its length we will take out the length of this post, its length LED notification, LED notification, its length is returned 500 its length is returned 500 its length is returned 500 will do and what we have seen in this is that we will chat elements right after so how did it get its time thanks to this okay and the this way what we did is we modified the same Hey this way what we did is we modified the same Hey we we we in it, if element national is mixed in it, then this is what is qualified, this remedy has been received and this point and this is what I have written to you here, according to this and this is what I have written to you here, according to this thing, what is the tiger pin number? what is the tiger pin number? what is the tiger pin number? ride a bicycle then subscribe My eyes have to be looted, I will check, I request to number, this is it, then we will give 12 cycles, the account value is Hussain, it is okay if electronic, we will cook for 10 more minutes, but if it is FD account statement. but if it is FD account statement. What will we do? We will do What will we do? We will do 914, okay? Out of that, we will make 914, okay? Out of that, we will make admission form for the IS intense pain limit admission form for the IS intense pain limit and it will be cleared from here through quantity printing machine. and it will be cleared from here through quantity printing machine. Okay, and if our Okay, and if our mum son is not equal to the number, mum son is not equal to the number, we will put a white sign on the number. we will put a white sign on the number. we will put a white sign on the number. Boss increment and have also added why not be a fan of this video channel Time to subscribe fan of this video channel Time to subscribe our Channel press The Light a
2024-03-20 12:18:47
81
https://i.ytimg.com/vi_w…xresdefault.webp
Remove Duplicates From sorted Array ii | Leetcode | Python Solution
DkDTjGs5HuM
hey guys persistent programmer here and welcome back to my channel so in this welcome back to my channel so in this channel we solve a lot of algorithms and channel we solve a lot of algorithms and go over really quick questions so if you go over really quick questions so if you haven't subscribed already go ahead and haven't subscribed already go ahead and hit the Subscribe button smash that like hit the Subscribe button smash that like button because that helps me create this button because that helps me create this content for you guys so without further content for you guys so without further Ado let's go ahead and look at today's Ado let's go ahead and look at today's problem we are given a 32-bit unsigned problem we are given a 32-bit unsigned integer and what we need to do is integer and what we need to do is reverse reverse um the bits we are given so if we have um the bits we are given so if we have an input like this what we need to do is an input like this what we need to do is reverse all of this so that it returns reverse all of this so that it returns this output here so we're literally this output here so we're literally going to take each bit and reverse it so going to take each bit and reverse it so let's look at how we can solve this let's look at how we can solve this problem problem so we know that we need to return a so we know that we need to return a result variable right so we are going to result variable right so we are going to go ahead and create that result variable go ahead and create that result variable we'll say res equals zero so this is we'll say res equals zero so this is what we have done we have created a what we have done we have created a place for our result now we also need a place for our result now we also need a temporary variable temporary variable um to hold the values that we are um to hold the values that we are shifting so we will say temp shifting so we will say temp is zero and we are going to need a way to iterate through um all our binary digits here and to do that we know we will use some kind of loop right so I can go ahead and say we will use a for Loop so far I in range 0 to 32 we know that we need to iterate over all these um bits so that we are able to change um and reverse the values so this is our first step we need to do is we need to interrogate each of these bits to see whether it's a zero or one and in bitshift offer operations the easiest way to do this is and something by one right so if I add 0 by 1 I will know whether it's a zero or one because the only case I will get a one is if it is a one one and one will give me a one so we can use the end operator to do this so okay very good we have found out that this is a zero so I've used the end operator now what I need to do is position this last bit here um to the front so how do I do that right so to do that I've created this temporary integer here and we will need to move this for this case we will need to move this 31 times forward right because this is at the 32 32nd position so let me write out the code so it looks it it makes sense how we are doing this so first thing I will do is perform this find out what this last bit is right so to find out that I can call this the least significant bit so LSB is going to be um equal to Ben so this is our input here n and we are going to times it by one okay so we have our last significant bit which is good and we know from the result of this whether it's a zero or one now we want to set the temporary bit here so we'll say temp is going to be um equal to so we will take our last significant bit and we are going to move it forward so we are going to take this and move it forward so we will do this and how do we know what is how many how many places do we need to move it forward right so to get that answer we can take our uh 32 bits that we know is that is is the number there there is and we will minus sorry I made a mistake here this should sorry I made a mistake here this should be 31. because be 31. because we are at the 32 position already so we we are at the 32 position already so we need to move it 31 times forward so this need to move it 31 times forward so this should be 31 uh minus I so in the first should be 31 uh minus I so in the first iteration I is 0 so we know that okay iteration I is 0 so we know that okay from the 32 position we need to move it from the 32 position we need to move it forward 31 times to be at the first forward 31 times to be at the first position here position here all right so now we have our 10 all right so now we have our 10 variables set up so we have the order variables set up so we have the order correct now all we need to do is put correct now all we need to do is put this in the result right so we need to this in the result right so we need to move this from here to our result so I move this from here to our result so I can say that to do this we use our or can say that to do this we use our or condition so I will say result is going condition so I will say result is going to be equal to to be equal to the whatever is in the result already the whatever is in the result already which is zero because that's what I've which is zero because that's what I've initialized it with initialized it with so it will say result so it will say result or uh our temp so I will say result and temp so we are taking our temp value and we are using the or condition to or it with the result so this will give us because we because if you do an or condition you are taking that same value and putting it over here last thing we need to do is process our next value here in the N right so how do we do that how do we uh say like okay we're done with this last significant bit what we want to do is process the next one here so okay maybe I should make this more clear here so we have we are Ending by one here right so I can say that okay if I have all these um these bits to process and I'm done with this one all I can say is okay let me um right shift the end so what that will do is remove this and we are going to process again with and with one this last uh bit here which is what we want to do so we will say n is equal to and by one by one so this is how we are getting to that so this is how we are getting to that last bit and the last thing we are going last bit and the last thing we are going to do is return the result so I will to do is return the result so I will return res here okay let's give this a return res here okay let's give this a run yay success
2024-03-21 14:24:37
190
https://i.ytimg.com/vi_w…xresdefault.webp
Reverse Bits | 190. Leetcode | Python Solution
gAzV1RqqLDI
Hello everyone so this is the next question distance between bus stops a bus from a distance between bus stops a bus from a stops number from 0 to a small form stops number from 0 to a small form circle not the distance between pairs circle not the distance between pairs of next stops distance at a i distance between the of next stops distance at a i distance between the stops number i and i stops number i and i psv psv psv return the shortest distance from the start point to the destination point. Firstly, we can apply the circular method in this and if we want to go even simpler then we can directly return only one distance from the Let us take Let us take Let us take out the sum up to and the remaining sum will be taken out the sum up to and the remaining sum will be taken by the total of the sum. If we compare the by the total of the sum. If we compare the minimum with the remaining sum, we will return the minimum of the two, like we will return the minimum of the two, like in this example, distance tooth 4 and in this example, distance tooth 4 and Starting is from zero to one Starting is from zero to one and its distance is one so ok take and its distance is one so ok take another example, some summation yes, another example, some summation yes, starting is zero and destination is two starting is zero and destination is two and what is its summation 1 + 2 that will be and what is its summation 1 + 2 that will be and as much as remaining and as much as remaining and as much as remaining how much is the total sum, then 4 + 3 7 8 9 10, if total is 10, then 10 - 3, how much is the seven, then three and which of the seven is the minimum, we will return it. Done Done Done first of all we define an int sum or the total sum will be of the circular loop which we will assign from zero and there will be an int which will show us the minimum distance or distance Point and destination will be the Point and destination will be the Point and destination will be the point, then we would define it with A and point, then we would define it with A and write the same. write the same. This is done. First we will check. This is done. First we will check. If we assume that we have given this first, like the If we assume that we have given this first, like the starting point is one and the destination, if starting point is one and the destination, if we have given zero then just we have given zero then just we have given zero then just then for that we can do that if start is greater than destination, if start is greater than destination then we swap start and destination. This will mean that we will not get confused if starting So it will take it from the initial point, So it will take it from the initial point, So it will take it from the initial point, if the start point itself is getting bigger then it is if the start point itself is getting bigger then it is swapping it and after swapping it and after swapping, the starting point will be swapping, the starting point will be minimum and then we can apply a for loop minimum and then we can apply a for loop from I A I from I A I to Start to Start I. destination and aa plus plus destination and aa plus plus i plus plus is happening like how to know i plus plus is happening like how to know that start if start is bigger or that start if start is bigger or destination is bigger then we do aa minus minus destination is bigger then we do aa minus minus i plus plus so we do this it will be i plus plus so we do this it will be easier than this easier than this method that we method that we method that we we are doing the initial check so that there is not much problem, then the sum plus equal to this distance, the distance of the distance, the distance of the position will continue till the position will continue till the destination and then we will put another for loop in destination and then we will put another for loop in which the whole sum will be like I equal. which the whole sum will be like I equal. Size of distance from t zero to i lesson distance t Size of distance from t zero to i lesson distance t okt okt size and i plus pis and what will happen in size and i plus pis and what will happen in this, we will store the sum total in this this, we will store the sum total in this and the same method will be same, only all the and the same method will be same, only all the elements are being added in it, elements are being added in it, distance of distance of eight and at the eight and at the eight and at the sum of total minus sum and just in return we will do this, return the minimum of both which is minimum and return minimum of ama sum so sum is a distance which is from start to The sum of is being added and R The sum of is being added and R The sum of is being added and R is the remaining from the total which is like th is the remaining from the total which is like th 4 is a remaining then its value is then 4 is a remaining then its value is then which will be minimum among the two and will return which will be minimum among the two and will return this sum is initially defined from zero this sum is initially defined from zero and all the rest and all the rest and all the rest code ok so all the test cases have passed all the test cases have been accepted so this is all the test cases have been accepted so this is the right answer thank the right answer thank you
2024-03-25 18:22:38
1,184
https://i.ytimg.com/vi/g…axresdefault.jpg
1184. Distance Between Bus Stops | Leetcode problem no. 1184. | C++ |Hindi |Array
xZpmwB4y9KE
uh hey hey everybody this is larry uh so i i don't usually do this but um i'm gonna don't usually do this but um i'm gonna do the explanation first and then you do the explanation first and then you can watch myself with live later can watch myself with live later uh in general for the most part uh uh in general for the most part uh i know what i'm doing but this time i i know what i'm doing but this time i actually ran it um actually i still kind actually ran it um actually i still kind of of did mostly what i wanted to do but i did did mostly what i wanted to do but i did do it way too um i went to a hiccup do it way too um i went to a hiccup so and you could see it watch it live so and you could see it watch it live after uh this after uh this but uh but yeah i just want to do an but uh but yeah i just want to do an explanation in the beginning explanation in the beginning um yeah hit the like button hit the um yeah hit the like button hit the subscribe button join me on discord and subscribe button join me on discord and today we're going to go over today's today we're going to go over today's prom prom majority element for day 22 of the majority element for day 22 of the september daily challenge so the first september daily challenge so the first the pre-record set that i would think the pre-record set that i would think that i think you should know is about that i think you should know is about the bullet more majority algorithm the bullet more majority algorithm uh there's a link here i'll link it in uh there's a link here i'll link it in the comments and the comments and and yeah and then the idea is that and yeah and then the idea is that we extend it from going over we extend it from going over n over two times two and over three n over two times two and over three times times uh so that's pretty much it and the idea uh so that's pretty much it and the idea is basically extending um and you know is basically extending um and you know when you watch when you watch me solve it live i actually explore some me solve it live i actually explore some of these ideas and thought process of these ideas and thought process so i definitely recommend uh staying for so i definitely recommend uh staying for that uh if you want to see that uh if you want to see the live thought process of a problem the live thought process of a problem that i haven't solved or that i haven't solved or um i don't think i've ever solved this um i don't think i've ever solved this uh before so or even looked uh before so or even looked seen it before so it is it is new to me seen it before so it is it is new to me but but basically the idea is that but but basically the idea is that having two candidates having two candidates it's um we're gonna go and it's um we're gonna go and so to convert it from n over two to n so to convert it from n over two to n over three we use two candidates instead over three we use two candidates instead uh and having two accountants as well uh and having two accountants as well instead of one count instead of one count and the idea behind baltimore is that and the idea behind baltimore is that you you know you have this kind of you you know you have this kind of uh majority thing where uh majority thing where where you just count the number of where you just count the number of elements that in a way elements that in a way you count the the delta of the number of you count the the delta of the number of elements that's in it elements that's in it uh uh in a candidate minus uh uh in a candidate minus the number of um the number of um the number of uh the number of uh votes that is for non-candidates right votes that is for non-candidates right uh it's a tricky way and that and the uh it's a tricky way and that and the majority algorithm works only if majority algorithm works only if uh these elements exist which is why we uh these elements exist which is why we which is why we do a second scan later which is why we do a second scan later but but so how does this generalize to one dirt so how does this generalize to one dirt instead of one half instead of one half well you know well you know it starts up the same uh for when if we it starts up the same uh for when if we when we get a vote uh and it's for a when we get a vote uh and it's for a candidate that we already have candidate that we already have then we just increment the row uh then we just increment the row uh otherwise otherwise you know we kick one of these people out you know we kick one of these people out um um or we attempted to kick one of these or we attempted to kick one of these people out or we just decrement people out or we just decrement both of them the key point to notice and both of them the key point to notice and which i didn't which i didn't during the video is that um during the video is that um this only happens half the time this only happens half the time because it would require because it would require both uh chem one and count two is not both uh chem one and count two is not zero so if one of these is zero that zero so if one of these is zero that means that it only means that it only that row only counted half the time um that row only counted half the time um so from that you get uh that's the only so from that you get uh that's the only invariant that you need invariant that you need to solve this problem and then that's to solve this problem and then that's how you have uh the candidates how you have uh the candidates uh at the end of this you would have uh at the end of this you would have candid one candid one and two in the in the in the thing and two in the in the in the thing in the variable and then you have to do in the variable and then you have to do a final loop because you have to assume a final loop because you have to assume that they assist and then you just check that they assist and then you just check that uh it reaches one third um so this that uh it reaches one third um so this is a very is a very short explanation uh for sure uh i go short explanation uh for sure uh i go into a little bit more detail when i into a little bit more detail when i solve it live but i just want to kind of solve it live but i just want to kind of go over the code because go over the code because it's a longer video today for that it's a longer video today for that reason uh reason uh because i made a typo but i thought the because i made a typo but i thought the album was wrong so album was wrong so it happens um and yeah so the complexity it happens um and yeah so the complexity of this will be linear time because of this will be linear time because uh we do over one work uh we do over one work per element all everything i highlight per element all everything i highlight is all one and all this is obviously all is all one and all this is obviously all one one so this is going to be of n times uh for so this is going to be of n times uh for complexity we only have complexity we only have four variables five variables six four variables five variables six variables something like that variables something like that so constant space as well which is the so constant space as well which is the requirement that requirement that is needed for this um yeah as i said is needed for this um yeah as i said this is not a this is not a uh an algorithm that i've seen very uh an algorithm that i've seen very often even in the often even in the majority case uh let alone the one dirt majority case uh let alone the one dirt case i don't know what that means case i don't know what that means but uh so you can take as you it mean but uh so you can take as you it mean both on interview or both on interview or competitive um yeah that's all i have uh competitive um yeah that's all i have uh hit the like button hit the subscribe hit the like button hit the subscribe button uh join me on discord and you button uh join me on discord and you could watch me could watch me actually solving this live next actually solving this live next hey everybody this is larry this is day hey everybody this is larry this is day 22nd 22nd of the ditko daily challenge uh hit the of the ditko daily challenge uh hit the like button the subscribe button join me like button the subscribe button join me on discord on discord and let's get solving this problem live and let's get solving this problem live majority element two majority element two okay i guess it's probably similar to okay i guess it's probably similar to the first one with the first one with uh the broiler more algorithm uh the broiler more algorithm uh that's what i'm going to uh uh that's what i'm going to uh i don't like so uh i don't like so uh um so yeah so i do solve this live so um so yeah so i do solve this live so sometimes i'm gonna run into some sometimes i'm gonna run into some hiccups uh so bear with me for a second hiccups uh so bear with me for a second i don't think i've used this before i don't think i've used this before uh or this problem before uh or this problem before uh i'm gonna put a link here uh i just uh i'm gonna put a link here uh i just googled it real quick googled it real quick uh but that is the algorithm that you uh but that is the algorithm that you should know uh as a prerequisite for should know uh as a prerequisite for this this uh but and you know i mean i don't know uh but and you know i mean i don't know how how practical it is when do we use but it is practical it is when do we use but it is just kind of something that i just kind of something that i figured i would need um but i haven't figured i would need um but i haven't know how to know how to solve this before but solve this before but my guess is that uh my guess is that uh given that n over three uh you know by given that n over three uh you know by pigeonhole or whatever um at most it's pigeonhole or whatever um at most it's going to going to have two elements have two elements right because if similar to um because if you have more than three elements that appear more than n over three times then you have more than 100 which is obviously not possible so from that um we can just maybe keep track of some counter and then figure out what are the possible uh ones i'm so i'm not gonna lie for this problem um i haven't thought this through and i haven't seen this a similar problem before other than knowing that it's boiling more so and i'm not well i'm not that practice on this farm so bear with me and let's kind of work for it together uh that'll be a fun challenge uh for today so let's go for it uh so for x and nums so okay so what is how would i think about this right so you so on the two people brought a more algorithm if i remember correctly and hopefully i do otherwise um otherwise something will be tricky is that basically you're trying to find the delta of um of one element of um of one element and everything else right and what i mean by that is that um and some of this is pigeonholed but basically let's say you have uh and i'm just explaining to two people or two uh two elem or uh majority version which is n over two version um which is that if you have something that you know let's say you have uh 15 elements right what you're looking for is something that appears eight times if it appears eight times then or more if it appears eight times then or more then you have um then you have um [Music] [Music] a candidate that a a candidate that a that has uh that would end up with plus that has uh that would end up with plus one at the end right because one at the end right because it shows up eight times and so forth it shows up eight times and so forth um so yes i think that's what i'm going to do with a similar method of uh but it can tr instead of doing one candidate i'm going to have two candidates and and yeah um [Music] i think the thing i have to think about that i'm a little bit uh hung up on right now is just figuring out what happens when you find an element that isn't uh one of the two candidates right so basically you have candidate let's say you have uh the first candidate candidate one you have candidate two uh let's say you have something that appears like some random x right uh do you decrement from the first one or and the second one or just the first one or just the second one right um well you know that if x appears what that means is okay well maybe it'll be easier if i okay well maybe it'll be easier if i work out a case so basically let's say work out a case so basically let's say uh let's say we have 15 elements uh let's say we have 15 elements or 15 votes right or 15 votes right uh let's say can they one already have uh let's say can they one already have four votes and candidate two only have four votes and candidate two only have two or so let's say yeah two or so let's say yeah now you're voting for a third candidate now you're voting for a third candidate larry or i don't know larry or i don't know uh then what does that mean that means uh then what does that mean that means that that in order for candidate one to have one in order for candidate one to have one third of the row third of the row it would decrement by one and so is this it would decrement by one and so is this one one is that reasonable i don't know i'm is that reasonable i don't know i'm gonna play about so the tricky part for gonna play about so the tricky part for this is just the visualization is this is just the visualization is already already relatively ups i don't know i wouldn't relatively ups i don't know i wouldn't say obscure it just doesn't come up damn say obscure it just doesn't come up damn often this algorithm often this algorithm um even in competitive so um even in competitive so the visualization is going to help but the visualization is going to help but let's um i'm going to play around with let's um i'm going to play around with sometimes it helps with uh people have sometimes it helps with uh people have different visualization techniques different visualization techniques and i urge that you find the and i urge that you find the visualization technique that works best visualization technique that works best for you for you uh sometimes uh i have pen and paper uh sometimes uh i have pen and paper already uh and that's what i'm gonna use already uh and that's what i'm gonna use um and sometimes i just write very short um and sometimes i just write very short snippet of code snippet of code uh that simulates what i want and then uh that simulates what i want and then kind of use print statement or something kind of use print statement or something like that like that to kind of visualize what that means for to kind of visualize what that means for me so i'm gonna me so i'm gonna let's let's uh let's get started on that let's let's uh let's get started on that so let's say we have candidates one so let's say we have candidates one is equal to say none right is equal to say none right it doesn't really matter um it doesn't really matter um candidates well okay and it's two is you candidates well okay and it's two is you go to none go to none count one is equal to zero count two is count one is equal to zero count two is equal to zero right equal to zero right so so okay so if count 1 is 0 0 so okay so if count 1 is 0 0 then we want to assign candidate then we want to assign candidate 1 to x and then count 1 is equal to 1. 1 to x and then count 1 is equal to 1. i mean this is just similar to the i mean this is just similar to the original um original um um for the more um for the more majority algorithm so i'm just writing majority algorithm so i'm just writing it out and then kind of visualizing what it out and then kind of visualizing what that means is that means is as uh and try to figure out what the as uh and try to figure out what the invariance could be invariance could be right um okay oh actually i have to make sure that it's not one of the candidates he uh um usually i mean this is the k i think this is the order i do it in for two uh for majority ran over two but i think that in this case it may not make sense so uh so if this is equal to candidate one then count one one l if else if candidate um let's just say and then just continue um let's just say and then just continue continue make it easy continue make it easy um and then else this is a new number um and then else this is a new number right so right so we either put it in we either put it in or this is a uh we have to or this is a uh we have to subtract from uh count one and count two subtract from uh count one and count two uh okay is that okay enough uh okay is that okay enough hm uh i think this one will be really illustrated uh is it straight sorry i can't even english right now uh it will show us it'll help us visualize the most so yeah so now we return okay so results is to go to empty list okay so results is to go to empty list if count one if count one is greater than zero and we still start is greater than zero and we still start append append candidates one if count two is greater candidates one if count two is greater than zero we sell starter pen than zero we sell starter pen candidates two and then just return candidates two and then just return results results uh i don't think this so this is not uh i don't think this so this is not finally this is not what the finally this is not what the quick uh this is not right yet um quick uh this is not right yet um because we still should do a pass to because we still should do a pass to vertified vertified uh that they're the majority or the one uh that they're the majority or the one third majority third majority but i just want to see real quick what but i just want to see real quick what this gives us uh so this gives us this gives us uh so this gives us two uh again that's because of the two uh again that's because of the rotification step right rotification step right um this looks okay um this looks okay but i i want to see but i i want to see for visualization i wanted to see the for visualization i wanted to see the progression of progression of of uh the states as we go through them of uh the states as we go through them uh and this one is a little bit tricky uh and this one is a little bit tricky to to do because we have continued statements do because we have continued statements but but we're going to try okay so yeah put one in there that's one okay so yeah put one in there that's one one two three one two three and put it three okay three one three and put it three okay three one three two and then now whatever you see a two two and then now whatever you see a two um um [Music] [Music] goes to two zero and now 2 over ticks goes to two zero and now 2 over ticks [Music] [Music] to be honest i'm not that confident to be honest i'm not that confident about it even though this seems ok about it even though this seems ok so let's go do a for loop again so let's go do a for loop again for x and nums um for x and nums um if x is equal to candidates 1 um let's just do let's reset the count i think that should be okay uh and then we just vertified that if now in this case it's up greater than zero is and over three four exactly right so uh let's just say okay so this gives us okay so let's um okay so this gives us okay so let's um so usually i so usually i so in a normal setting i'm going to play so in a normal setting i'm going to play around with more different test cases around with more different test cases uh let's actually do that real quick uh uh let's actually do that real quick uh but for the most part um yeah i'm going but for the most part um yeah i'm going to try to think through different to try to think through different scenarios different ordering of the scenarios different ordering of the stuff stuff uh but in the interest of time i'm just uh but in the interest of time i'm just going to submit just to kind of see going to submit just to kind of see um just to see uh how that goes so yeah i didn't actually consummate that one but okay i'm gonna submit and if we get a wrong answer that's okay because then now i can see uh because ways right now i'm still uh because ways right now i'm still trying to understand the problem and trying to understand the problem and that's part of the learning that's part of the learning is that uh depends on what you want to is that uh depends on what you want to practice for right if i want to practice practice for right if i want to practice for a contest and i want to practice for for a contest and i want to practice for correctness correctness um then i am going to you know just um then i am going to you know just think for these different cases for now think for these different cases for now uh i'm just practicing uh i'm just practicing learning this thing so i'm still trying learning this thing so i'm still trying to figure out cases that to figure out cases that um you know in time efficient way um you know in time efficient way just like what am i doing right hey just like what am i doing right hey everybody uh so everybody uh so usually uh this is gonna be a live uh usually uh this is gonna be a live uh recording recording um and it it was a live recording but i um and it it was a live recording but i in inserted this kind of quick in inserted this kind of quick disclaimer because uh so apparently what disclaimer because uh so apparently what i did was i had a typo i did was i had a typo uh and if you follow a full you'll see uh and if you follow a full you'll see it so um it so um so i'm gonna put a link for you to skip so i'm gonna put a link for you to skip to the end where i explain to the end where i explain the uh complexity and stuff like that or the uh complexity and stuff like that or you could watch me you could watch me try to solve it or try other techniques try to solve it or try other techniques uh uh and try to visualize the problem for the and try to visualize the problem for the next like 20 minutes next like 20 minutes uh that's my bad whoops sometimes it uh that's my bad whoops sometimes it happens sometimes it happens the best of happens sometimes it happens the best of us us so i hope that you also learn from that so i hope that you also learn from that if you like anyway if you like anyway thank you so okay so in this case that thank you so okay so in this case that is very clear why uh this is is very clear why uh this is my current algorithm is that right my current algorithm is that right because uh for the ones it drops off it drops off because there are enough unique elements which actually should be in the case i at least try really really quick uh one is clearly the answer but because we have nine um the three four five six will delete the answers from these so i think now now i have to think about how this now i have to think about how this generalized so my generalization generalized so my generalization attempt was not good or it was not attempt was not good or it was not accurate accurate um now i wonder if you know we just do it because i think the thing we want is because i think the thing we want is that uh that uh so what does that mean when one none so what does that mean when one none will come in will come in that means that i'm i'm thinking just in that means that i'm i'm thinking just in general maybe that general maybe that i need to double everything so that's my i need to double everything so that's my thought process right now and why did i thought process right now and why did i say that and maybe the constant isn't say that and maybe the constant isn't right for doubling but right for doubling but but what i mean is that when a rule but what i mean is that when a rule comes in uh what does this do to it comes in uh what does this do to it right so your target needs to be right so your target needs to be this number of numbers over three and this number of numbers over three and when a nine volt comes in when a nine volt comes in that means that um that means for that means that um that means for for every two rows that isn't your for every two rows that isn't your number number it cancels out your your your previous it cancels out your your your previous row right row right so that's how i would think about it and so that's how i would think about it and from that um from that um that was just there did i just had a that was just there did i just had a typo typo i think maybe this is a typo as well but i think maybe this is a typo as well but so that's actually pretty bad so that's actually pretty bad i don't know if i just noticed it or or i don't know if i just noticed it or or whatever but whatever but how did that uh and that one my answer how did that uh and that one my answer so well did i just get really lucky on on a typo did i just get really lucky on on a typo uh now something's weird uh now something's weird what did i change how come my answer is what did i change how come my answer is really well really well uh that's awkward well this should definitely be one regardless um but i think now instead of uh incremented by one it should be you go to buy two because every two votes that you oh sorry every one vote that you get will get cancelled by two votes so which so that you can actually do plus one for the count of number of rows and then oh this is two two and then subtract a half every time you just get another row but uh just to make it easier i double but uh just to make it easier i double everything that's what i said earlier everything that's what i said earlier about doubling about doubling but now i'm returning nothing do i have but now i'm returning nothing do i have a typo somewhere that's weird that's weird now four and two votes that looks good now four and two votes that looks good so that means that so that means that the stuff should be on this side for x the stuff should be on this side for x is not is not not set the candidates right not set the candidates right it looks okay so yeah so that's kind of my thought process and and some of this like i said is about getting the right visualization as you sail for the problem and for me um you could kind of see like sometimes a wrong answer will just give you right clear immediate visualization of oh yeah of course this is wrong because uh the first the three ones will get easily controlled by three four and five even though that's not enough right that obviously still is good um i have a typo somewhere this looks good i have a typo somewhere this looks good right right these are good candidates also why does the right candidates too it should be candid too oops uh hmm sorry about this debugging that is really weird what i mean i maybe you're sitting at home and you're like okay this is clearly whatever but now the target is just wrong oh how why did i delete the dirt by three so okay i don't know what happened there maybe there was a typo somewhere that i did it by accident but okay so this looks um better but clearly there's still a wrong answer here that's weird so yeah so one and three are candidates for some reason oh because now this is these are no longer zero or um no that's not true right this has four so i i guess there is another uh my algorithm is just wrong uh or it's not complete um hmm i had to think about this a little bit because basically this gets four votes quote-unquote that gets cancelled by or rather um there's an invariant that i have to think about because for these the three uh they get four votes which in theory these will get cancelled by but but but the ones here as well i think we i'm just thinking about different i'm just thinking about different possibilities of fixing this uh and it might be just that i don't know can we do it in parallel or do i like maybe i can do it a second time and then just do the majority of the because we there we have an algorithm because we there we have an algorithm that allow us to uh get the one dirt for that allow us to uh get the one dirt for at least one number but maybe it doesn't work for two numbers and then we could get the majority of the um of the remaining numbers right let's do that instead i think i was trying to be too clever with trying to do one pass uh sorry about that as i said this is experimental so yeah okay let's try to get one number yeah okay let's try to get one number that's one dirt and if we have one that's one dirt and if we have one number that means that we have a number that means that we have a possible second number right possible second number right because if because if no i don't um now i'm not so sure i mean no i don't um now i'm not so sure i mean i i think now with this visualization i i i think now with this visualization i can see how can see how uh these two votes cancel these one row uh these two votes cancel these one row uh right like three four can't drop the uh right like three four can't drop the one one makes sense but one one makes sense but but but the way that i did it the but but the way that i did it the ordering is weird because ordering is weird because if i if i you know if i change this to if i if i you know if i change this to for example for example um three four five six uh um three four five six uh one one one one um or one one one one um or you know similar to this actually just you know similar to this actually just three three two two two uh like we could three three two two two uh like we could do three um uh let's move to five six to five this is a very long radio side but yeah these three will get canceled by these four ones but we want ones to be the answer so this is not good enough uh let's revert this real quick and then now we have to think about another and maybe we just do one at a time i and maybe we just do one at a time i don't know don't know let's play around with that sometimes in let's play around with that sometimes in a contest you just have to play about be a contest you just have to play about be able to play around with stuff because that was one of my alternative because that was one of my alternative uh things to play around with uh things to play around with but but that doesn't seem like it gives but but that doesn't seem like it gives you the answer obviously you the answer obviously because this is clearly not right um because now the one the three three so now one and then two you might removes to one but not the three even though we huh now i'm just trying different things to now i'm just trying different things to be honest um and let's click on submit for fun uh and then see if we could get a test case that tell us something it's basically you have two two you have it's basically you have two two you have nine three uh yeah because then nine and then the because then the three cancels out the nine because we're greedy and then nine comes in again and so forth so two is always a candidate so the last two candidates are two and nine but you do the last pass the two will uh clear this out so no good there and then the nine um yeah this is an interesting problem you don't hmm now i have to think about it a little um yes i don't remember this album as well yes i don't remember this album as well as i hope so i'm just looking a little as i hope so i'm just looking a little bit on the um bit on the um on the wikipedia article but let me see what shows up here just try let me see what shows up here just try to figure out good visualization with to figure out good visualization with this as well this as well so this one it looks good on this answer but so what can we have a wrong answer did i what hm how do i look at my did i what hm how do i look at my submissions because these are clearly right but i was that one answer just because i had was that one answer just because i had count one so let's zoom it again why not okay wow okay so my first answer was right it's just that a typo and i thought that my algorithm was wrong okay sometimes you just have silly days okay i don't know what to say about that okay i don't know what to say about that but this is i mean this is my first but this is i mean this is my first intuition right intuition right uh and i like as i said you know i'm uh and i like as i said you know i'm gonna go through visualizations gonna go through visualizations and you know it makes sense um but yeah um so what is the out but yeah um so what is the out complexity so this is going to be linear complexity so this is going to be linear time we look at each element time we look at each element uh at most once and uh at most once and well sorry at most all one time so it's well sorry at most all one time so it's gonna be linear time and in terms of gonna be linear time and in terms of space we only have space we only have four variables really right so and the four variables really right so and the results i guess a couple more variables results i guess a couple more variables so it's gonna be all one space um so it's gonna be all one space um yeah that's all i have for this problem um let me know what you think i'm i think i'm just a little confused because i had a typo that um that kind of messed up this video a little bit so i apologize for that uh but and some of it is because uh maybe as a medal lesson if you're still here for so long that um that you know for for a lot of problems i'm confident uh and when you're confident that that means about the algorithm right and when you're confident about the algorithm then you're gonna know that it's the implementation issue uh and that might be in a typo that might mean other things um and in this case because i was not confident about the algorithm i didn't think about um implementation i didn't think about um implementation issue because that was pretty issue because that was pretty straightforward implementation wise but straightforward implementation wise but somebody started typo um and and yeah so definitely uh maybe that's my takeaway for this uh let me know what you think hit the like button to subscribe and join me in discord uh and hopefully tomorrow will be a better day and uh for decoding and i will see you
2024-03-22 11:08:51
229
https://i.ytimg.com/vi/x…axresdefault.jpg
229. Majority Element II - Day 22/30 Leetcode September Challenge
gNZ5R3tfNS8
hello guys my name is ursula and welcome to my youtube channel and today we are to my youtube channel and today we are going to solve a new record question going to solve a new record question that is power of 4 that is power of 4 so let's start so we are given an so let's start so we are given an integer and return the true if it is integer and return the true if it is power of 4 otherwise the term false and power of 4 otherwise the term false and integer n is the power of four uh if integer n is the power of four uh if there exists an integer x say that x n there exists an integer x say that x n is equal to power power x so basically is equal to power power x so basically they are asking is that we have to they are asking is that we have to return to if return to if n is the power of 4 n is the power of 4 okay n is equals to okay n is equals to 4 power x then 4 power x then we have to return that true and we have to return that true and otherwise it's false so i will be giving otherwise it's false so i will be giving you 2 you 2 i will be giving a true solution for i will be giving a true solution for this this the first one is brute force if we do do the first one is brute force if we do do this by brute force this by brute force so if you if you see this so if you if you see this sorry um um what will i do is first of all my n n um um and it's greater than equal to zero and it's greater than equal to zero okay okay and and remainder 4 is also equals to 0 okay if this is so we will divide n by 4 and n is equals to 1 n is equals to 1 so let's see this if it's working or not foreign this was the this was the logic i have used here now second thing logic i have used here now second thing i will i will okay now the second method we are going okay now the second method we are going to apply here is mathematical to apply here is mathematical okay okay guys so we have done this brute force value thing now the second method i am going to tell you is mathematical value so mathematical maths method if we apply so what we will be doing is uh if you see this thing here n is equals to what we have written n is equals to 4 power x okay this is the thing we have okay so if we take log both side what you will be getting here is uh is equals to x uh is equals to x log log 4 okay this is the thing we will be 4 okay this is the thing we will be getting so we will we can write that x getting so we will we can write that x let x is equals to let x is equals to math math math dot log math dot log n n upon upon sorry sorry upon upon math math dot dot log log four so what we will get the value of x four so what we will get the value of x so we we will say that that that we will so we we will say that that that we will say what we will be saying this say what we will be saying this that result is equal to s we will be checking that if x is a whole number then return true else written false so what you will be x x minus minus number number x x okay okay return return x x is equals to 0.0 is equals to 0.0 so so what we are saying here is that if what we are saying here is that if result result sorry yes sorry yes if result is equals to 0.0 then return if result is equals to 0.0 then return true as return false means that if x is true as return false means that if x is for example 4 for example 4 and if we subtract 4.0 it would be and if we subtract 4.0 it would be return zero point four point four oh return zero point four point four oh sorry zero point zero uh so it will be sorry zero point zero uh so it will be true otherwise it would be false like if true otherwise it would be false like if i say this that here we are getting x is i say this that here we are getting x is equals to five and here we are getting equals to five and here we are getting sorry uh five point uh three and the sorry uh five point uh three and the value number is uh if we are suppose we value number is uh if we are suppose we are getting uh are getting uh five so we will be getting a as five so we will be getting a as zero point three so that is not correct zero point three so that is not correct so it will return false so this is the so it will return false so this is the method we have applied as a method of method we have applied as a method of mathematics so we can write this thing mathematics so we can write this thing and run the code and run the code and you can see that we are getting the and you can see that we are getting the answer answer server error so what server error so what is the error coming now okay so is the error coming now okay so uh what we will be saying here is uh what we will be saying here is if if n is greater than equal to zero and then if we will run this here because we do not want the negative value here so we will be only dealing with the values which are greater than zero so if we run this you can see that we are getting the answer so this was this foreign and like the video please do subscribe and do comment and do like the video thank you guys for watching the video
2024-03-24 11:00:17
342
https://i.ytimg.com/vi/g…axresdefault.jpg
342. Power of Four with JavaScript | Leetcode question with Javascript #youtube#leetcode#javascript
1en6nTXuhIQ
hi guys let's do the lead code eight string to integer lead code eight string to integer it's also known as a280i it's also known as a280i if you been reading your knr you would if you been reading your knr you would see that see that they talk about atoi so what is it knr is kerning an enriched c programming language so um implement the problem states that implement a t o i which converts a string to an integer then he says that the function first then he says that the function first discards as many white space characters discards as many white space characters as necessary as necessary until the first non-white space until the first non-white space character is found character is found then starting from this character takes then starting from this character takes an optional initial plus or minus sign an optional initial plus or minus sign followed by as many numerical digits as followed by as many numerical digits as possible and interprets them as a possible and interprets them as a numerical value numerical value the string can contain additional the string can contain additional characters after characters after those that form the integral number those that form the integral number which are ignored and have no effect on which are ignored and have no effect on the behavior of this function the behavior of this function if the first sequence of non-white space if the first sequence of non-white space characters in str is not a valid characters in str is not a valid integral number integral number or if no such sequence exists because or if no such sequence exists because either either str is empty or it contains only white str is empty or it contains only white space characters no conversion is space characters no conversion is performed performed if no valid conversion could be if no valid conversion could be performed zero value performed zero value is returned um only the space is returned um only the space character is considered a white space character is considered a white space character so that's easy we don't have character so that's easy we don't have to to compare it with slashing or slash t compare it with slashing or slash t assume we are dealing with an assume we are dealing with an environment that could only environment that could only store integers within the 32 bit sign store integers within the 32 bit sign integer range so then we are integer range so then we are in a 32-bit sine integer range which is in a 32-bit sine integer range which is in in max which is 2 raised to the power 31 max which is 2 raised to the power 31 minus 1 or in minus 1 or in min which is this is negative 2 raised min which is this is negative 2 raised to to 31 so that's pretty much 31 so that's pretty much is the problem and he gives an example is the problem and he gives an example for example you're given the string 42 for example you're given the string 42 you convert it to 42 integer you convert it to 42 integer you're given minus 42 string you convert you're given minus 42 string you convert to minus 42 to minus 42 you're giving 4 193 with words and these you're giving 4 193 with words and these all these other known digits are all these other known digits are basically ignored basically ignored so you get 4193 then you have watts and so you get 4193 then you have watts and 987 you get 987 you get 0 and that's 0 and that's because he's saying the first because he's saying the first non-white stress vector is w this is not non-white stress vector is w this is not a numerical digits or a plus minus sign a numerical digits or a plus minus sign therefore no valid conversion could be therefore no valid conversion could be perform perform ic that's interesting so basically ic that's interesting so basically i guess we'll need to have a check that i guess we'll need to have a check that checks for checks for the character to be between 0 and 9. the character to be between 0 and 9. now str equal to this one this is now str equal to this one this is interesting as well because interesting as well because it's saying this is out of the range of it's saying this is out of the range of a 32-bit sign a 32-bit sign integer therefore into min is returned integer therefore into min is returned so if you're out of the range and so if you're out of the range and depending upon whether you're negative depending upon whether you're negative or positive then you're just returning or positive then you're just returning max okay so let's give it a shot max okay so let's give it a shot hopefully it's not too hard it's a very hopefully it's not too hard it's a very classic problem i would say classic problem i would say so we need a so we need a indexer into s or iterator whatever the indexer into s or iterator whatever the heck you want to call it so it's heck you want to call it so it's i and then you have i and then you have sine and i would initialize that one to sine and i would initialize that one to one i would be initializing the for loop one i would be initializing the for loop and then we can have a and then we can have a variable on it result variable on it result which where we would be storing the which where we would be storing the results results now for i equal to 0 now for i equal to 0 so first thing we should do is as the so first thing we should do is as the problem states problem states skip all space characters equal to this now equal to this now normally we would have also probably normally we would have also probably checked like s i checked like s i equal to equal to [Music] [Music] new line or slash tab but you know this new line or slash tab but you know this is he said that don't worry about them is he said that don't worry about them only only space is considered a white space space is considered a white space character then we just say character then we just say okay that's not the only thing and then okay that's not the only thing and then we have to say i plus plus typical while we have to say i plus plus typical while loop loop and then you say basically that is your and then you say basically that is your skipping all white space because the skipping all white space because the body of the for loop in this case will body of the for loop in this case will be empty be empty now after we have done that now after we have done that we have to take care of the sign so how we have to take care of the sign so how do we take your do we take your sign so we say if sign so we say if s i at this point is s i at this point is equal to plus equal to plus or s i equal to or s i equal to minus then what happens then we have a check which says okay so now we are assigned the value of sign so sign is we can have a seize power here where we in as few lines we can get our effect so then the sign is we check if it is equal to this we check for that and if that is the case if we return the sign will be one otherwise the sign will be minus one right so the sign gets fixed here now what is the catch here work on the next digit so you make sure work on the next digit so you make sure that the i is incremented over there that the i is incremented over there so now you come to another wire loop so now you come to another wire loop where we start by initializing result to where we start by initializing result to 0 0 then we say if s i you could also then we say if s i you could also use a for loop here with a little bit of use a for loop here with a little bit of jugglery i would say but it's as good as jugglery i would say but it's as good as this this so be in the loop as long as we have so be in the loop as long as we have this condition fulfilled which is so i was actually using a while loop here and i had while something like this like while s i not equal to null character basically walk through this string right and then within that you can have things like s i is it is it and things like that and then but this is and then you you have to also initialize the result to zero here if you you're going to use the while loop because while loop will not initialize the um the accumulator or result for you you need to do it outside and in the for loop also but for loop gives you a very well defined construct to go over these problems and si less than equal to the digit 9 then we are in good shape and then we can do i plus plus right here now at this point as you can see we all we need to do is we need to say result equal to the result times 10 plus keep adding the the new digit that you find so that is s i minus zero s i minus zero so that's your thing now what is the so that's your thing now what is the catch here catch here he's saying first of all let's see if it he's saying first of all let's see if it passes through passes through some of the test cases at this point some of the test cases at this point already already so at this point if we come back so at this point if we come back here and we can simply return sign times here and we can simply return sign times result result what happens then let's see this is one what happens then let's see this is one code and as you can see this that is failing and as you can see this that is failing and that is failing and that is failing because he's saying look at the the because he's saying look at the the error number error number look at the error that he actually gives look at the error that he actually gives he says this cannot be represented in he says this cannot be represented in type int type int so we have a problem here our result is so we have a problem here our result is actually in then he said very clearly actually in then he said very clearly when you look back when you look back he said that if you cannot represent it he said that if you cannot represent it within this within this this 32-bit sign in these are ranks then this 32-bit sign in these are ranks then we have to basically return we have to basically return in max arrangement so in that case i was in max arrangement so in that case i was actually trying something like this actually trying something like this and then doing a check if and then doing a check if the result is so here i have the result is so here i have we can have a check which says if result we can have a check which says if result is greater than is greater than in max now in max now we can do something here we can say if we can do something here we can say if result is greater than max then if now if the result is greater than in now if the result is greater than in max then if result max then if result if sine is see if sine if sine is see if sine is minus 1 like because is minus 1 like because we already have taken the sine so if we already have taken the sine so if sine is minus 1 sine is minus 1 we just set result to in max plus 1 but as you can as you know in absolute sense uh the sign negative sine 32 max is actually one more than the in positive in 32 in positive in 32 number so and then otherwise it's just number so and then otherwise it's just in max right now in max right now and then we can just break but then the and then we can just break but then the problem is problem is that should take care of that let's see that should take care of that let's see that and as you can see that basically is passing the all the test cases but i guess i think one of the things he mentioned was that assume we are dealing with an environment that could only store integers within the 32-bit sign integer range so basically we i don't think we have choice to use in 64. so in that case how about that you can make use of double to make sure that this when this this doesn't overflow and every time we calculate result we see hey is it greater than max that means for a hint it has already overflowed in that case we just do this little bit of convoluted logic i would say not too much of it then break out of that and then we are good to go so let's say it passes this one and wow cool so it's four milliseconds wow cool so it's four milliseconds faster than the faster than the 56 percent of c online solution so 56 percent of c online solution so that's cool that's cool so as you can see we just nailed the so as you can see we just nailed the lead code 8 which was characterized as lead code 8 which was characterized as medium medium difficulty but it's very classic c difficulty but it's very classic c kind of problem where you do the integer kind of problem where you do the integer ascii to integer taking care of the ascii to integer taking care of the overflow overflow and the plus sign and minus sign i would and the plus sign and minus sign i would say say and also making sure that you skip all and also making sure that you skip all these space characters these space characters so there you have it so there you have it uh we just in distinct integer a to i in distinct integer a to i we did called it and we did called it and don't forget to subscribe to the channel don't forget to subscribe to the channel and i will see you guys in the next and i will see you guys in the next video video until then adios asta manana
2024-03-19 11:57:57
8
https://i.ytimg.com/vi/1…axresdefault.jpg
Leetcode 8: String to Integer (ATOI)
266HkbRLoYE
Hello friends, in this video we are going to solve this problem by designing a circular DQ. solve this problem by designing a circular DQ. Basically, we have to implement a circular Basically, we have to implement a circular DQ and design it DQ and design it so that so that I can do all the operations in it very easily and I can do all the operations in it very easily and all this. all this. all this. who has to implement the circular deck, not just the deck, what happened to us in the deck was that I could do all the operations in the beginning and in the last, but what is the meaning of circular, I I I I can go from the last to the beginning, right means after going to the last, can go from the last to the beginning, right means after going to the last, you can go to the beginning again, so there is you can go to the beginning again, so there is a lot of operation in this, you have to simply a lot of operation in this, you have to simply implement it like insert implement it like insert last, delete front, delete last, get front, get rare, last, delete front, delete last, get front, get rare, so let me tell you. so let me tell you. so let me tell you. question in a very different way and then I will tell you how things work, so make sure that you subscribe the channel right now because you forget to subscribe later and subscribers are very important, so please subscribe. See, what we have is a, first d is d, what we do in this is that I can insert the element from the beginning and can also remove the element from the beginning, I have taken it out like this, I can insert the element in the last I can remove the element from this, I can remove the element from this, I can remove the element from this, this is our d, okay, okay, this is our d, okay, okay, understand, what is meant by circular, understand, what is meant by circular, after coming from here, after coming from here, I will after coming from here, after coming from here, I will go directly here, right, now see go directly here, right, now see my circular d, what is its size. my circular d, what is its size. my circular d, what is its size. three three given okay after that insert last one insert last suggest we don't have any last so no I will insert this then what will I do I will go to insert last insert last so no element is I will do it last, it will be fine, like if I have I will do it last, it will be fine, like if I have I will do it last, it will be fine, like if I have played it, I can do it in the end, then the played it, I can do it in the end, then the answer will be true, then I answer will be true, then I can bring it, then I have done the answer, I will go can bring it, then I have done the answer, I will go ahead and then our insert front ahead and then our insert front is, insert front, what is insert front? is, insert front, what is insert front? is, insert front, what is insert front? insert 'th' in the front, I can insert 'th' in the front, I can also do it in the answer, then 't' will be done and see my circular DC, its size has been given as 'th', I If If If I do insert front, what will I do insert front, what will happen to us, which is the fourth element, I happen to us, which is the fourth element, I will try to insert it in f, so as soon as will try to insert it in f, so as soon as I try to insert four here, our I try to insert four here, our size is only th, so I will not be size is only th, so I will not be able to do it. See, insert front function works. able to do it. See, insert front function works. Well, I have done that but its size Well, I have done that but its size is three and here I am inserting the fourth element, is three and here I am inserting the fourth element, so what can happen, so what can happen, not possible, then what will be the answer not possible, then what will be the answer false, then I will move ahead, false, then I will move ahead, then I will move ahead, get rear, get rear then I will move ahead, get rear, get rear rear rear rear element two then I can receive two then what will be the answer we have received two two and then I will move ahead what is full which is Return two, Return two, Return two, why because three is the size of three why because three is the size of three elements and three is this size. elements and three is this size. Go ahead delete last. If you want to delete last Go ahead delete last. If you want to delete last then I will delete t from it, that means I then I will delete t from it, that means I can delete tr, it will be fine then can delete tr, it will be fine then jaga insert front four four. jaga insert front four four. jaga insert front four four. in the front, so now what will I do, see here first I will delete it so that you can see that yes, I have deleted it and now what will I do, what will I do, put the four in the front, okay, then I will move ahead, If you If you If you put it in the front, then it will become gate put it in the front, then it will become gate front. Who is there in the front? If there is four, then four will front. Who is there in the front? If there is four, then four will come in our answer. So see come in our answer. So see all the operations which are there; insert last insert last get front all the operations which are there; insert last insert last get front get rear is full delete get rear is full delete last etc etc, this is also a function. last etc etc, this is also a function. We have to implement everything. Okay, so whatever We have to implement everything. Okay, so whatever we have done here, we have to do the same thing there with Sem. we have done here, we have to do the same thing there with Sem. We have We have inbuilt functions available for all the functions, so I will do inbuilt functions available for all the functions, so I will do everything with its help. So everything with its help. So let's understand. let's understand. let's understand. see, what we have to do is first create a D and make its size. Now what I will do is pass it in the constructor which is of the element, what does it mean, which is of the element, I will keep it in the size. How much is our size? Okay, now I have to insert the front. If I have to insert it in the front, then first I will check whether the size of d is less than the size of d. If it is less, Will I be able to do it, if it is full, please Will I be able to do it, if it is full, please Will I be able to do it, if it is full, please see, D is there, it has a tooth and its size is see, D is there, it has a tooth and its size is also our three and there is some size three, is there any also our three and there is some size three, is there any element four which I have to put in it, element four which I have to put in it, so can I put it, no, I can't put it, so can I put it, no, I can't put it, will I check first? will I check first? will I check first? is less or not then I will insert T and return it otherwise I will do the insert last then I will check the size of D whether there is space in it or not, only then I will be able to insert it and if not Can't insert Can't insert Can't insert right delete front If I want to delete the front right delete front If I want to delete the front then should I check which DK is not E then suggest if there is any then should I check which DK is not E then suggest if there is any DK and it is there is DK and it is there is no element in it and I am told to no element in it and I am told to delete the front element. delete the front element. delete the front element. can I do it? If not then I will check first. If it is not there then I can delete. If not then I can delete. Last then I will check whether it is not there. If it is MT then can Delete last element ca Delete last element ca Delete last element ca n't do front if k is mt then n't do front if k is mt then return minus otherwise front element k if k is return minus otherwise front element k if k is mt not mt then return last element otherwise if mt not mt then return last element otherwise if manav has to manav has to check whether we have mt or not check whether we have mt or not check whether we have mt or not what will I do directly, the mother function is ours, I will return it, is it full or not, I will check the size of A, is it equal to our size or not, we have treated the size right and all the All the work is All the work is All the work is done in ofv because you are done in ofv because you are deleting from the front, inserting from the front in o one, deleting from the front, inserting from the front in o one, inserting from the last in the front o one, inserting from the last in the front o one, deleting from the last in the deleting from the last in the front of one, or in the o v. front of one, or in the o v. front of one, or in the o v. right, let me show you the same code in Java too. You will get to see the same code in Java. We have constructed it, then in the insert function we will Will Will Will check in delete whether it is empty Will check check in delete whether it is empty Will check in delete whether it is empty in delete whether it is empty Check in gate front if it is empty Will check in Check in gate front if it is empty Will check in rear gate if it is empty Will rear gate if it is empty Will check in MT If it is check in MT If it is zero then zero then zero then not then it is not MT and we will check its size in L. Is it zero or is its size equal or not? If you see, the number of elements in D is the same, its size means it You must have understood this very simple You must have understood this very simple You must have understood this very simple question. If you question. If you still haven't understood in this case then still haven't understood in this case then rewind the video and watch what I told you again and rewind the video and watch what I told you again and you will understand. So let me you will understand. So let me run the code and show you. Okay but run the code and show you. Okay but before that if before that if before that if then you can take it by going to this link or if you want DSA course then go to this link and you can take it. More than 9 lakh people have The course is The course is The course is available in both the languages. If you available in both the languages. If you use the Loki 10 coupon code, you will use the Loki 10 coupon code, you will get an instant discount of Rs. 15. get an instant discount of Rs. 15. You can also join our club. You can also join our club. You will find all the links in the description, so You will find all the links in the description, so let me run the code and show you. let me run the code and show you. Okay, so Okay, so see what I will do, I will show you see what I will do, I will show you how, one minute I do this a little bit, how, one minute I do this a little bit, I go into C plus plus and this is our I go into C plus plus and this is our code of C, which I told you code of C, which I told you is the code, I do it a little bit once. is the code, I do it a little bit once. is the code, I do it a little bit once. understand it well and do it, I will click on submit and I don't think you will have any doubt related to this because it is a very easy question. Okay, now what I do is I show you the Java code and You will not even be asked, You will not even be asked, You will not even be asked, but you should know a little bit about but you should know a little bit about when I can insert and when I can insert and when I can delete, so this is our Java when I can delete, so this is our Java solution, I will submit it also, solution, I will submit it also, so let's meet you in the next video, so let's meet you in the next video, some such videos. some such videos. some such videos. subscribe the channel, like the video and share it with your friends because
2024-03-20 14:31:10
641
https://i.ytimg.com/vi_w…xresdefault.webp
Design Circular Deque | 641. Design Circular Deque | Coder Army Sheet | Leetcode | Amazon | Google |
gKhvVHd8ihI
hey what's up guys john here uh so today let's take a look at this uh uh so today let's take a look at this uh this elite called this elite called problem here uh number 419 problem here uh number 419 battleships in the board so okay so battleships in the board so okay so you're given like a 2d board you're given like a 2d board and you need to count how many and you need to count how many battleships are in it so how battleships are in it so how what does so what does the what does so what does the battleship means right so battleship are battleship means right so battleship are represented by represented by x and and the battleships can only be placed horizontally or vertically will at least have one dot in between will at least have one dot in between right and the length of the battleship right and the length of the battleship it's not limited to to one or to any it's not limited to to one or to any length length right so for example here in this right so for example here in this in this like 2d graph here there are two in this like 2d graph here there are two battleships right battleships right because it says the battleship can only because it says the battleship can only be placed either be placed either horizontally or vertically right horizontally or vertically right so basically any continuous so basically any continuous axe will belong to the same same axe will belong to the same same battleship battleship right for example this one the right for example this one the the first battleship is this one and the the first battleship is this one and the length of battleship is one length of battleship is one the second battleship is this one the the second battleship is this one the length of three length of three and it also gives you another example and it also gives you another example here this is like an invalid here this is like an invalid example because it says a battleship between battleships it has to be uh at least one dot in between and this one since this is a battleship this is also battleship right but there's no so that's why this one is invalid okay so how so how are we going to uh to solve this problem right so things like you can think of this uh this like uh array to the array as a as a graph and to do that you know we can use like and to do that you know we can use like uh uh either dfs or bfs either dfs or bfs either dfs or bfs either dfs or bfs search right basically every time search right basically every time we see a axe here right we know okay we we see a axe here right we know okay we seize a battleship seize a battleship and then we just start from here we uh and then we just start from here we uh we traverse all the uh we traverse all the uh we traverse other the room uh we traverse other the room uh all the acts that's on the same i mean all the acts that's on the same i mean that are linked together that are linked together right so by linked together i mean left right so by linked together i mean left right top and down right top and down right and once that is finished then we right and once that is finished then we are we finish are we finish the uh traversing this one shape the uh traversing this one shape and we can also after and we can also after traversing the every node here we can traversing the every node here we can just mark this uh change the x just mark this uh change the x back to dot so that we won't uh traverse back to dot so that we won't uh traverse this this one more time right so that's the first step right so i'm sorry that's the uh that's the the native approach uh let's try to write this native approach it should be pretty straightforward in this case and m equals to length like board right i'm going to create a board here board zero right then board zero right then i'm gonna have a directions here right i'm gonna have a directions here right so since we're going to uh so since we're going to uh traverse all four directions we're gonna traverse all four directions we're gonna have minus one have minus one zero and then zero minus one zero minus one and zero one right so and then we just do a for loop right before uh loop through the entire the entire 2d board and for j in range and right so every time when we see uh x right then we start our traversing either bfs or dfs is equal to uh x is equal to uh x right then we start out traversing right right then we start out traversing right so first i'm gonna increase this thing so first i'm gonna increase this thing to one to one okay um let's do a dfs traverse this time because we have i have done we have done a few like bfs in the previous videos uh so for the again so who for those who are curious about bfs search bfx reverse we're gonna have a q we're gonna have a q and then every time we see so like uh unvisited x right we just uh move that thing we just move that we just add that coordinates coordinates to the to the queue and then we do a this loop until the queue is empty and for the dfs right the dfs is a similar thing dfs let's do the dfs will be using a dfs like a recursive call basically and here is going to be the inj current okay so we do this right and then we simply do a dfs dfs of this current ing right we we um we do a for loop right so first i'm gonna set this current eye and corn j market to be dot so so that we know this thing has been visited before right so that we when we see the x it we won't be uh processing the same max again right and then starting from here directions right so new i current directions right so new i current i plus d0 right similarize the uh the i plus d0 right similarize the uh the bfs bfs instead here we're using like uh similar to the bfs we're using a dfs which which will be which is the uh the recursive call here basically we check if check the boundary check new i right m new j n right and what new j n right and what and this like board and this like board uh new i new j is equal to the x then we then we if it's it's acts right then what do we if it's it's acts right then what do we do we uh we do a dfs uh new we do a dfs uh new i and new j right i and new j right so and we'll know so since every time it so and we'll know so since every time it when it reaches here it will mark this when it reaches here it will mark this one to the one to the to the visited here so i'm not going to to the visited here so i'm not going to mark it here i'm going to leave this job mark it here i'm going to leave this job to to uh to here right uh to here right at the beginning so basically after this at the beginning so basically after this thing's finished thing's finished right then uh right then uh the uh all the the uh all the so for the current shape right all the x so for the current shape right all the x have been have been marked as as dot right then when this marked as as dot right then when this one is finished one is finished right then we know okay all the x will right then we know okay all the x will be marked to dots and then we know we be marked to dots and then we know we have have seen the complete the whole ship seen the complete the whole ship already right and then we just keep already right and then we just keep moving until moving until we traverse finish all the we traverse finish all the we have seen all the the positions all we have seen all the the positions all the the elements on this 2d elements on this 2d board right in the end we simply return board right in the end we simply return an answer an answer this should just do it if i this should just do it if i board okay typo here all right cool so all right cool so it works so pretty straightforward so it works so pretty straightforward so it's just like simple it's just like simple uh simple like bfs or dfs traverse uh simple like bfs or dfs traverse every time when you see so x right and every time when you see so x right and then you just uh then you just uh increase the number of the shapes right increase the number of the shapes right and then and then in the end uh we just do a quick check in the end uh we just do a quick check here right so here right so and then we just mark this thing to dot and then we just mark this thing to dot to mark the visited set right but then to mark the visited set right but then what's the time complexity and space what's the time complexity and space complexity right so the space complexities zero actually zero actually it's zero right and then because it's zero right and then because we're not introducing any any new uh we're not introducing any any new uh arrays here arrays here we're just simply using the the we're just simply using the the parameters right parameters right and then now what's that the time and then now what's that the time complexity complexity the time complexity is going to be a the time complexity is going to be a this is dfs and this is dfs and uh dfs is going to be a basically m times n we are doing the dfs again but we are doing the dfs again but but since it's it's bounded right the but since it's it's bounded right the dfs will be bounded to the dfs will be bounded to the number of x here so basically we're not number of x here so basically we're not re visiting the x re visiting the x more than once let's see and since the uh for each of the dfs right so for to do through each node we need like m times n and the entire dfs here that's the uh so how many dfs will be will be here right so basically we're going to have like the uh the number of the x right basically if there's like x dot gonna like implement gonna like implement something like the number of x here something like the number of x here number of acts right yeah because it's uh every time once we we finish the act visiting x we will be mark this one to dots so we will not revisit x multiple times that's why we do add here right okay cool i think that's pretty much it is for this problem and oh sorry no there's a follow-up here right can you do it in yeah see could you do it in one pass using only one actual all one extra space and without modifying the value of the board right so i think we're kind of doing one pass with o1 actual memory but we're modifying this board right and it asks you can you can can you come up with another solutions with a better like only one pass without actual memory and without without the modification right then then then we cannot use the dfs or bfs right because for the dfs or either dfs or bfs we have to memorize the uh which node we had been visited before right that's why that's we either do a modification of the of the board or we do a actual space to do a scene set to track those right so but it asks us can you do it without using either dfs or bfs right so how should we do it right like the uh come out this thing like the uh come out this thing so if you if you watch closely i think it's kind of obvious you know because we know right if there's like if if this x right let's say if there's a x x x and dot dot and there's another like x x x right let's say this is the the board here right let's also uh just ignore all the other dots at this moment right so if you see that so as at least for this x right if we see x and there's like either like a left or x or right is also x then we know let me know okay so this x is part of the of the ship right the battleship so we can simply ignore it right same thing so that's why for me i just come up with so that's why for me i just come up with a with a solution here so a with a solution here so we just need to think of so when should we just need to think of so when should we mark this where should we we mark this where should we increase the count of of battleship increase the count of of battleship right right so for me i use this starting point so for me i use this starting point i use the leftmost x which is this one i use the leftmost x which is this one and the topmost x and the topmost x to to indicate okay i have seen a to to indicate okay i have seen a battleship battleship and so that means if there's and so that means if there's nothing on the left or the or there's a nothing on the left or the or there's a dot on the left dot on the left right then i mark this thing right then i mark this thing i mark this thing to be a a strip right i mark this thing to be a a strip right to be a start of the ship to be a start of the ship and anything that any x if there is a x and anything that any x if there is a x on the on the on the left then it's a part of then on the left then it's a part of then it's a it's a it's a part of the shape right basically it's a part of the shape right basically i just i just ignore it i just i just ignore it same thing for this shape for the same thing for this shape for the vertical shape here right vertical shape here right if there's a like a x uh there's nothing if there's a like a x uh there's nothing on the top on the top or what where the or what where the where the above one is dots then i i i where the above one is dots then i i i will mark i would reincrease the shift will mark i would reincrease the shift count because i know i count because i know i already found the ship that is a already found the ship that is a is placed vertically right and then is placed vertically right and then if this acts the top one if the x above if this acts the top one if the x above it it if the so if if the so if the above the element the above the element of the current x is also x right then we of the current x is also x right then we know we i can just know we i can just simply remove it just like how we uh simply remove it just like how we uh ignore sorry i can ignore this one just ignore sorry i can ignore this one just how we ignore how we ignore this one for the horizontal shapes right this one for the horizontal shapes right and then we simply do a loop through and then we simply do a loop through each of the dots here okay so let's try to code this thing right so same thing i'm gonna copy this one here so that's uh that's for sure what we need here to do the for loop and then we simply do a range here right just and uh so if right so the still the the condition for us is we have it has to be x first right and then we do what we check right i think from me i think i i check i think from me i think i i check if i need to so basically i check if i if i need to so basically i check if i need to need to continue i need to skip the current x continue i need to skip the current x right right basically i do uh so i check this one first right if that if the left one is x then i uh i skip but we also need also only do a boundary check basically if the j is greater than zero right otherwise there's no no left right and board i j minus one j minus one is also x right then we think simply or simple skip continue right same thing if i is greater than zero and if i is greater than zero and board i minus one j board i minus one j is x we also continue is x we also continue right and now since we have already right and now since we have already skipped the uh the unvalid skipped the uh the unvalid start off the ship then let's check start off the ship then let's check right if if j equals to zero right that's a if j equals to zero right that's a starting point starting point sorry sorry if the board's uh j equals to zero and then we know we need we have seen the ship or or what or the uh there's a the left one is a dot or the word i dot j minus one is a dot right then we know okay we have seen like a ship that had been placed horizontally like this one right then we do answer plus one right else else right so we cannot do a if here because once we have seen the ship we because once we have seen the ship we cannot mark it again right basically and else i'll see if sorry else if i equals to 0 or board i minus 1 j and start right then we also we also mark this one to be a ship right in the end we simply return the okay let's just run it okay let's just run it yeah this thing also works yeah yeah this thing also works yeah basically in this case basically in this case it satisfies the follow-up here it satisfies the follow-up here basically it's still a one pass right basically it's still a one pass right which loops through the which loops through the the entire 2d uh board one time the entire 2d uh board one time and with no extra with no and with no extra with no extra memory and without modifying the extra memory and without modifying the board we simply use a bunch of board we simply use a bunch of if check here right and cool i think that's that's it for this problem yeah thank you so much for watching the videos guys and hope you guys enjoyed enjoy it and
2024-03-15 18:42:57
419
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 419. Battleships in a Board
K9jlX5yh7iM
hello everyone even before starting today's session i even before starting today's session i would like to point you guys to the would like to point you guys to the other video that i have published today other video that i have published today do have a look at it it has million do have a look at it it has million dollar of valuable advice in it it's by dollar of valuable advice in it it's by someone who was among you guys one of someone who was among you guys one of the subscriber of a coding decoded the subscriber of a coding decoded channel he worked really hard for it and channel he worked really hard for it and got through morgan stanley so it's all got through morgan stanley so it's all about his journey and there are multiple about his journey and there are multiple instances which he has quoted in the instances which he has quoted in the video from which you can take video from which you can take inspiration and it will motivate you inspiration and it will motivate you guys to perform better at coding guys to perform better at coding interviews interviews now let's move on to today's session now let's move on to today's session today's session is about day 14 of today's session is about day 14 of september liquid challenge the question september liquid challenge the question that we have today is an easy question that we have today is an easy question the name of the question is reverse only the name of the question is reverse only letters letters in the question we are given a string s in the question we are given a string s we need to reverse this string we need to reverse this string such that all the non-english characters such that all the non-english characters retain their position the rest of the retain their position the rest of the english characters gets reversed for english characters gets reversed for example here the input string is a b example here the input string is a b hyphen c d hyphen c d so a position gets replaced by d b's so a position gets replaced by d b's position gets replaced by c and the position gets replaced by c and the hyphen position says either it is hyphen position says either it is because it is a non-english character because it is a non-english character similarly you can go through the other similarly you can go through the other examples as well you will witness the examples as well you will witness the same thing same thing without much to do let's look at the ppt without much to do let's look at the ppt that i have created for this and let's that i have created for this and let's get started with today's question get started with today's question reverse letters only lead code 917 reverse letters only lead code 917 and i have taken a slightly different and i have taken a slightly different example to what was specified in the example to what was specified in the question the string that i have is a c d question the string that i have is a c d exclamatory mark p exclamatory mark p a c d and p are my english characters a c d and p are my english characters valid english characters and exclamatory valid english characters and exclamatory mark is an exclamatory mark mark is an exclamatory mark how am i going to solve this question how am i going to solve this question as a general practice for reversing a as a general practice for reversing a string you take two pointers and i'll string you take two pointers and i'll exactly do the same thing exactly do the same thing except for the fact whenever i see a except for the fact whenever i see a non-english character either from the non-english character either from the starting pointer or the ending pointer starting pointer or the ending pointer i'll skip it i'll skip it how let's iterate through it how let's iterate through it the first character is a which will be the first character is a which will be pointed pointed by the start pointer and the end is p by the start pointer and the end is p which will be pointed by the p character which will be pointed by the p character both of them we will check if both of both of them we will check if both of them are valid english characters we them are valid english characters we will perform this swap operation so will perform this swap operation so let's swap those up let's swap those up we have p here we have p here we have a here we have a here and what we're going to do as we swap and what we're going to do as we swap both of them we'll increment s and we both of them we'll increment s and we will decrement end what do you see here end is being pointed at a non-english character which is an exclamatory mark so what you are going to do you will simply skip this character you will copy this character or retain this character to the same position and you will reduce the pointer of e so e now points to d and s remains at the same place now both of them are english characters and you will perform the swap operation so these two get swapped and we have d here we have c here and what you are going to do next you will increment s decrement e so e points here s points here and this is a breaking condition you abort the process at the end of the it we have the updated string which is nothing but p d c exclamatory mark followed by a capital a this seems like a pretty easy question uh interviews generally ask these questions as a preliminary clearing round as i told in yesterday's video as well so writing a clean crisp code or such videos is of high importance to catch interviews attention that you encode well the time complexity of this approach is order of n and we are not using any extra space we are updating the initial input string so the space complexity is constant time without much to do let's look at the solution that i have coded for this and let's move on to the coding part the first thing that i have done here is to create a character array from the input string that is given to me because strings are immutable while you can replace specific instances of c uh when given in the array format i've taken two pointers s and start and end till the time my start is less than end i check if my current start character happens to be a valid english character if it is not then i increment the start pointer and contains the process similar thing i also do for the end character and if my end character happens to be a non-english character i reduce the end pointer and continue the process without even swapping anything if both of them are valid english characters then i perform the swap operation i increment the start pointer reduce the end pointer and return my updated string how have i written is english character helper method it accepts a character and it check it checks whether the character is an english english uppercase character or lower english lowercase character if it happens to be it returns true otherwise it returns false pretty straight forward accepted accepted and i have already talked about the time and i have already talked about the time complexity and the space complexity of complexity and the space complexity of the solution the solution this brings me to the end of today's this brings me to the end of today's session session if you liked it please don't forget to if you liked it please don't forget to like share and subscribe to the channel like share and subscribe to the channel thanks for viewing it thanks for viewing it have a great day ahead and stay tuned have a great day ahead and stay tuned for more updates from coding decoded for more updates from coding decoded i'll see you tomorrow with another fresh i'll see you tomorrow with another fresh question but till then good bye
2024-03-25 10:56:53
917
https://i.ytimg.com/vi/K…axresdefault.jpg
Reverse Only Letters | Leetcode 917 | Live coding session 🔥🔥🔥
CT9b6B_CyY4
channel of Jhal Hello Hello and Welcome is Asha Question is 165 Computers A Number Okay 165 Computers A Number Okay so basically we give Question Is saying so basically we give Question Is saying and what is the question So electricity used to go to Saturday and what is the question So electricity used to go to Saturday If we read this then If we read this then it is given in such words number We get 1.4 it is given in such words number We get 1.4 Whatever you write, it should be done twice quickly. Whatever you write, it should be done twice quickly. If there is a question, then keep Nadiya here that If there is a question, then keep Nadiya here that how to return. If the position is to greater how to return. If the position is to greater Hussain - If you want to close the version for the great, Hussain - If you want to close the version for the great, then the weight has to be returned. We can see the then the weight has to be returned. We can see the mother's murder here. mother's murder here. mother's murder here. here, I can't understand it even with pimples, like 1.01 is written and 1.001 is written that both have equal usage which is the leading role or there is no value, It It It is 1.0, it is 1.00, so if it is not given there, then is 1.0, it is 1.00, so if it is not given there, then it will definitely give all after some point, it will definitely give all after some point, so both of them are correct, now here it is so both of them are correct, now here it is written 0.1 and here it is written 1.1, so written 0.1 and here it is written 1.1, so now things like 1.10 is greater, meaning now things like 1.10 is greater, meaning first. first. first. man has tons, simple implementation is questionable, let's see how to do it in more, okay, first of all, what will we do, let's make this a guest or else, then I Equal to that Bhajan Bhandar plate is fine and when I have to do dots plus then you do it like this otherwise it is Multani okay then what will you do boys that maybe I have used the wrong one. that maybe I have used the wrong one. It will be done like this so It will be done like this so that including that now it is done I have that including that now it is done I have come to travel in the Amazon of both the semesters come to travel in the Amazon of both the semesters and jelly has been taken now what will you do My and jelly has been taken now what will you do My Island One Laut Length and Judgment World Does Island One Laut Length and Judgment World Does Not Length Okay now what to do what will you do to Not Length Okay now what to do what will you do to that that that anti anti zone.com austin is zone.com austin is dynasty your result dip in danger dots end me come birthday you me now here I have It has happened that the It has happened that the It has happened that the weight is weight is 232. 232. If you don't do it then use it like a screen. If you don't do it then use it like a screen. Even before that, you can easily Even before that, you can easily use it by looking at them. You If If you do, then there will be a The album has to be returned till then, The album has to be returned till then, The album has to be returned till then, you will return - woven, you will return - woven, then what will you do, then you will put it on the cycles then what will you do, then you will put it on the cycles and make it once again, okay, and make it once again, okay, you have done it, from now on, what will happen like in you have done it, from now on, what will happen like in this example, you will see that that this example, you will see that that Which one here is 1.00, here it Which one here is 1.00, here it can be 1.0, 1.1, neither can come can be 1.0, 1.1, neither can come in which print to control their six, so in which print to control their six, so it will be 2 more minutes, will divide it in two, will it will be 2 more minutes, will divide it in two, will divide it in the middle, so for that, divide it in the middle, so for that, do that one. do that one. do that one. end here, then now we will not wait outside for that. Wife is licensed but one daughter's length is yours. Is it teacher.com 0 Why what happened when I am in The Flirting The Flirting The Flirting Commission has notified you for this, Commission has notified you for this, but what will you do? Now but what will you do? Now if this does not happen, it means that the other person if this does not happen, it means that the other person 's 's wife is Nisha and it is simple for him, then here I made a mistake, I subscribed here and got a plate here I will I will if all these people are there then what to do now, what will you do now, will you do it or not, will you do you do now, will you do it or not, will you do 80, it is finishing here, maybe 80, it is finishing here, maybe one of my packets is too much, let's see, it is one of my packets is too much, let's see, it is for yes. for yes. for yes. this torch has started that torch has started that it has become alone, please plant Akshay in me, please see Ajay, Ajay, that if Bhushan is here, then that if Bhushan is here, then Okay, okay, Okay, okay, Okay, okay, both of these are easily okay, so both of these are easily okay, so now let's try our own tests and see, now let's try our own tests and see, it all started here it all started here and here we have reached zero point, then what will and here we have reached zero point, then what will happen if the Rahi Hamari Rahi Hamari Rahi Hamari Ho Hain Iss Style One Status And Why Doesn't Seem Was Written Ok Ok How Did This Test Happen Now Spooch Why Doesn't Seem Was Written Ok Ok How Did This Test Happen Now Spooch Karo Yahan Par Two Songs And Yahan Par Tu Two Hai Karo Yahan Par Two Songs And Yahan Par Tu Two Hai Then Let's See Let's Check The Speaker Now support me, I have Now support me, I have Now support me, I have stopped it here, nothing has been done, then I am stopped it here, nothing has been done, then I am seeing the answer key, if it is okay soon, then now I feel like let's go to the court, let's take it But I have But I have But I have not done it wrong, let's break it down here, now I am not only not confirmed, how is everything coming, so I just check to submit, what is the complaint, okay, ok, speed code no, it is good, Hero Scooter will go over Hero Scooter will go over Hero Scooter will go over and if you like it then do whatever you want, I will and if you like it then do whatever you want, I will say like, share and subscribe, you will like it say like, share and subscribe, you will like it better, ok thank you too.
2024-03-21 13:51:08
165
https://i.ytimg.com/vi/C…axresdefault.jpg
Compare Version Numbers | LeetCode 165| Java
sta2-XpNNa4
in this tutorial I am going to discuss a very interesting problem insert delete very interesting problem insert delete get random in oven so in this problem we get random in oven so in this problem we have to design a data structure that have to design a data structure that supports all the following operation in supports all the following operation in average oven time and the operations are average oven time and the operations are insert remove and get random so when insert remove and get random so when this method is called insert we have to this method is called insert we have to insert an item value to the set if it is insert an item value to the set if it is not present when this method remove is not present when this method remove is called we have to remove an item from called we have to remove an item from this set if it is present and when get this set if it is present and when get random is called it returns a random random is called it returns a random element from current set of element and element from current set of element and each element must have the same each element must have the same probability of being returned so let's probability of being returned so let's understand this problem statement understand this problem statement through an example so in this example so through an example so in this example so imagine all these three methods are imagine all these three methods are implemented in this class randomized set implemented in this class randomized set and to access these method we have to and to access these method we have to first create an object so we first first create an object so we first created an object of this class and then created an object of this class and then we can call this these method in any we can call this these method in any order so in this example here a set of order so in this example here a set of instructions are given and let's instructions are given and let's understand them so first when this understand them so first when this method is called with an argument 1 so method is called with an argument 1 so it insert 1 as it is not present then it insert 1 as it is not present then this remove method is called and again I this remove method is called and again I am reiterating so the method can be am reiterating so the method can be called in any order it is just for an called in any order it is just for an explanation purpose and when remove explanation purpose and when remove method is called with argument 2 so 2 is method is called with argument 2 so 2 is not present so what it does it it does not present so what it does it it does not do anything and it return false that not do anything and it return false that this is not a valid operation and in this is not a valid operation and in this case we return true as we have this case we return true as we have inserted a 1 successfully then this inserted a 1 successfully then this operation insert 2 so 2 is not present operation insert 2 so 2 is not present so let's insert them and return true so let's insert them and return true which indicates that this operation is which indicates that this operation is successfully done then when gate rendom successfully done then when gate rendom is called so we can return any of the is called so we can return any of the element either 1 or 2 so I mean each element either 1 or 2 so I mean each element must have the same probability element must have the same probability so if 1 is returned then immediately if so if 1 is returned then immediately if we call get random we call get random it will return - I mean in so basically it will return - I mean in so basically we don't have any weight edge on any we don't have any weight edge on any element it can be all the element have element it can be all the element have the same probability of being returned the same probability of being returned so get random should return either one so get random should return either one or two randomly then we call this method or two randomly then we call this method remove with an argument one so one is remove with an argument one so one is they are so we removed them and we they are so we removed them and we return true would never true that this return true would never true that this operation is successfully done then the operation is successfully done then the next call is to insert two and two is next call is to insert two and two is already there so we don't have to insert already there so we don't have to insert this element we simply return false and this element we simply return false and then get random is called then get random is called only one element is there so we return only one element is there so we return in this element so this is the problem in this element so this is the problem statement and now let's think which data statement and now let's think which data structure we choose so that we can structure we choose so that we can perform all the all these operation in a perform all the all these operation in a one-time complexity in this problem we one-time complexity in this problem we have to implement insert remove get have to implement insert remove get random in constant time so let's first random in constant time so let's first discuss which data structure should be discuss which data structure should be used to solve this problem in constant used to solve this problem in constant time then we will discuss its code so time then we will discuss its code so the first data structure which comes in the first data structure which comes in our mind is can we solve this problem by our mind is can we solve this problem by using hash map or hash set using hash using hash map or hash set using hash map and hash set we can implement insert map and hash set we can implement insert and remove operation in constant time and remove operation in constant time but what about get random so to but what about get random so to implement get random we have to choose implement get random we have to choose random index and return the element random index and return the element present at that index but hash map and present at that index but hash map and hash set does not have the concept of hash set does not have the concept of indexes so we can't implement get random indexes so we can't implement get random in constant time by using hash map and in constant time by using hash map and hash set so let's move to another data hash set so let's move to another data structure so what about ArrayList if we structure so what about ArrayList if we use ArrayList can we do all the use ArrayList can we do all the operation in oh one so by using error operation in oh one so by using error list we can implement insert and get list we can implement insert and get random in oh one error list is a dynamic random in oh one error list is a dynamic size array so what we can do is whenever size array so what we can do is whenever this insert method is called so we can a this insert method is called so we can a we can insert an element at the end of we can insert an element at the end of this array list so first one is inserted this array list so first one is inserted then two then three in this way we can then two then three in this way we can do the insert operation do the insert operation oh one and whenever this great random oh one and whenever this great random method is called we can choose random method is called we can choose random index from the available indexes and index from the available indexes and return the element present at that index return the element present at that index so in this way these two operation will so in this way these two operation will be done in oh one but what about remove be done in oh one but what about remove methods removing an element from an methods removing an element from an array list takes o n time complexity so array list takes o n time complexity so we can't use array list as well so what we can't use array list as well so what about if we use these two data structure about if we use these two data structure together to solve this problem in oh one together to solve this problem in oh one so the idea here is to insert each so the idea here is to insert each element in an array list and in hashmap element in an array list and in hashmap we put each element and its index and we put each element and its index and element index is the index which is element index is the index which is present in ArrayList and using this present in ArrayList and using this strategy we can implement all these strategy we can implement all these three operations in oh one so let's three operations in oh one so let's discuss one by one how we can implement discuss one by one how we can implement them in oh one and let's visualize it them in oh one and let's visualize it let's visualize how we can solve this let's visualize how we can solve this problem in oh one time complexity using problem in oh one time complexity using hash map and ArrayList so what we can do hash map and ArrayList so what we can do is we can visualize this approach by is we can visualize this approach by taking following instructions so where I taking following instructions so where I represent insert R represent remove and represent insert R represent remove and ga represent get random method call and ga represent get random method call and in each method call let's see how we can in each method call let's see how we can do the operations in oh one time do the operations in oh one time complexity so now this thing is clear complexity so now this thing is clear that whenever we create an object of that whenever we create an object of this class the constructor is called and this class the constructor is called and we create an object of hash map we create an object of hash map ArrayList and this random random class ArrayList and this random random class so in map we store we keep T and value so in map we store we keep T and value pair of n type in list we store list of pair of n type in list we store list of integers and this random at this random integers and this random at this random class is used to get the random value class is used to get the random value between zero to array length minus 1 so between zero to array length minus 1 so now when this insert operations this now when this insert operations this insert method is called with the insert method is called with the argument 1 so first thing we check is argument 1 so first thing we check is if this element this one is present in a if this element this one is present in a map if it is then we have to return map if it is then we have to return false I mean we have if if this element false I mean we have if if this element is already present we don't need to is already present we don't need to insert them else what we have to do is insert them else what we have to do is let's put them in a map so we put them let's put them in a map so we put them at 0th index and then we put put them in at 0th index and then we put put them in a map so we first put them in an a map so we first put them in an ArrayList and is it it it is at 0th ArrayList and is it it it is at 0th index and then we put them in a map with index and then we put them in a map with with the value with this element and with the value with this element and this index so index is 0 and then we this index so index is 0 and then we return true so now that the next return true so now that the next operation is remove - so first we check operation is remove - so first we check is - is present so is - is already is - is present so is - is already present then we can able to remove it present then we can able to remove it else simply return false so when we else simply return false so when we check is - is present in a map no so we check is - is present in a map no so we return false so now you can see this I return false so now you can see this I mean this lookup is constant this mean this lookup is constant this addition so adding an element in an addition so adding an element in an array list is also constant and this put array list is also constant and this put operations is also in constant time operations is also in constant time similarly when we are going to remove an similarly when we are going to remove an element we first check them in a map so element we first check them in a map so it is not present in a map so it's a it is not present in a map so it's a constant operation so we simply return constant operation so we simply return false then the next operation then the false then the next operation then the next method call is insert with the next method call is insert with the value 2 so again we check so it is not value 2 so again we check so it is not present in a map and we first inserted present in a map and we first inserted them in a ArrayList so it's index value them in a ArrayList so it's index value is 1 then we inserted them in a map with is 1 then we inserted them in a map with this index value now the next method this index value now the next method called as get random so now we have to called as get random so now we have to randomly pick any index and return the randomly pick any index and return the element present in this present at this element present in this present at this index so we can get any index out of 0 & index so we can get any index out of 0 & 1 so let's suppose we get index 1 so we 1 so let's suppose we get index 1 so we return to and I will show you the code return to and I will show you the code of get random method shortly so now of get random method shortly so now let's move to next operation so the next let's move to next operation so the next operation next operation next Halas remove with the value one so again Halas remove with the value one so again we check is this element present in a we check is this element present in a map yes so this condition is escaped map yes so this condition is escaped then what we so we are using a very then what we so we are using a very clever technique here so that removing clever technique here so that removing an element from ArrayList is also an element from ArrayList is also constant so what we are doing is we are constant so what we are doing is we are first getting the index of this element first getting the index of this element from a hashmap so we get its index which from a hashmap so we get its index which is 0 then we are getting the last is 0 then we are getting the last element from the array list and why we element from the array list and why we are getting it you understand shortly so are getting it you understand shortly so we are and getting it so we get 2 and we are and getting it so we get 2 and then at this index so we have to remove then at this index so we have to remove this index the element present at 0th this index the element present at 0th index so we'll put 2 here so we put this index so we'll put 2 here so we put this 2 at this index and this to remain as it 2 at this index and this to remain as it is and then we update its index value in is and then we update its index value in the hashmap the hashmap as well and then we remove this entry so as well and then we remove this entry so this value as we have to remove 1 and this value as we have to remove 1 and also we remove the last element from the also we remove the last element from the array list so in this way removing an array list so in this way removing an array list removing an element from an array list removing an element from an array list is in constant time is in O 1 array list is in constant time is in O 1 if we remove the element from from let if we remove the element from from let us say from from this index from 0th us say from from this index from 0th index then we need to shift the element index then we need to shift the element one step otherwise this space remains one step otherwise this space remains empty so it's a I mean a dynamic array empty so it's a I mean a dynamic array so it will fix this size and in this in so it will fix this size and in this in in this operation it will take time so in this operation it will take time so that's why we have used this clever that's why we have used this clever technique and now this entry is removed technique and now this entry is removed this entry is remove so one is removed this entry is remove so one is removed from both the array list and hashmap so from both the array list and hashmap so now the next operation so keeping the now the next operation so keeping the indexes in hashmap has the advantage so indexes in hashmap has the advantage so when we get one in constant time we know when we get one in constant time we know that this element is present at this that this element is present at this index we simply go there we do the index we simply go there we do the following operations that we take the following operations that we take the last element from the error list we put last element from the error list we put at that index and then we remove the at that index and then we remove the last element now let's move to the next last element now let's move to the next operation so the next operation is operation so the next operation is insert two so this time two is already insert two so this time two is already present in a map so simply return false present in a map so simply return false we don't need to add them and then the we don't need to add them and then the next operation is get random so when get next operation is get random so when get random is called only one element is random is called only one element is there so the array size ArrayList size there so the array size ArrayList size is 1 so we get and a number 0 between 0 is 1 so we get and a number 0 between 0 and less than 1 so we get only 0 so we and less than 1 so we get only 0 so we return this 2 so we randomly returns two return this 2 so we randomly returns two so now you can see we can achieve all so now you can see we can achieve all these three operations we have done all these three operations we have done all these three operations in constant time these three operations in constant time in one time so this is the logic behind in one time so this is the logic behind this approach and now let's see the get this approach and now let's see the get random method as well so if you see here random method as well so if you see here is the get random method where we are is the get random method where we are calling we are asking to give me the calling we are asking to give me the random number between zero to list dot random number between zero to list dot size so this list dot size is not size so this list dot size is not included it means when we pass the size included it means when we pass the size let's say the size is 5 so it will give let's say the size is 5 so it will give you the random number between 0 to 4 so you the random number between 0 to 4 so in this way all the these 3 operation in this way all the these 3 operation insert/remove and gINT random isn't a insert/remove and gINT random isn't a one-time complexity so that's it for one-time complexity so that's it for this video tutorial and if you know any this video tutorial and if you know any other approach to solve this problem you other approach to solve this problem you can let us know through your comment so can let us know through your comment so that anybody who is watching this video that anybody who is watching this video get the benefit from the approach you get the benefit from the approach you mentioned in the comment section so mentioned in the comment section so that's it for this video tutorial for that's it for this video tutorial for more such programming videos you can more such programming videos you can subscribe our YouTube channel you can subscribe our YouTube channel you can visit our website which is HTTP colon visit our website which is HTTP colon slash - slash - thanks for watching this video
2024-03-24 11:49:44
380
https://i.ytimg.com/vi_w…xresdefault.webp
Insert Delete GetRandom O(1) | LeetCode 380 | Programming Tutorials
4wl-sgd1pQc
Hello everyone welcome back tu disrespect video and in this video we will solve sorting sentence in this video we will solve sorting sentence which is the fourth problem of the string. which is the fourth problem of the string. If you want to see the complete series then If you want to see the complete series then I will put the link of the playlist I will put the link of the playlist in the description box and will in the description box and will also give you the link of every question. You will get the link of the question of lead code in the description box, so let us understand this problem You will get the link of the question of lead code in the description box, so let us understand this problem directly from the example, directly from the example, so let's take this example and take it to the dashboard, I will paste it, then see friends, If you get the output in this sentence, If you get the output in this sentence, and it is written that one and three are written, it should come in the second position, so in the second position, so here I write the sentence and where it should come, if it should come in the first position, I am in this I am in this I am in this and what is required at the third position, so this should be our output, so it here and break it, on the it here and break it, on the basis of whose space, there is space here, so basis of whose space, there is space here, so we can split, and by splitting, we we can split, and by splitting, we What will people do What will people do next? sentence and then there will be and here we will make indexing zero one two three MP in which we will 01 first of all we will read. first of all we will read. first of all we will read. minize it then we will make it 2 - 1, hence we will do minize it then we will make it 2 - 1, hence we will do go to 1 - 101 index, then 2 will come, then we will keep it on the second index and again basically we will We will do this because what we have to return We will do this because what we have to return We will do this because what we have to return is to string is to string and after converting it into word then we will and after converting it into word then we will return date wood b d approach return date wood b d approach so we code this approach so so we code this approach so let's go to d lead code platform so first of all let's go to d lead code platform so first of all we will string we will string we will string in which we will split the word and then let's say level is equal to s dot split, this is an inbuilt function and on the basis of which we will split it, on the basis of space, we will split this sentence, Hey, we will take another one Hey, we will take another one Hey, we will take another one in which we will in which we will keep our output which we keep our output which we want to return to the original, so here we will pass it in correct, so pass it in correct, so first of all, what we do is find out its length and basically we and basically we will try to read the last character, right if if if index because zero based indexing was done. If we try to read the force index, then we are reading the N - 1 last character which N - 1 last character which will be our digital and it was will be our digital and it was clearly mentioned in the digital that the numbering will be done. clearly mentioned in the digital that the numbering will be done. 129 It may be that we are not getting a number greater than 9, so why would we read the last character only? Okay, if there was a number greater than nine, 10 11 12, then our approach changes a bit. It is okay We will do this by doing We will do this by doing We will do this by doing only 48 mines or we only 48 mines or we can also do zero mines like this, you took us out, you did the mines van and here we are keeping it, so only the string from here till here come here. only the string from here till here come here. only the string from here till here come here. keep it, then how are we doing this thing? We will start from T dot substring and zero and till where we will go till N - 1. Okay [Music] So take a stringbuilder, all are equal, you will create a and read each string We will read because then keep only the word in it and keep the space, because then keep only the word in it and keep the space, otherwise we will paint on this page and return and trim it and what will happen in the last word too, a space will be added and let's run and see. will be added and let's run and see. will be added and let's run and see. Friends, see you in the next video. Friends, see you in the next video.
2024-03-25 11:15:13
1,859
https://i.ytimg.com/vi/4…axresdefault.jpg
1859. Sorting the Sentence || Java || Easy explanation || Hindi
QcR2HiMrypg
hey everyone welcome back and today we'll be doing another lead code problem we'll be doing another lead code problem 717 one bit at 2-bit character this is 717 one bit at 2-bit character this is an easy one you have two special an easy one you have two special characters the first character can be characters the first character can be represented by one bit zero the second represented by one bit zero the second can character can be represented by two can character can be represented by two bits then or eleven uh one zero or one bits then or eleven uh one zero or one one this is not 10 and 11 given a binary one this is not 10 and 11 given a binary array bits and array bits and that ends with 0 return true if the last that ends with 0 return true if the last character must be a one bit character so character must be a one bit character so zero is the one bit character basically zero is the one bit character basically they are saying if there is a zero at they are saying if there is a zero at the very end the very end Standalone so here if we have this Standalone so here if we have this example we are going to return true example we are going to return true because this is our two bit character because this is our two bit character this 0 and this this one and this 0 and this 0 and this this one and this 0 and then 0 at the very last is going to be a then 0 at the very last is going to be a single you can say a one bit character single you can say a one bit character so we'll be returning true in this case so we'll be returning true in this case in this case we are not going to return in this case we are not going to return true because this is a 2-bit character true because this is a 2-bit character and this is also 1 and 0 is also R2 bit and this is also 1 and 0 is also R2 bit character character so that's it so that's it so we will be starting our index from 0 so we will be starting our index from 0 n will be our length of nums n will be our length of nums and and number of bits you can say number of bits you can say we will be having as a counter we will be having as a counter so while our I is less than nums so while our I is less than nums and and if if dates at I is equal to 1 then we know dates at I is equal to 1 then we know that we are going to have one is just that we are going to have one is just basically not a zero bit a one bit basically not a zero bit a one bit character so we'll be incrementing I by character so we'll be incrementing I by 2 because we we whenever we reach one or you can say in counter one we are going to have a two bit so that's why we are going I plus 2 and nums will be all also num bits will also be incremented by two so that's it and now in the else case we can see that if we have a 0 we are just going to increment our index by nums is not going to be incremented nums nums is not going to be incremented nums is going to be 2 because obviously we is going to be 2 because obviously we are not not to do increment at each are not not to do increment at each point and num bits will be one if you point and num bits will be one if you encounter a zero so if we encounter a encounter a zero so if we encounter a zero at the very end then obviously num zero at the very end then obviously num bits is going to be one and then we can bits is going to be one and then we can just return if num just return if num states are equal to 1 so that was it oh okay so it was our bits array I that's it
2024-03-21 10:40:38
717
https://i.ytimg.com/vi/Q…pg/sddefault.jpg
717. 1-bit and 2-bit Characters | Leetcode | Python
1QlP6cVLrII
hi guys this is khushboo welcome to algorithms made easy algorithms made easy in this video we will see the question in this video we will see the question global and local inversions global and local inversions we have some permutation of a that we have some permutation of a that consists of numbers 0 to n consists of numbers 0 to n minus 1 where n is the length of a minus 1 where n is the length of a number of global inversions is number of number of global inversions is number of eyes eyes less than j wherein 0 is less than i less than j wherein 0 is less than i less than j which is less than n and for less than j which is less than n and for that that my a of i should be greater than a of j my a of i should be greater than a of j that is in the descending order now that is in the descending order now the number of local inversions is the the number of local inversions is the number of number of eyes wherein my a of i eyes wherein my a of i is greater than a of i plus 1. is greater than a of i plus 1. so this is locally comparing a of i with so this is locally comparing a of i with just its next value but in global you just its next value but in global you can have comparisons with any value can have comparisons with any value that satisfies i less than j condition that satisfies i less than j condition and wherein this a of i is greater than and wherein this a of i is greater than a of j a of j we need to return true if and only if we need to return true if and only if the number of global inversions is equal the number of global inversions is equal to the number of to the number of local inversions for the example one local inversions for the example one the output is true whereas for example the output is true whereas for example two the output is false two the output is false now how we are getting this output will now how we are getting this output will see with the help of an example see with the help of an example so don't worry as this might sound a so don't worry as this might sound a little bit tricky to you little bit tricky to you while reading out but when you visualize while reading out but when you visualize this this would this this would become very simpler so let's go and see become very simpler so let's go and see how we can how we can solve this question with an example solve this question with an example let's first take this particular example let's first take this particular example and as per the definition given to us and as per the definition given to us for the global inversion for the global inversion it means that these are the number of it means that these are the number of inversions inversions with a of i greater than a of j where with a of i greater than a of j where i is less than j so if you consider 3 i is less than j so if you consider 3 you can have 3 inversions these are you can have 3 inversions these are global inversions because 3 global inversions because 3 is greater than 2 3 is even greater than is greater than 2 3 is even greater than 1 1 and 3 is even greater than 0 these are and 3 is even greater than 0 these are the indexes the indexes and these are the numbers now if you and these are the numbers now if you consider 2 consider 2 you will get 2 inversions for that these you will get 2 inversions for that these are also global inversions are also global inversions and if you take one you will get one and if you take one you will get one global inversions so in total global inversions so in total you will have six global inversions for you will have six global inversions for this particular example this particular example now let's go ahead and see what is local now let's go ahead and see what is local inversions inversions so local inversion would be just for so local inversion would be just for your local your local pairs that is for in i plus 1 pair pairs that is for in i plus 1 pair so over here your local inversions are so over here your local inversions are the ones the ones marked with this white because 3 is marked with this white because 3 is greater than 2 greater than 2 then this 2 is greater than 1 and this 1 then this 2 is greater than 1 and this 1 is also greater than 0 so these are my is also greater than 0 so these are my local inversions which are 3 so if you local inversions which are 3 so if you see over here see over here my local inversions are 3 but my global my local inversions are 3 but my global inversions are inversions are 6 which is not the case that i want and 6 which is not the case that i want and so so the answer for this particular example the answer for this particular example would have been false would have been false so now what are the things that we can so now what are the things that we can find out find out by using the properties the hint given by using the properties the hint given in the question in the question says that find out where you can place says that find out where you can place zero zero so this would help us solve the question so this would help us solve the question further further so now let's see if we take a ascending so now let's see if we take a ascending order number order number that is 0 1 to 3 we can say that there that is 0 1 to 3 we can say that there are no inversions because are no inversions because we don't get a place where in my a of i we don't get a place where in my a of i is greater than a of j is greater than a of j in the second case if i just swap in the second case if i just swap these numbers against themselves then these numbers against themselves then i'll get two local inversions i'll get two local inversions and two global inversions because 1 is and two global inversions because 1 is greater than 0 greater than 0 and 3 is greater than 2 neither this one and 3 is greater than 2 neither this one is greater than any of these is greater than any of these others and neither is this 3 greater others and neither is this 3 greater than any of than any of the other because there is nothing left the other because there is nothing left so over here also we can say that so over here also we can say that the local and global inversions are the local and global inversions are equal so the answer is true so equal so the answer is true so you can have these three cases wherein you can have these three cases wherein you have an ascending order you have an ascending order no inversions wherein you can have a no inversions wherein you can have a swap of these numbers swap of these numbers and you can have equal number of local and you can have equal number of local and global inversions or you can have a and global inversions or you can have a mix of both so let's find out where my mix of both so let's find out where my zero can be placed zero can be placed my zero can either be placed at the my zero can either be placed at the zeroth index zeroth index or first index if it is placed any or first index if it is placed any further i'll get further i'll get more number of global inversions than my more number of global inversions than my local inversions local inversions as we have seen in this particular as we have seen in this particular example so i can say example so i can say 0 can only be there at 0th or 0 can only be there at 0th or 1st position as you can see in all these 1st position as you can see in all these 3 examples 3 examples which would yield true now what about which would yield true now what about the other numbers the other numbers other numbers can be either placed at other numbers can be either placed at the ith position that is for ascending the ith position that is for ascending order wherein you will have no order wherein you will have no inversions inversions or in the swap case it can be at i minus or in the swap case it can be at i minus 1 1 for example so this 1 is at i minus 1 for example so this 1 is at i minus 1 that is 0th that is 0th index and i plus 1 that is the 0 index and i plus 1 that is the 0 comes to the first index so it is i plus comes to the first index so it is i plus 1 1 so that's the trick over here i can only so that's the trick over here i can only have the elements or the numbers at have the elements or the numbers at i i minus 1 or i plus 1 index i i minus 1 or i plus 1 index and so this can also be stated as and so this can also be stated as the absolute difference between any the absolute difference between any index and the number would be always index and the number would be always less than 1 that is either 0 or plus 1 less than 1 that is either 0 or plus 1 and minus 1 and minus 1 which gives us 1 when we find its which gives us 1 when we find its absolute value absolute value so that's all for this question so let's so that's all for this question so let's go ahead and code it out go ahead and code it out so over here we'll iterate over all the so over here we'll iterate over all the numbers and we need the absolute difference between the index and the number and it should not go if it goes beyond one we can return if it goes beyond one we can return false otherwise false otherwise finally we can just return true so let's finally we can just return true so let's try to run this code try to run this code and it's giving a perfect result let's and it's giving a perfect result let's submit this submit this and it got submitted the time complexity and it got submitted the time complexity for this particular approach would be o for this particular approach would be o of n of n as we are going to go through all the as we are going to go through all the elements in my a elements in my a so that's it for today guys i hope you so that's it for today guys i hope you like the video and i'll see you in like the video and i'll see you in another one another one so till then keep learning keep coding
2024-03-21 16:20:11
775
https://i.ytimg.com/vi/1…axresdefault.jpg
Global and Local Inversions | Live Coding with Explanation | Leetcode - 775
eI6dBpol2A0
hello everyone welcome back to the swift academy in today's video we are going to solve another lit code issue that is so popular among the interviewers it's called twosome and also it categorized as an easy question but regarding that it is easy because simply you can find the answer for that it is so important how you communicate with your interviewer how you describe the things to your interviewer how you are going to solve this solution by the brute forcing solution then you are going to use another's approach then your third approach and you have to talk all the time with your interviewer about how you are thinking so please think loud and talk about how you are going to solve the problem even if the interviewer give you an easiest question it is going to find how your thought process is so bear with me i'm going to describe this question to you this is two sum it will give you an array of the norms and it is going to finding the target but what is the target there is only two number or integer inside that array that if you add them together the target value will be the things that the question asking for so for example in this question we are looking for the target nine and if you look at the noms the array you can find out okay at the index zero and at the index one two plus seven is equal to the 9. it means that we have to return just the index of those numbers that when you add them up together you will have the target okay the brute force approach that you are going to think about it is to iterate to roof the whole array inside a two loop and just seeing that if the value one adding to the next value is going to be our target or not but we know that when we are going to use two for loops inside together we are going to have the time complexity of o and s score which is not so good for example if you have a long list of the array and you have a bunch of numbers here if you are going to iterate for example one million numbers what will be happen in the case of the time complexity it's not going to be worth you a lot because always you have to design an algorithm that is so efficient so let me describe how we are going to solve this problem by using a little bit of the space in memory okay now take a look at this example we have an array uh consists of a bunch of numbers here and the question will be asking us about to find the two number or two digits that when you add them together you are going to have 14 so if you are going to using the first approach the brute force approach we ended up with the two for loops that which is not actually so efficient so we are now going to use another methodology that we always using that inside that this kind of the questions guess what we are going to use the hash maps uh you know that inside the hash maps when you are inserting something into it the time complexity is going to be o1 and then you are deriving data from that it is going to be one as well so inserting or asking about one value inside the hash maps the time complexity is one so by the help of the hashmaps we can actually solve this problem and it's ready to roof hold the list just one time but we sacrificing the space for that so the whole time complexity is going to be o n and it means that we can actually iterate to hold the least just one time it's about the time complexity but in case of the space a divorce case scenario we should sacrifice it the whole list and it will be on as well so the time complexity reduced to the on but we with the help of the space that we are using we are going to all end time complexity let me explain how we are going to use hash maps for solving this problem we are going to use just one for loop here and on each time that we are visiting one of those numbers or indexes first of all we are going to ask our hashmaps do you have the difference between those target and the index object that we are actually looking for for example when we are uh in the index 0 if this is our hash maps we have the key and we have the value if we are at the index 0 what will be the difference between them 14 minus 2 is going to be what is going to be 12. so we are going to ask hashmaps as you can see we already have 12 in our list but we are at the index 0 now so at the index 0 we still didn't see the 12 that existed so we are going to add 2 inside our hash maps and the value is going to be the index of the value so 2 is going to be in at the index of 0. then later on we are going to do the difference between the 14 and also uh to read the next index is gonna be 11 we are going to ask our hashmaps do you have any element at any index no then we are going to add it to our hash maps again so we are going to add the tree at the index one it should be go on until we see the index of one of those that we are actually trying to do at the end when we reach to the 12 we are calculating the difference between the target and the 12 there so 14 is gonna be minus 12 it's gonna be two first of all we are going to asking our hashmaps do you have any data inside our hash maps and yes we have the tutor so at the index of the zero then we are going to return back the index of the zero and also the index that we already visiting the index that you're already visiting is zero one two three four so the response will be zero four with this approach we will have the time complexity of o n by the sacrificing the space so let's jump to the code and show you how we are going to code it in swift language so now we are going to solve this problem in swift language as you can see inside the question description it is saying that there is exactly one solution for that so don't worry if they give you a number target that would be not add up so with that in mind we are going to solve this problem with the approach that i described by using the hashmap so first of all we are going to create our hashmap and our hashmaps is gonna beat two integers as the key and value and i define it as an empty hash maps now then we just need one for here because we are going to iterate once inside our numbers or our array so for i in 0 till our nums dot count then we are going to asking our hashmap if the value is already there or not do you have any index of that value so we need this current value let currentval equal to noms i and also in the difference here so let live equal to our target minus the current val that we are now there so currentval and now we have the different here it's time to asking our hashmap if you already have it or not so we can asking our hashmap by an if statement if let index equal to our hashmap it means that we have an index already there and else if it doesn't have anything then we are going to populate our hashmap with that data so with the current val that we already on it now and we equally to the i it means the index but when we have the data we can just simply return i because the i is the current index that we are on it and also the index that we get from the hashmap so the next one will be the index and if we get out of our loop and we didn't find anything we can just simply returning an empty alley so let me build up and see the result as you can see that this approach by using the hash maps and sacrificing a memory space here we are going to be more than 95 percent above other submissions for two sum now so always think about it to when you can sacrifice the space regarding the time complexity and always talk with your interviewer about such these situations be successful like this video and subscribe to this channel to see more content like this you
2024-03-18 09:37:14
1
https://i.ytimg.com/vi/e…axresdefault.jpg
Interview Question - Two sum - Leetcode 1
muiEShGc2hg
understand it is little bit not un difficult but little bit medium ok so d question is saying date given and wait and return true it is d power of adrevise return false like for example like This This This Exit N Wait Access Date Like N = 4 Exit N Wait Access Date Like N = 4 Power Power Of And d third condition is given And d third condition is given d = 1 so you want to return true ok I d = 1 so you want to return true ok I think you understand d concept what is d think you understand d concept what is d concept of d question so I am understand concept of d question so I am understand what is here how will what is here how will I solve this man lo end I solve this man lo end Equals you are 16, like okay, so when we Equals you are 16, like okay, so when we divide ours by four, like, then four becomes four, four goes, divide ours by four, like, then four becomes four, four goes, Drishti, okay, if we divide this, then is zero, is zero, okay, and the one above is our okay, and the one above is our divider. divider. divider. or so, now you have understood that the one below is the model and the one above is the divider, when again when we divide our four, then what comes from which four. Here comes all N = 1 so when you have to return true and this is the code list of your let's take, you will apply the condition here till my N is not equal to zero then my Okay, as I was just Okay, as I was just Okay, as I was just explaining here, look here, explaining here, look here, I had done that and like here four I had done that and like here four came, then four, our when n = apan, what will we do, end module. When it is not equal to zero, you have to understand, then what you have to do is return, return falls like, let me explain to you how, like here is 16. Okay, so see what I did first here, my is 16 here. I divided 16 by four like I wrote here 16 is ok I divided it here by four ok so ok so here also my right is present ok I will divide right then n equals you Look, if I did what I did here Look, if I did what I did here Look, if I did what I did here and modular four, that is, I and modular four, that is, I will divide four again here, I will divide four again here, I just did 4 here and just did 4 here and came here, understand that this thing will start to understand, if that van will not come, then if the So what will the return do? Our submission has also been done. Thank you so
2024-03-24 10:58:56
342
https://i.ytimg.com/vi/m…axresdefault.jpg
Power of Four | LeetCode 342 |
ZdTta7wPMco
it's a very basic level problem it's a topless Matrix you can say so we it's a topless Matrix you can say so we are given an M cruise and Matrix we have are given an M cruise and Matrix we have to return to if the Matrix is topless to return to if the Matrix is topless otherwise we'll return Force means otherwise we'll return Force means topless Matrix is topless Matrix is if if if uh these diagonals are same in this if uh these diagonals are same in this way way so if these diagonals are same so first so if these diagonals are same so first we have 9 we have 9 then we have 5 5 then we have 5 5 right so all the elements of each right so all the elements of each diagonal are same then we have one one diagonal are same then we have one one one then we have two two then one then we have two two then two to two we have 2 2 and 2 then we two to two we have 2 2 and 2 then we have three and three have three and three right then we have four right then we have four so just we have to compare their indexes so just we have to compare their indexes you can see here so let's say it's its you can see here so let's say it's its index is 0 0 so uh so let's say we are index is 0 0 so uh so let's say we are observing observing our this diagonal our this diagonal which is which which is containing only which is which which is containing only one one right so I'll compare so first its index right so I'll compare so first its index is 0 0 now we have to check this number is 0 0 now we have to check this number at which index it is it is at so one one at which index it is it is at so one one row is increasing and one column is row is increasing and one column is increasing means index is from 0 0 to 1 increasing means index is from 0 0 to 1 1. 1. again uh we have one one then we have again uh we have one one then we have two two two two right so just we have to compare the right so just we have to compare the values in this way so simply we'll run values in this way so simply we'll run our two national loops and we'll check our two national loops and we'll check if Matrix of i j is not equal to Matrix if Matrix of i j is not equal to Matrix of 5 plus 1 J plus one elements otherwise will return true so you can see here it's running so you can see here it's running so you can see here the solution is so you can see here the solution is accepted so that's it for this video accepted so that's it for this video it's it's nothing here to explain much it's it's nothing here to explain much right if you still haven't out you can right if you still haven't out you can ask in the comment box ask in the comment box otherwise it's an accepted solution otherwise it's an accepted solution right so you can connect with me my right so you can connect with me my LinkedIn and Twitter handles are given LinkedIn and Twitter handles are given in the description box so stay tuned for in the description box so stay tuned for more videos
2024-03-21 16:07:42
766
https://i.ytimg.com/vi/Z…axresdefault.jpg
766. Toeplitz Matrix✨ | Easiest Solution💥😃Problem of the Day #geeksforgeeks#leetcode
5lYoAtet31s
hey how's it going leak code 1846 maximum element after decreasing and maximum element after decreasing and rearranging you're given an array of rearranging you're given an array of positive integers ARR perform some positive integers ARR perform some operations possibly non on ARR so that operations possibly non on ARR so that it satisfies these conditions the value it satisfies these conditions the value of the first element in ARR must be of the first element in ARR must be one one aha uh the absolute difference between aha uh the absolute difference between any two adjacent elements must be less any two adjacent elements must be less than or equal to one in other words ABS than or equal to one in other words ABS a r I might I got a r I might I got it uh there are two types of operations it uh there are two types of operations that you can perform any number of times that you can perform any number of times decrease the value of any element of ARR decrease the value of any element of ARR to a smaller positive integer rearrange to a smaller positive integer rearrange the elements of ARR to be in any the elements of ARR to be in any order order okay it doesn't seem like duplicates are okay it doesn't seem like duplicates are going to benefit us in any going to benefit us in any way and okay there's no values less than zero and um we can never increase a value so the biggest value we could possibly have is the final value of the array so I think the first thing we're going to do is we're going to get rid of duplicates we're going to say ARR equals list of sorted of set of ARR and then while AR R of 0 is greater than one we're going to say ARR well no no we don't have to do that we don't have to do the uh the things one at a time okay that was dumb now it can only increase by one every time uh so let's say 4 I in range one to length of ARR and then if a r of I is greater than one more than the previous value then we are going to decrease it value and then we're just going to value and then we're just going to return the last element I guess gu it's supposed to be confusing cuz you're supposed to get confused with the organizing but seemed pretty straightforward to 210 you're right you are right I should not have eliminated the AR rr. AR rr. sort run whoopsie all right and there we
2024-03-25 10:26:13
1,846
https://i.ytimg.com/vi/5…axresdefault.jpg
Leetcode 1846 Maximum Element After Decreasing and Rearranging
qQKbr4WtGjc
Hello Hello everyone welcome back on the chain Anil Kapoor himself is going to discuss Anil Kapoor himself is going to discuss write there is a problem in finding the right element in July 4th write there is a problem in finding the right element in July 4th so what is the problem in so what is the problem in which my given input is fine which my given input is fine and tell us which is the APK element in it and tell us which is the APK element in it apk apk apk element and bigger than your side, so our element is our tax return, like if we see what are the PK limits in all, which can be one element, The element on the left The element on the left The element on the left i.e. Vansh increases and Chopra on the right, its forest i.e. Vansh increases and Chopra on the right, its forest is on top of it, okay, the second one can limit first, is on top of it, okay, the second one can limit first, this is this is because see why it is because see why it is bigger than there and only and only bigger, okay, so bigger than there and only and only bigger, okay, so we can return any of these pin elements. we can return any of these pin elements. Anyone can do it, basically we have to Anyone can do it, basically we have to return his tax in the output, then return his tax in the output, then you return one in the output or make it a favorite you return one in the output or make it a favorite in the question of some person in the question of some person that he has said that these were returned that he has said that these were returned on the word also money returning back to the one. on the word also money returning back to the one. on the word also money returning back to the one. ok hai hai aur chowki tibba post video and think simple kya way you can sleep ok element tunee p ke nimitt ok so see at the time of the simplest the first thing that will come to mind is what will we do we will age We will keep doing like here We will keep doing like here We will keep doing like here this is our we will check that this festival this is our we will check that this festival is increased by element and festival is is increased by element and festival is increased by both the big side then it is of scale increased by both the big side then it is of scale or and if we get the pick then we will just or and if we get the pick then we will just return its index i.e. simple return its index i.e. simple process of process of process of even worse, they have said in the portion that you must not write the algorithm in the login is logged in, now you have to keep it in the login time, okay, in the login time, one of yours is thinking of the leaves of Ghori It will be like It will be like how to put the final truth - in the appointed A, it seems that it will be soft, not some solution, there is a valuation of the research, why shot name can be kept as Babuni and its answer is this symbol of approaching the questions, then he can see what is the way. So we will find this question, we will fold it from this side, it is very easy, okay, so till now we do not know what water really is, okay - what is there in it, we take it, okay where to take it, in the beginning i.e. People have done it at the ends and then we only take it in chicken and we have taken it lightly, we have sex in the last, we have sex and then what do we do, we take out these mean streets, what do we do and we don't Till ilaj balance Till ilaj balance Till ilaj balance he is equal to high till then he is equal to high till then we will work and what do we do we we will work and what do we do we take out a yo take out a yo yo honey low plus hai bay tu this is what you do - yo honey low plus hai bay tu this is what you do - da da ok ok so this is what we do here also ok ok so this is what we do here also what did we take out what did we take out what did we take out locals are in more plus 6 of Sector-22, I am dead, it is free, that is, 3D is lying here, okay, so we will check the first one, it is lying on whatever media, if on the - If you - If you - If you increase this by increase this by hello hello and whoever is lying on our minute, hello hello and whoever is lying on our minute, if he has vada in his right investment if he has vada in his right investment i.e. middle and end explanation, then this fight has gone to all of the wheat, no, I am someone, this will be my condition, Got the pick, give it to Middleton Got the pick, give it to Middleton Got the pick, give it to Middleton because there are meds and injections which because there are meds and injections which I have measured here for Marawi. I have measured here for Marawi. Look here, the one which is free is Look here, the one which is free is bigger than there, this condition is the right answer bigger than there, this condition is the right answer but this condition continues. but this condition continues. but this condition continues. big from five, now we have to think that if this condition comes then we will either have to go left or right, then what do we do with our best rating like N Yadav goes left, then either we will apologize. I think for myself that how do they happen and where do you know, we were satisfied with the triptych pre-primary international that we were satisfied with the fact that our brother is the right one, the 5.5 is small on this side because from small here to 5.5 is small on this side because from small here to here. here. here. smaller than C, then there is an advantage of making it left or right because it is bigger in the five worlds, so if you think that if there is such a condition of five elements, then it matches. Done, you will increase the edifice, the file can be right to left or there is a change in the new system, there is a possibility here, so what do I mean to say, if this condition of ours is not true then we go to the press and do the computer, Is that a comment Is that a comment that if then our meat is our dip which is that if then our meat is our dip which is ours this one if this is the dead ours this one if this is the dead media element it is smaller than our right one media element it is smaller than our right one whatever type hey whatever type hey wait here lying on the side it is smaller media freedom wait here lying on the side it is smaller media freedom fighter fighter fighter that mid plus time is that mid plus time is good, otherwise if this Kshatriya, if there is good, otherwise if this Kshatriya, if there is someone bigger than this here at the halt, but you guys, then someone bigger than this here at the halt, but you guys, then it is like this, it is like this, then we will go to the exam, we will then we will go to the exam, we will request oo made. request oo made. so this is our algorithm, once according to this, so this is our algorithm, once according to this, we look at the triangle, then let's see what will happen according to this, see, first of all, our media was what will happen according to this, see, first of all, our media was that now whatever the husband is, that is the PK limit because that now whatever the husband is, that is the PK limit because 310 is on the big side. 310 is on the big side. 310 is on the big side. not increase from the five, okay, so what we will do is that we will go to the brightness, this is our palazzo's meat plus one i.e. for and high, which is like that, there is so our media will go here with the so our media will go here with the help of trust by the media. help of trust by the media. help of trust by the media. class six bittu panch i.e. liquid liner dekh hoge toh six hai he apni 578 and a signup land rights violation in order for the word you hai to this one drinks i.e. yes this one let's find and return our next condition room So this is how it will work okay let's So this is how it will work okay let's So this is how it will work okay let's see a little one which would have been done better that now like we only tested 1421 that now like we only tested 1421 okay so this okay so this was just a heroine of funds so mixed in it first was just a heroine of funds so mixed in it first take our 102 take our 102 okay and okay and okay and then Media Advisor Plus One by Two i.e. live chicken, know any more of its electronic here, it will appear here that if our and zero are not there then fruits right and take will compare it Plus just add water and then compare. Now Plus just add water and then compare. Now Plus just add water and then compare. Now see what is there and what I want to do. If the see what is there and what I want to do. If the knowledgeable lineage of light knowledgeable lineage of light increases, then this is our back element. Okay, so increases, then this is our back element. Okay, so now what will we do, let's now what will we do, let's measure it. Okay, so this is indicated. In which our made tow came, it was found to be Vidro, okay, we can do quarters like we took 1234, okay, so induction is required in this, if there will be car loans in minutes, then what will be the free of zero, That is, the time vagina That is, the time vagina That is, the time vagina is now J2, it is greater than, so I have is now J2, it is greater than, so I have seen this left curd, if it is seen this left curd, if it is not greater than three, then it cannot be thick and not greater than three, then it cannot be thick and because it is more dear butt, then okay, because it is more dear butt, then okay, this top will go in this direction, this top will go in this direction, go to the office, ours will go. go to the office, ours will go. go to the office, ours will go. one plus one two one plus one two and that's what he has come to meet you that now ours will be found tubeless cb2 i.e. Chotu i.e. hit is now that now see is it okay reminder Sorry to you, this frilled one is Sorry to you, this frilled one is Sorry to you, this frilled one is bigger but he is not bigger than the playwright one, that is, I cannot be a teacher and that is, I cannot be a teacher and because the right one is big, then I too will because the right one is big, then I too will give the right one a piece, then what will we do with the give the right one a piece, then what will we do with the people, then what will change for us, Mithila. people, then what will change for us, Mithila. Health Neetu Prashant three and also Health Neetu Prashant three and also our Shri will be found here C2 our Shri will be found here C2 Yo Yo Honey 3 Yo Yo Honey 3 So now our media look at this I am scared So now our media look at this I am scared mine is this mine is this i.e. now look carefully Mirchi Maya and i.e. now look carefully Mirchi Maya and this is our last and this one this is our last and this one so here so here so here but if there is any element on the machine right then this condition then look at the adjective here on the emplacement because we ourselves are the last untouched okay where the last we are just only to be looted so we answer sheet okay okay This is such a thing that the chicken might have been This is such a thing that the chicken might have been This is such a thing that the chicken might have been considered ineligible. Now considered ineligible. Now basically, let's basically, let's discuss it once again quickly. The rhythm value is discuss it once again quickly. The rhythm value is something like this that by taking non, the something like this that by taking non, the elastic of the zoom will be elastic of the zoom will be 11 - Suppose if the end size is of the face. 11 - Suppose if the end size is of the face. A fuel will be used there till the nose Who lives A fuel will be used there till the nose Who lives in is equal to high, in is equal to high, we will take it out, we will check the plus Highway-22, we will take it out, we will check the plus Highway-22, now what to check here, check the fuel now what to check here, check the fuel carefully, if you have to drown, if carefully, if you have to drown, if your media comes, it means this one which your media comes, it means this one which we have we have no limit on your left on your left, this is just what you will no limit on your left on your left, this is just what you will do here, if you are going to increase it with the ride element, then I am your answer, I need to close the gate, otherwise it is I am your answer, I need to close the gate, otherwise it is not so, then you not so, then you not so, then you n't impose empress on people, ok, why will the truth go here for humans, we have the option, if Google app goes to the right, then it is nothing, if MS Word is not defeated, then this rupee is history, otherwise in Alif Alif, or if Yours and last induction which we saw in this one, look at this, your last index is on mother's name last next, so here only you have on the left side, I have given that what will you do only with this and which is Element on the fort, a Element on the fort, a Element on the fort, a little - minute, if she has a big little - minute, if she has a big meaning, family, your speak index, Rafiq meaning, family, your speak index, Rafiq element, conducting a written, ours, element, conducting a written, ours, otherwise, what is the option, now she will ask on the right, then otherwise, what is the option, now she will ask on the right, then one option, go to the left, then you one option, go to the left, then you will like, minus point, okay, will like, minus point, okay, no. no. no. in this we have set this which was for minutes, this one will check this one is bigger than these two and his lips, then he looks at that side, if you understand your fruit, how is this one, then It is very simple, It is very simple, It is very simple, what to do first of all, we will take a size and what to do first of all, we will take a size and variable in it, it makes the size variable in it, it makes the size that if this is Mukesh, it is one, if you understand, you have that if this is Mukesh, it is one, if you understand, you have only one limit, only yours, then only one limit, only yours, then yours, then what will you do, if it yours, then what will you do, if it is not, then people will play that. is not, then people will play that. is not, then people will play that. out the day, if it is of chilli, then if the video comes, it means there is an element on the left only on the front, then compare it with the light one, if it is bigger then I am fine with yours, injection of papaya element because there is an option to Two are fine, similar exams Two are fine, similar exams Two are fine, similar exams will come midway - that is only in your life you will come midway - that is only in your life you will eliminate someone on less than will eliminate someone on less than fence safe and if it has increased by minutes from the left one then it is fence safe and if it has increased by minutes from the left one then it is okay by the media, if not the injection of limit okay by the media, if not the injection of limit then it is Haiku - 134 then it is Haiku - 134 and what will you do in the last and what will you do in the last and what will you do in the last friend, if the midwinter fall in these is increased from both left element and right then it is Marathi, otherwise Johnson is a big limit, go towards that side, if my plus demand is this diet Will do the Will do the Will do the right and minimum, okay, let's right and minimum, okay, let's submit it, it is accepted, and the description of the pattern has been taken in the description, there is same to same logic, there is nothing new, nothing is different and login is the login time, okay in this way. vitamins will be applied and the vitamins will be applied and the vitamins will be applied. Please like and subscribe the vitamins will be applied. Please like and subscribe the channel and till the next video minutes.
2024-03-21 13:47:03
162
https://i.ytimg.com/vi/q…axresdefault.jpg
Find Peak Element 🔥🔥| Leetcode 162 | C++ | Python | Medium | Approach + Code
vMVweyz7pOk
invalid tweets tweets ID is the primary key for this table this table contains key for this table this table contains all the Tweets in a social media app all the Tweets in a social media app write a solution to find the IDS of the write a solution to find the IDS of the invalid tweets the twit is invalid if invalid tweets the twit is invalid if the number of characters used in the the number of characters used in the content of the twit is strictly greater content of the twit is strictly greater than than 15 return the result table in any order so you select from where the where the length of the 15 and we we we turning any
2024-03-20 12:10:55
1,683
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode SQL 1683. Invalid Tweets
gU8raekRs1E
[Applause] hello and welcome today we're doing a hello and welcome today we're doing a question from Li code called keys and question from Li code called keys and runes it's a medium let's get started runes it's a medium let's get started there are n rooms and you'd start in there are n rooms and you'd start in room 0 each room has a distinct number room 0 each room has a distinct number in 0 1 2 all the way to n minus 1 and in 0 1 2 all the way to n minus 1 and each room may have some keys to access each room may have some keys to access the next room formally each room has a the next room formally each room has a list of keys rooms I and each key rooms list of keys rooms I and each key rooms IJ is an integer in 0 to n minus 1 where IJ is an integer in 0 to n minus 1 where n is the length of rooms any key rooms n is the length of rooms any key rooms IJ equals V opens the room with number B IJ equals V opens the room with number B initially all the rooms start locked initially all the rooms start locked except for room 0 you can walk back and except for room 0 you can walk back and forth between rooms freely returned true forth between rooms freely returned true if and only if you can enter every route if and only if you can enter every route example 1 we have room 0 1 2 3 we output example 1 we have room 0 1 2 3 we output true because we can start in room 0 pick true because we can start in room 0 pick key 1 and then go to room 1 so we go to key 1 and then go to room 1 so we go to room 1 and pick up the key to go to room room 1 and pick up the key to go to room 2 at room 2 we see we have a list of 2 at room 2 we see we have a list of keys room 3 is in that key go to room 3 keys room 3 is in that key go to room 3 there are no keys there but it's ok there are no keys there but it's ok since we visited all of the rooms so we since we visited all of the rooms so we output true example 2 we have room 0 1 2 output true example 2 we have room 0 1 2 3 and here we output false we start with 3 and here we output false we start with room 0 and we see we have keys for room room 0 and we see we have keys for room 1 and 3 so we can go from 0 to 1 and 0 1 and 3 so we can go from 0 to 1 and 0 to 3 so at room 1 what keys does one to 3 so at room 1 what keys does one have it has keys 4 3 0 & 1 so 1 can go have it has keys 4 3 0 & 1 so 1 can go to 3 and go to 0 or it can go back to to 3 and go to 0 or it can go back to itself and at room at 30 we have keys itself and at room at 30 we have keys for 0 and we see that we never actually for 0 and we see that we never actually hit room 2 so we output false hit room 2 so we output false so for this question we want to start so for this question we want to start with all the rooms that we can visit with all the rooms that we can visit everything that's unlocked we start from everything that's unlocked we start from room at 0 we see what keys that room has room at 0 we see what keys that room has and add those to our next rooms to be and add those to our next rooms to be visited and for each room that visited and for each room that to visit we see what he's that moon has to visit we see what he's that moon has if we haven't already visited those if we haven't already visited those rooms we add that on to our lists who rooms we add that on to our lists who visit next so what I'm gonna do is I'm visit next so what I'm gonna do is I'm gonna have a set for visited rooms and gonna have a set for visited rooms and exact for rooms that are unlocked that I exact for rooms that are unlocked that I need to visit and it's gonna start with need to visit and it's gonna start with the room 0 since room 0 starts unlocked the room 0 since room 0 starts unlocked so why would stack is not empty so while so why would stack is not empty so while stack I'm gonna pop off what's in stock stack I'm gonna pop off what's in stock so Lewin equals sad huh and I'm gonna so Lewin equals sad huh and I'm gonna explore the keys in that room so if I'm explore the keys in that room so if I'm doing this I can add my room to my doing this I can add my room to my visited tech since I'm in here I'm visited tech since I'm in here I'm visiting this so visited dot add room visiting this so visited dot add room and then for key in rings index with and then for key in rings index with room for each key I want to check if room for each key I want to check if it's in visited or not if not I'm gonna it's in visited or not if not I'm gonna add this to my side so if he not in add this to my side so if he not in visited sack dot append key and we're visited sack dot append key and we're gonna go through the entire stack that gonna go through the entire stack that way once done we're gonna return true or way once done we're gonna return true or false so this means if we visited all of false so this means if we visited all of our rooms the length of visited is going our rooms the length of visited is going to equal our input list so return to equal our input list so return whether or not the length of visited whether or not the length of visited equals the length of rooms and a quick equals the length of rooms and a quick walk through let's start with this walk through let's start with this example right here we have our visited example right here we have our visited and it's gonna be empty and we have and it's gonna be empty and we have stack which is gonna start with moving 0 stack which is gonna start with moving 0 so I pop off what's in stack have that so I pop off what's in stack have that in my room add that to visit it I check in my room add that to visit it I check all the keys in this room so I have keys all the keys in this room so I have keys for one and three none of them are in for one and three none of them are in visited so I add that to my stack go visited so I add that to my stack go back in pop off what's on top I got two back in pop off what's on top I got two visited take off from dreams and that to visited take off from dreams and that to visit it check all the keys in that room visit it check all the keys in that room so I have keys for 0 but I see that it's so I have keys for 0 but I see that it's already visited so I have nothing in already visited so I have nothing in back I need to add to stack so I can back I need to add to stack so I can move on back into my while loop move on back into my while loop and pop off the remaining room added to and pop off the remaining room added to visit it and iterate through room ones visit it and iterate through room ones key so I have key 3 it's already visited key so I have key 3 it's already visited nothing to add to sack I mean zero is nothing to add to sack I mean zero is visited room one is visited and I have visited room one is visited and I have nothing to add to side so what the nothing to add to side so what the length on my visited is three but I had length on my visited is three but I had four dreams so I had zero one two three four dreams so I had zero one two three I had four rooms in total I needed to I had four rooms in total I needed to visit but I only visited three so I visit but I only visited three so I would output pulse so let's run code and would output pulse so let's run code and then comment all of this out accepted then comment all of this out accepted and submit and it is accepted as well if and submit and it is accepted as well if you have any questions let me know it you have any questions let me know it down below otherwise I'll see you next down below otherwise I'll see you next time time [Music]
2024-03-22 16:01:11
841
https://i.ytimg.com/vi_w…E/sddefault.webp
Keys and Rooms - LeetCode 841 Python
RDA2vKkq8NY
hello girls total reality doing with the first really important here coal today's first really important here coal today's problem is fine lucky number a mean to problem is fine lucky number a mean to you so what is all about like given you so what is all about like given another and okay number even to go to another and okay number even to go to sleep and series in the or is equal to sleep and series in the or is equal to the value for example there is the value the value for example there is the value enough difference is to about food is to enough difference is to about food is to which is a lot younger so many anywhere which is a lot younger so many anywhere 103 difference your face to and 103 difference your face to and frequency of 3 is 3 so yellow key number frequency of 3 is 3 so yellow key number is 3 although you can get to also but is 3 although you can get to also but here to take the largest one and here here to take the largest one and here also to here and nothing is there okay also to here and nothing is there okay number so it is giving a minus 1 there number so it is giving a minus 1 there is no in here is minus 1 you can say is no in here is minus 1 you can say member so best way to approach this member so best way to approach this question is to map what will do you will question is to map what will do you will get a map their dog says we'll basically will be storing each value with a total number of three pencils so initially it will be nothing but ever SMS it gets the again like appear in something again same number you know just an agreement to so basically this is creation of the map with all the numbers and then we will just use lucky - 1 because 2 minus 1 if there's nothing as we need to check so if I dot first which is the T value is equal to equal to a dot second and sorry then later lucky equality I go first then later lucky equality I go first and just within their lucky let's okay that's fine okay girls drinking Nancy in the next
2024-03-21 01:02:58
1,394
https://i.ytimg.com/vi_w…xresdefault.webp
1394. Find Lucky Integer in an Array Leetcode
3Qc-Fpn70Bw
hey everyone uh today i'll be going over the elite code problem the elite code problem 1769 minimum number of operations to 1769 minimum number of operations to move all balls to each box move all balls to each box so you have all this junk here but as so you have all this junk here but as always i'm just going to explain it as always i'm just going to explain it as simply as possible and i'll do so with simply as possible and i'll do so with this test case here this test case here so given this test case we're given some so given this test case we're given some string and these are just boxes right string and these are just boxes right and it's a one if it has a ball in it and it's a one if it has a ball in it and it's a zero if it doesn't have a and it's a zero if it doesn't have a ball in it so you could think of this ball in it so you could think of this string kind of like as an array right so string kind of like as an array right so it's like this uh so this one has a ball it's like this uh so this one has a ball this one has a ball basically we're this one has a ball basically we're trying to figure out um the minimum trying to figure out um the minimum number of operations to move all of them number of operations to move all of them to each box to each box so so moving to this first one how many moving to this first one how many operations would it take to move all operations would it take to move all these balls to this box these balls to this box well it's simple it's just how far are well it's simple it's just how far are they from it right so this one is two they from it right so this one is two from it so we have two operations so far from it so we have two operations so far uh this one is four from it so we have uh this one is four from it so we have six operations so far and then this one six operations so far and then this one is five from it so we add five and it's is five from it so we add five and it's 11. if you actually look here uh this is 11. if you actually look here uh this is in the example two uh this one is eleven in the example two uh this one is eleven uh if we follow the same logic you get uh if we follow the same logic you get the rest of this so i won't do that the rest of this so i won't do that because it'll take a while because it'll take a while so you can actually do it exactly this so you can actually do it exactly this way it's kind of naive but that would be way it's kind of naive but that would be an n squared solution and we could do an n squared solution and we could do better than that better than that now you could just calculate the now you could just calculate the distance of every box to every box uh distance of every box to every box uh that would be an n squared and it does that would be an n squared and it does work but yeah it would just be too weird work but yeah it would just be too weird um you can actually do this in end time um you can actually do this in end time which is what i'm going to be showing so which is what i'm going to be showing so we can actually get crafty about this we can actually get crafty about this right right we can go left to right and right to we can go left to right and right to left in this array and calculate the left in this array and calculate the accumulative distances from each ball to accumulative distances from each ball to going to the end basically going to the end basically so we can do that because if we go left so we can do that because if we go left to right and right to left if we add to right and right to left if we add those at any given point that'll be the those at any given point that'll be the total number of operations to get all total number of operations to get all balls from the left and all balls to the balls from the left and all balls to the right right right right so that's exactly why we're doing it so that's exactly why we're doing it this way so if you look we're getting a this way so if you look we're getting a result here so let's set up our result result here so let's set up our result which is just a res and it's going to be which is just a res and it's going to be the same exact size as length the same exact size as length and we do it this way remember boxes is and we do it this way remember boxes is a string this throws a lot of people off a string this throws a lot of people off but we can just treat it as an array but we can just treat it as an array right we're going to have a few more right we're going to have a few more things which is a res things which is a res i'm gonna have an ops which is just i'm gonna have an ops which is just total operations and you'll see why and total operations and you'll see why and also a count okay so the first thing we want to do is go left to right so what is the goal here we're just trying to figure out the accumulative distance of getting all balls everywhere we see in the array from left to right so we're going to go left to right and boxes length and just a normal for loop right the first thing we want to do is at this point we want to add however many operations we have the reason why we do this each iteration of the loop is because we're going one more right so if we're going one more we have to add all the operations we've already done because they have to go one more distance so an example is if we've had five operations at index one going to index two it'll be plus five more because they all five of those balls have to go over so that's why you do it that way uh the next thing you want to do is we're going to add the count and this is just counting like the ones the balls the total balls uh we're going to add to the count uh however many balls we have and to just quickly figure out if this is a ball and treat it as a number let's just go boxes dot car at i and let's just convert it to an n so we'll go minus the zero card because if it's zero it'll be zero if it's one it'll be one right so we'll do that and then the next thing we want to do is we just add count to the ops because what however many balls we have at this point we'll have to add it to operations for the next iteration and it's just that simple uh we can actually just go ahead and copy this down and then make this right here boxes dot and then we're just going right to left and then we're just going right to left right right sorry about that sorry about that so this time right to left same exact so this time right to left same exact thing another thing we want to do is thing another thing we want to do is since we're going right to left and it's since we're going right to left and it's a fresh iteration uh we actually want to a fresh iteration uh we actually want to reset reset uh ops and count right uh ops and count right so let's go ahead and do that so ops so let's go ahead and do that so ops will be zero again and count will be will be zero again and count will be zero again zero again and then lastly let's return res and we and then lastly let's return res and we should be good let's go ahead and run should be good let's go ahead and run this oh res is already defined oh yeah i hope somebody called that we actually didn't need a ras variable that's silly it looks like it's good let's submit it and looks like it's good 76 so let's talk about run time remember i talked about the bad solution and why it was going to be n squared and this is actually uh o n time because all we're doing is two loops left to right right to left so it's 2n which is just n right uh space we do not count the output array as space usually because it's not extra space this is expected space so really space is one right because we're not using anything besides the output array so yeah i hope this made sense thank you for watching i appreciate it
2024-03-22 12:49:16
1,769
https://i.ytimg.com/vi/3…axresdefault.jpg
Leetcode Solution - 1769 Minimum Number of Operations to Move All Balls to Each Box
RKPCF-hsOPY
today we're looking at lead code 199 binary tree binary tree right side view this is a continuation right side view this is a continuation of our level order traversal series in of our level order traversal series in this playlist and we are going to be this playlist and we are going to be using using the same template the same pattern to the same template the same pattern to solve this as we use to solve solve this as we use to solve the other problems that deal with level the other problems that deal with level order traversal in this playlist that's order traversal in this playlist that's including including binary tree level order traversal one binary tree level order traversal one and two and two n airy tree level order traversal and a n airy tree level order traversal and a zigzag zigzag level order traversal so we're just level order traversal so we're just going to make a slight modification going to make a slight modification and we're going to use the same pattern and we're going to use the same pattern to solve this one as well to solve this one as well okay so what we have here is we have a okay so what we have here is we have a binary tree binary tree we're given the root and we want to we're given the root and we want to imagine ourselves imagine ourselves standing on the right side of it and standing on the right side of it and return those values of those nodes so return those values of those nodes so they can be ordered from top to bottom they can be ordered from top to bottom so here we have a tree we want to return so here we have a tree we want to return 1 3 1 3 and 4 because they are all on the right and 4 because they are all on the right side of the tree side of the tree and our nodes are going to be 0 to 100 and our nodes are going to be 0 to 100 and the values are minus 100 to and the values are minus 100 to 100 okay 100 okay so what we want to do here is if this is so what we want to do here is if this is our tree our tree we want to have two while loops and then we want to have two while loops and then we want to use a q we want to use a q data structure okay and what we're going data structure okay and what we're going to do is we have this q to do is we have this q data structure we're going to initialize data structure we're going to initialize it with the root it with the root okay and we're going to also initialize okay and we're going to also initialize a result and set it to an empty array a result and set it to an empty array and now we have two while loops here and now we have two while loops here okay we have an outer while loop that as okay we have an outer while loop that as long as the queue is not long as the queue is not empty we keep on running this loop and empty we keep on running this loop and an inner while loop that an inner while loop that we want to get the length of the queue we want to get the length of the queue at that moment in time at that moment in time okay so uh let me just kind of step okay so uh let me just kind of step through that through that here we have the q it's at one it's not here we have the q it's at one it's not empty at this point empty at this point we can see that the value in the queue we can see that the value in the queue is at the zeroth level is at the zeroth level okay this is zero one two the value at okay this is zero one two the value at the the the queue at this point in time is one the queue at this point in time is one which is the value at the zeroth level which is the value at the zeroth level so so when we get to this point we're going to when we get to this point we're going to save the length of this save the length of this of the queue at this point which is one of the queue at this point which is one and then we are going to take the last and then we are going to take the last element element in the queue okay at this point it's one in the queue okay at this point it's one so we're just going to go ahead and push so we're just going to go ahead and push this one into the cube this one into the cube now we are going to go into our inner now we are going to go into our inner loop and we're going to run it loop and we're going to run it length times okay so we'll decrement it length times okay so we'll decrement it when we're inside of there when we're inside of there and what we want to do is po pull out and what we want to do is po pull out this one so we shift it off this one so we shift it off and we put its children back into the and we put its children back into the queue so we check if there's a left queue so we check if there's a left there is we go ahead and push that two there is we go ahead and push that two into the queue into the queue we check if there's a write on the one we check if there's a write on the one node there is it's three we push that node there is it's three we push that into the queue into the queue and we only did it on one iteration so and we only did it on one iteration so we break out of that while loop that we break out of that while loop that inner while loop inner while loop and now we're back on the outer while and now we're back on the outer while loop and you can see now loop and you can see now the queue has the correct values the queue has the correct values for that first level and so all we're for that first level and so all we're going to do is take the last going to do is take the last value here this 3 whatever is the last value here this 3 whatever is the last element in the queue element in the queue and push that into the result so here we and push that into the result so here we have have 3 that gets pushed into the result 3 that gets pushed into the result then again we do the same thing we save then again we do the same thing we save the the length of the queue at that the the length of the queue at that moment moment into this lend variable which is going into this lend variable which is going to be two to be two and now we go into our inner loop and and now we go into our inner loop and we're going to run it twice okay we're going to run it twice okay first time we run it we're gonna shift first time we run it we're gonna shift off this two and it does have a child it off this two and it does have a child it has a 5 has a 5 so we go ahead and push this 5 into so we go ahead and push this 5 into into our q and we decrement this this into our q and we decrement this this length here to 1. length here to 1. and then we go ahead and shift off this and then we go ahead and shift off this 3 and we go ahead and put that into the 3 and we go ahead and put that into the queue queue or we put the children of that into the or we put the children of that into the queue which is four okay queue which is four okay and then this length will turn zero and and then this length will turn zero and we'll break out of this we'll break out of this uh inner while loop now you can see that uh inner while loop now you can see that the q at this point when we get back the q at this point when we get back into the outer while loop into the outer while loop has the correct values for that level has the correct values for that level and we just want to get the last one we and we just want to get the last one we just want to get this 4 just want to get this 4 push that into the result and that is push that into the result and that is our answer and again we'll just do one our answer and again we'll just do one more more iteration just to kind of go over this iteration just to kind of go over this the length here will be 2 the length here will be 2 and then we go into the inner while loop and then we go into the inner while loop we shift off this 5 node we check for we shift off this 5 node we check for any children there's no children any children there's no children we shift off this 4 node there's no we shift off this 4 node there's no children at the same time this children at the same time this decrements down to zero decrements down to zero we break out of this inner loop and now we break out of this inner loop and now there's nothing in our queue it's empty there's nothing in our queue it's empty okay the queue is empty and so we break okay the queue is empty and so we break out of this outer loop out of this outer loop and then we go ahead and return that and then we go ahead and return that result okay so that's the idea behind this now what is our time and space complexity i know there's two while loops so it's it's tempting to think that we're doing this in quadratic time but you have to think about how many times are we hitting these nodes okay how many times are we are we traversing through these nodes and we're only traversing through them once because even though we have two loops this second loop is just running level by level it's not running through the whole entire tree and so our time complexity here is actually o of n it's just linear time because we're and then what about what about our space and then what about what about our space complexity well complexity well it it's not linear normally in the other it it's not linear normally in the other videos it's linear because we're saving videos it's linear because we're saving the entire level here we're just saving the entire level here we're just saving the values on on uh on the height of the the values on on uh on the height of the tree tree okay so just on the on the right side of okay so just on the on the right side of the tree we're just saving those values the tree we're just saving those values and so the uh the um and so the uh the um space complexity is gonna be o of h space complexity is gonna be o of h which is the height of the tree and if which is the height of the tree and if it's it's balanced then it would actually be log n balanced then it would actually be log n but we don't have a guarantee that the but we don't have a guarantee that the input is a balanced binary tree if it input is a balanced binary tree if it was a balanced binary tree then we would was a balanced binary tree then we would have have a space complexity of log log n but a space complexity of log log n but in this case we can just say the the in this case we can just say the the space complexity is the height of the space complexity is the height of the tree because we're just going to get tree because we're just going to get the the right most values the the right most values which is just going to be the height of which is just going to be the height of that tree the right height of the tree that tree the right height of the tree okay so let's jump into the code okay so let's jump into the code um the first thing we want to do um the first thing we want to do is uh just go ahead and whoops we don't is uh just go ahead and whoops we don't want to do that want to do that okay see what's going on here okay see what's going on here okay okay so first we want to take care of the edge case if the root is empty then an empty array okay and now what we want an empty array okay and now what we want to do to do is go ahead and initialize our q and place our root inside there go ahead and initialize our result set it to an empty array and then we just want to do while the queue is not empty okay and then we want to push into the okay and then we want to push into the result result the last element in our queue the last element in our queue okay so we can do result dot push q uh sorry q at q dot length -1 and then here we just want to do a dot val because this is asking for the values not the nodes okay but in the queue we're actually saving the nodes all right and so now what we do is we do a while len minus minus all this is going to do is decrement len until it gets to zero it'll coerce to a false value and break out of that while loop we want okay and now we just want to put the okay and now we just want to put the children into the children into the uh into the queue so if there is a left uh into the queue so if there is a left child we can just do a q dot push no dot we can do q dot push no dot right we can do q dot push no dot right and then we just want to return our and then we just want to return our result okay and that's it let's go ahead and run this make sure everything works and we're good is elite code number 199 binary tree right side view hope you enjoyed it and i will see you
2024-03-21 14:36:48
199
https://i.ytimg.com/vi/R…axresdefault.jpg
LEETCODE 199 (JAVASCRIPT) | BINARY TREE RIGHT SIDE VIEW
I10jRHCqCzY
music] [ ] [music] yeah yeah [music ] [music] [music]
2024-03-22 18:16:59
1,832
https://i.ytimg.com/vi_w…xresdefault.webp
1832. Check if the Sentence Is Pangram |LeetCode Series Solution With Python3||omnyevolutions
GwiKly7UJbQ
hey hello there today i want to talk about question 677 maps on pairs about question 677 maps on pairs we want to implement a class called we want to implement a class called mapson which supports two methods mapson which supports two methods uh insert and some so it's a pretty much uh insert and some so it's a pretty much a a very simple key value of storage the very simple key value of storage the insert is the insert is the right operation the sum is the read right operation the sum is the read operation operation so the let's look at keep reading the so the let's look at keep reading the insert method insert method will be given the key value pair the will be given the key value pair the string is the key the integer string is the key the integer is the value so we want to remember the is the value so we want to remember the key value of mapping key value of mapping if the key already exists we want to if the key already exists we want to update the update the the associated value to be the newly the associated value to be the newly given up volume so given up volume so this insert handles both insert and this insert handles both insert and update update then just the read message the query the then just the read message the query the sound method here we'll be given the sound method here we'll be given the string represent string represent prefix so we're doing kind of a prefix prefix so we're doing kind of a prefix matching matching we want to return the sum of all the we want to return the sum of all the all the values associated with the key all the values associated with the key that starts with that prefix that starts with that prefix so looking at example uh so the so looking at example uh so the we initialize this theorem structure we we initialize this theorem structure we insert the first the key value pair insert the first the key value pair apple to three apple to three so when we do a query using ap as the so when we do a query using ap as the prefix because ap prefix because ap matches apbre in the prefix kind of a matches apbre in the prefix kind of a sense sense so we know that apple has the value 3 so so we know that apple has the value 3 so we return 3 we return 3 because this is the only key value pair because this is the only key value pair we currently have now we currently have now now and ap actually matches that now we now and ap actually matches that now we insert another insert another new key value pair abb let the value be new key value pair abb let the value be 2 2 now if we do the same query sum ap now if we do the same query sum ap because ap matches both apple and app in because ap matches both apple and app in the the in the prefix sense so we add those two in the prefix sense so we add those two values together and return the sum values together and return the sum which is five here so the obviously which is five here so the obviously the very obvious way to do to solve this the very obvious way to do to solve this problem is to problem is to just use map map string to value just use map map string to value so that's the insert the time complexity so that's the insert the time complexity for this is almost a constant all we do for this is almost a constant all we do is just take the string to a hash and is just take the string to a hash and create this key value mapping it's create this key value mapping it's almost the constant almost the constant the query sum the query sum is to do this prefix mapping map is to do this prefix mapping map matching matching for key in keys for key in keys if uh if if uh if key dot starts with the query then we um you know answer add this value something like something like that so we're going to have a loop to iterate over all the existing keys in this data structure and for every key existing key we will match that try to match that with the prefix so let's say the prefixes of size l the length of for the prefix then we have n key in total this thing would cost uh n and multiplied by l in time so so we can see here this very simple approach using a just using a map to store the key value association have the sum to be the sum here has to be quite heavy on the time complexity it has to check all the keys so it's not so ideal so let's think about how we can actually speed up this query so since that we are doing prefix query instead of just inserting the single key value pair we can insert all the prefix to the same same value mapping if none of those existing yet if it's if the prefix exists that we're going to do some update so let's talk about we're just so this is called this second approach so this is called this second approach is going to be i'm gonna show you how it looks like so so instead of only have one entry in the so instead of only have one entry in the key value key value mapping storage apple two three we mapping storage apple two three we actually gonna do actually gonna do r a to three ap to three app to three appl to 3 and also apple to 3. so the next time we search for anything that starts with ap ap we can just directly grab the value here so if we insert another another key value pair ap to apb to 2. what we're going to do basically follow the path gear and basically follow the path gear and updating here to be 5 and 5 and 5 updating here to be 5 and 5 and 5 because we're adding 2 now so because we're adding 2 now so if we search for ap the prefix if we search for ap the prefix ap we're just going to directly grab 5. ap we're just going to directly grab 5. let's talk about another thing update let's talk about another thing update let's say that we insert apb equal to 1 let's say that we insert apb equal to 1 this time what we would do is to this time what we would do is to do some kind of an adjustment to all the do some kind of an adjustment to all the nodes uh nodes uh all the nodes all the prefix key value all the nodes all the prefix key value pairs here pairs here so we know that app used to be two but so we know that app used to be two but now is 1. now is 1. so the difference is 1 subtract by 2 so the difference is 1 subtract by 2 equal to equal to negative 1. so for all the prefix negative 1. so for all the prefix in appb we're going to decrement the in appb we're going to decrement the value by 1. value by 1. so after this update so after this update if we do the prefix query for if we do the prefix query for anything here it should return the anything here it should return the correct value correct value so we can see here we use a lot more so we can see here we use a lot more space and space and the insert is now no longer constant the insert is now no longer constant anymore so this insert now takes uh uh we have to consider all k all k up i'm using l right uh all l different uh prefix for the key and if we if we're using c plus plus we might have constant slice but for most languages it's uh the string is immutable so the take the slice take the prefix it takes also linear time so it will be in this case it will be but the good thing about this is that but the good thing about this is that the query is constant so the difference between this approach one and approach two is that one is uh very light on the insert but the queries the read is complex second one we basically are trading space and the time on the insert to speed up the read so the read is not constant but the insert is the the key size squared so so the question is now is there so the question is now is there something that kind of in between something that kind of in between maybe ideally both linear in terms of maybe ideally both linear in terms of read and write so so if our read and write so so if our application the the this key value application the the this key value storage is storage is used to support sort of balance the read used to support sort of balance the read and write and write we want to approach three so notice we want to approach three so notice how this looks like here in the in the how this looks like here in the in the second approach second approach we basically create we basically create a path sort of like a pass inside the a path sort of like a pass inside the try try we have a root note points to a a points we have a root note points to a a points to b p points to another p to b p points to another p that p note points to have a children that p note points to have a children start with uh that has a key of uh l start with uh that has a key of uh l and and so on so forth um we will just and and so on so forth um we will just uh uh if we use try we can just store all if we use try we can just store all those those uh prefix to uh prefix to the value kind of association um just as the value kind of association um just as the just put the number as a one of the the just put the number as a one of the properties for the try node inside the properties for the try node inside the tri data structure tri data structure so that way we essentially store the so that way we essentially store the same information as same information as as prefix hash but as prefix hash but the insert is going to be linear time we the insert is going to be linear time we just go one path just go one path uh through the following the uh through the following the you know the the key or the query you know the the key or the query do a linear pass inside the try and do a linear pass inside the try and updating the updating the values for the nodes along the way so values for the nodes along the way so if we use try the insert is going to if we use try the insert is going to the time complexity is going to go down the time complexity is going to go down from l square to from l square to order of l but the sum order of l but the sum we no longer can directly look up at the we no longer can directly look up at the prefix to volume mapping we have to prefix to volume mapping we have to start with the first start with the first character and do a linear path inside character and do a linear path inside the try to graph the value the try to graph the value so so that's sort of like a balance in so so that's sort of like a balance in between the between the we we now have linear time insert and we we now have linear time insert and linear time uh linear time uh query so let's just quickly put it in here approaches three is to years try to have order of l insert and the sum i guess depends on the real application you can choose either one of those the you can choose either one of those the one of the three approach that one of the three approach that satisfies the needs the best satisfies the needs the best yeah so i'm gonna just code the try yeah so i'm gonna just code the try solution because it's uh solution because it's uh the one that requires the most code i'm just subclassing the default i'm just subclassing the default dictionary so the try is dictionary so the try is more dynamic we only insert this more dynamic we only insert this character to character to you know the next character to the node you know the next character to the node association when we association when we really have to so the space is growing really have to so the space is growing dynamically even though it will be dynamically even though it will be slower than slower than pre-allocation so pre-allocation so [Music] we're going to set the constructor of the default factory to be the tri node itself and every node we just have a value associated with it so it's like the node a will have five node p following node a would have another five node p following the previous node p will also have a value of 5 associated with that node so that's this slot here initially every node would just have a value 0. now we initialize this key value of storage now let's code the the insertion oh now let's code the the insertion oh something that we need to do is for something that we need to do is for either either two and three the approach we also need two and three the approach we also need to to keep the same key value pairs as the keep the same key value pairs as the first one first one because the update here remember that because the update here remember that when we insert up when we insert up apb to 2 we just go apb to 2 we just go we either update update all the we either update update all the prefix hash in the second approach to prefix hash in the second approach to have all those add to have all those add to um in the try we just follow the try um in the try we just follow the try paths to paths to update every node value to to increment update every node value to to increment those by two those by two but when we have a update uh we have to but when we have a update uh we have to figure out figure out what's the previous value and calculate what's the previous value and calculate the delta the delta use that downtown to update all those use that downtown to update all those prefix prefix or in try's case it's updating all the or in try's case it's updating all the values for the values for the nodes on the path so for that reason we nodes on the path so for that reason we want to store the want to store the the key value pair we can we can we can the key value pair we can we can we can do a single pass and try to grab that do a single pass and try to grab that uh or in the prefix hash uh or in the prefix hash sorry in the in the prefix hash it's sorry in the in the prefix hash it's always there always there but in the try we could either do a but in the try we could either do a linear path to grab the value linear path to grab the value or or we can use extra space to store or or we can use extra space to store that that so so if we actually so so if we actually just do a traverse to grab that just do a traverse to grab that then figure out the data and do another then figure out the data and do another second pass second pass the insert is still the insert is still linear in with respect to the size of linear in with respect to the size of the input so the input so but but if i can directly look it up but but if i can directly look it up it might be faster so i'm going to use a it might be faster so i'm going to use a map to do that it's pretty much the key value pair so it's pretty much the key value pair so it's a string to integer mapping okay so let's cut the insert insert here is basically create a path inside the try if the character does not exist otherwise we will just try to do the update so if the tree if the path does not exist that means we don't have a key for that that that's essentially meaning that we that that's essentially meaning that we have a delta of have a delta of the value here so so to have the insert the value here so so to have the insert the function for both insert and update the function for both insert and update we always going to be dealt with that we always going to be dealt with that delta for a delta for a fresh new insert the delta is just the fresh new insert the delta is just the value value for real update is going to be the for real update is going to be the difference between the difference between the new key and the o key new key and the o key so if we don't have that key so if we don't have that key the default dictionary will return a the default dictionary will return a zero so the difference is zero so the difference is pretty much the value itself so this pretty much the value itself so this will make sure that the insert were will make sure that the insert were exposed in the exposed in the new case or the update case so the new case or the update case so the insert is insert is just going to do a single passing try just going to do a single passing try we get the node which initialize the we get the node which initialize the root for each character inside the key we're just going to traverse keep traverse inside the try uh node c char let's make uh make the code a little bit more readable and for every node here uh we're gonna we're gonna set the update the value is yeah so this should be the insert yeah so this should be the insert okay we okay we should also update this as well remember the new value for the key now this for loop is to do a linear pass inside the try and for every every tri node along the way we update the value with the new delta so that's the insert you can see here it's a log of lti here for the sum it's uh it's going to be the same situation we're going to grab the and for for every character in the prefix we're if it's not there we should return what if it's not there we should return what we should return we should turn zero right because there is no value associated with that key otherwise we're just going to follow and once we exhausted all the character and once we exhausted all the character inside the prefix inside the prefix we will land in the in the node that we we will land in the in the node that we can just uh can just uh directly return the value i'm not sure should we return 0 or something here it doesn't let's see if the code works it's working uh let's try to do a test case when we have a prefix that's not existing here so we insert output three we try to query apx what kind of thing you should return it should return zero okay so this has i think it's better to just make a quick note here if the prefix does not exist we should return zero all right uh so it seems to working let's submit it okay it's working um so uh yeah it's uh it's not a hard question and the good thing about it is about this question is that we have three different time complexity uh decisions that we can come we have three different approaches which they all have their trade-offs even the most straightforward method can be useful uh if we are dealing with a really right heavy but rarely read the kind of situation but for the for the second one is uh read you know they're the trade-off the right is slow but the the read is super fast uh the one that i code here using try is sort of like uh in between maybe like a default option if we really maybe like a default option if we really have three different kind of options for have three different kind of options for this this keyboarding storage all right so that's keyboarding storage all right so that's this question today
2024-03-20 15:59:25
677
https://i.ytimg.com/vi/G…axresdefault.jpg
Leetcode 677 Map Sum Pairs
Dz0q7aJQOcU
Hello Hello Everyone in the month of Sandeep and in this video you will show you how to solve this video you will show you how to solve plate problem vs problem se zameen akshikari na dheer wa nyanyat subscribe our channel subscribe a slack we examples and tried to understand what a question is singh More than More than More than time to subscribe to that time to subscribe to that a army this zero earn one which is this a army this zero earn one which is this particular morning what is the meaning of particular morning what is the meaning of subscribe elements and values ​​from a subscribe elements and values ​​from a are next wwc2 what is the way want to that is the are next wwc2 what is the way want to that is the what is the difference among all what is the difference among all elements and the elements and the elements and the Subscribe - ₹499 Vighna more subscribe and subscribe the Channel subscribe that 2G spectrum of and B-2 element is my duty Difference latest wave fight According to a Divya Narendra the difference will be a 3 The Best Answers Issues and Electronic to the Answer Returning from example2 example2 example2 Returning from example2 example2 example2 Returning from example2 example2 example2 452002 end subscribe that fry already set up all the limits in that fry already set up all the limits in rangers same denge pattern - off service - rangers same denge pattern - off service - that Bigg Boss all elements in the avengers that Bigg Boss all elements in the avengers theme next straight or 2000 2 eggs subscribe and subscribe to the Page if liked The Video then subscribe to liked The Video then subscribe to liked The Video then subscribe to the Video then subscribe to the Page the Video then subscribe to the Page Differences One is Next Subscribe Differences One is Next Subscribe Inside Do Inside Do n't Forget to Subscribe 56001 Subscribe Channel n't Forget to Subscribe 56001 Subscribe Channel Subscribe Must Subscribe Subscribe Subscribe Must Subscribe Subscribe [Music] Subscribe Thank You Information On For particular For particular For particular index of evidence index of evidence that Idea want to know what to eliminate them before that Idea want to know what to eliminate them before but no one can select the ability to this worship that I problems in it ranger balance that I problems in it ranger balance marriage palace can go from 1200 after 10 minutes marriage palace can go from 1200 after 10 minutes pan lid and explosive assistance pan lid and explosive assistance force but not limited force but not limited force but not limited rose day can help in tasty elements present itself a the correct select c android 2.3 lines is in the limit for 52 years older than what does have arrest nothing is seen the Holly and 4151 Two Times Holly and 4151 Two Times Holly and 4151 Two Times for Extra Oil That Toot Guys Is Possible to Build a for Extra Oil That Toot Guys Is Possible to Build a Splash Select Subscribe Before You Start Other Elements Present in Everything Is Us a Product Solve Animated 605 What All Elements Present Before This From This Particular Form Correct Sacrifice and Drop Again That someone else The Element of Presenting You That someone else The Element of Presenting You in Next Time When You Are Ment for 28 in Next Time When You Are Ment for 28 2012 Will Do Something 2012 Will Do Something Good for Everything in this Value The Good for Everything in this Value The Correct Correct That New Swift Equals Early-Morning Youth The That New Swift Equals Early-Morning Youth The Elements of Medicine for Five But Avoid Elements of Medicine for Five But Avoid This To-Do List This To-Do List This To-Do List Subscribe To All World Channel Subscribe To All World Channel Next Debit Is Equal To Ayodhya Next Debit Is Equal To Ayodhya Notification But Avoid Calculator Values Notification But Avoid Calculator Values For This You Minus One Ranger Tense Present For This You Minus One Ranger Tense Present In This Particular Roegi Coffee Date Perfect Perfect Perfect Love You To Applicant Index 2.1 SIM Ko Love You To Applicant Index 2.1 SIM Ko Swadist A Flying This Is Always 90 Degrees And And Sunao Hafte Dal Di Values ​​For You And Sunao Hafte Dal Di Values ​​For You Interested In All Its Students Of Query The Interested In All Its Students Of Query The Ye Want To Ye Want To Ye Want To Jai Hind Istri 315 What is the Best Defense of the Great Co Targeted Vs Difference Only Value - This Value 1008 Columns in This Element Hindi E Was the Like U World Record of 102 Traffic Jams They Arrange Values World Record of 102 Traffic Jams They Arrange Values to Small Value Salwar Late to Small Value Salwar Late Message Message Message subscribe my channel to subscribe my channel to left right the center ranged from this left right the center ranged from this rains we have the greatest range ki rains we have the greatest range ki dadi a hair oil them with the republic day to all of us here we have times we have dropped in the here we have times we have dropped in the Center Range Center Range Select Ghaghra 15000 Next Se Select Ghaghra 15000 Next Se Mobile Again Zero - Se Zinc Vansh Birthday Mobile Again Zero - Se Zinc Vansh Birthday 182 90252 Angle Definitely Subscribe 182 90252 Angle Definitely Subscribe Next 9 News Se Just Rs 10 Mobile Next 9 News Se Just Rs 10 Mobile Aggressive 108 Me This Element Was Again Aggressive 108 Me This Element Was Again Notes In Hindi Strange Enemies Notes In Hindi Strange Enemies Convention Only But Not On Scene Convention Only But Not On Scene Convention Only But Not On Scene Acid 000 Definitely Comment 100000000 The note of the correct To give only eight tips Saturday 14th 6820 Volume Minimum Episode This not only the plain mode of this is elements of Baroda always involved in the first to in more according 1000 subscribe to the Page according 1000 subscribe to the Page A Saiya Diet Wikipedia Introduction Element Ranges A Saiya Diet Wikipedia Introduction Element Ranges From 12108 Dubey Only Tight And From 12108 Dubey Only Tight And Element - Features - Element From Zet And Element - Features - Element From Zet And Finally Bigg Boss Fixed Period Subscribe Finally Bigg Boss Fixed Period Subscribe Must Insects Straight To Must Insects Straight To A Plate Crops Country Code Vegetables A Plate Crops Country Code Vegetables Difference In Function And Two Parameters Difference In Function And Two Parameters Norms And Where Is Not Physically Storing Norms And Where Is Not Physically Storing The The The the Channel Please subscribe and subscribe the Video then subscribe to subscribe the Channel Please subscribe subscribe the Channel Please subscribe thanks for thanks for [संगीत]
2024-03-25 12:25:52
1,906
https://i.ytimg.com/vi/D…axresdefault.jpg
Leetcode 1906 Minimum Absolute Difference Queries
mptPELnQACI
oh hey hey everybody this is Larry this is day what is it day 12 of the legal is day what is it day 12 of the legal daily challenge hit the like button hit daily challenge hit the like button hit the Subscribe button drop me on Discord the Subscribe button drop me on Discord let me know what you think about today's let me know what you think about today's qualm 976 largest perimeter of the qualm 976 largest perimeter of the triangle it's Wednesday or Tuesday triangle it's Wednesday or Tuesday depending on where you are hope you are depending on where you are hope you are having a great week middle of the week having a great week middle of the week hope everyone does well hope everyone does well um yeah let me know what you think about um yeah let me know what you think about this Farm I am not gonna lie I drank a this Farm I am not gonna lie I drank a little bit too much tonight little bit too much tonight um not that much actually I'm okay but um not that much actually I'm okay but I'm I'm uh so we'll sell that how this I'm I'm uh so we'll sell that how this video goes it's a little tipsy let's go video goes it's a little tipsy let's go uh given nums we turned the largest uh given nums we turned the largest perimeter of a non-zero formed by the perimeter of a non-zero formed by the way of these lengths if it's impossible way of these lengths if it's impossible form on any triangle of non-zero area we form on any triangle of non-zero area we turn zero okay turn zero okay so there is obviously the triangle in so there is obviously the triangle in the quality the quality um I'm thinking about whether so I'm just thinking about like a random property in my head I don't know if it's true where what is the triangle in equality right and that basically is that that means that a plus b is greater than C right I was going to say equal to but I was like that's not true right and then my question is the the largest of those three well what can we do right hmm because I think I'm I'm inclined to that that so I have a so I have a hypothesis I so I have a so I have a hypothesis I guess that's what I'm trying to do is guess that's what I'm trying to do is that and I don't know if this is true so that and I don't know if this is true so it might not be right is that we sort it might not be right is that we sort then the answer is going to be adjacent then the answer is going to be adjacent why do I say that why do I say that um and some point of this is kind of um and some point of this is kind of like a almost like a reverse like a almost like a reverse um like if I I try to kind of think a um like if I I try to kind of think a little bit backwards or another little bit backwards or another direction right the way that I would direction right the way that I would maybe think about is something like maybe think about is something like like let's say they are not like let's say they are not adjacent right let's say okay let's adjacent right let's say okay let's start with adjacent let's say we have a start with adjacent let's say we have a b and c where this is you go to you know b and c where this is you go to you know um let's say N Sub I ends up I plus one um let's say N Sub I ends up I plus one N Sub I plus two right well if this is N Sub I plus two right well if this is not a triangle not a triangle would it ever make sense would it ever make sense to like in a sliding windowy you know to like in a sliding windowy you know kind of way would it ever make sense to kind of way would it ever make sense to make this bigger no right because then make this bigger no right because then it's still not a triangle would it make it's still not a triangle would it make sense to make this smaller no then it's sense to make this smaller no then it's still not a triangle so that means that still not a triangle so that means that I feel like I mean it's not a great I feel like I mean it's not a great proof but that was the first intuition proof but that was the first intuition that when I first performed I'm like is that when I first performed I'm like is this true and I to be honest I don't this true and I to be honest I don't think I have a great proof other than think I have a great proof other than what I just it's not what I show you what I just it's not what I show you start a strict mathematical proof but start a strict mathematical proof but it's the idea that and you could kind of it's the idea that and you could kind of maybe prove that aware as well meaning maybe prove that aware as well meaning that if there's a big you know if that if there's a big you know if there's a an X such that X is greater there's a an X such that X is greater than N Sub I then you want X instead than N Sub I then you want X instead right right um because 10 has a bigger parameter um because 10 has a bigger parameter um and then same thing um and then same thing well I mean I guess that's not the truth well I mean I guess that's not the truth I was gonna say the same thing here but I was gonna say the same thing here but that's not true right but if we have that's not true right but if we have another number that makes it bigger then another number that makes it bigger then we go right we go right but I can prove it to be honest so uh but I can prove it to be honest so uh yeah yeah right um it's minus two and I guess we can kind of go the other and I guess we can kind of go the other way I actually meant to just do it this way I actually meant to just do it this way but if we go back if we assume that way but if we go back if we assume that the the adjacent thing is true I believe the the adjacent thing is true I believe it is it is because okay oh yeah I think the other because okay oh yeah I think the other example I mean I didn't do a good job of example I mean I didn't do a good job of this but the other example of like if uh this but the other example of like if uh num N Sub I ends up I plus one ends of I num N Sub I ends up I plus one ends of I plus two if there isn't numbered with X plus two if there isn't numbered with X where X is true I kind of skip this a where X is true I kind of skip this a little bit then that means that little bit then that means that that these three numbers are good that these three numbers are good instead so then you can remove this and instead so then you can remove this and also by definition these are adjacent or also by definition these are adjacent or whatever right so I think that whatever right so I think that I think it's I think it's it's kind of tough because if it was in it's kind of tough because if it was in the contest I definitely would play the contest I definitely would play around with it a little bit more maybe a around with it a little bit more maybe a lot more because I'm not that confident lot more because I'm not that confident about this I feel like I'm okay enough about this I feel like I'm okay enough to give it a go and there is some um you to give it a go and there is some um you know meta second guessing with the fact know meta second guessing with the fact that this is easy right like if this was that this is easy right like if this was a heart would I think a little bit more a heart would I think a little bit more deliberately to be honest probably so deliberately to be honest probably so this user is not a great hint well it's this user is not a great hint well it's too much of a hint if you ask me too much of a hint if you ask me um I'd rather not know it um I'd rather not know it but yeah so but yeah so we have a is equal to well ABC maybe we have a is equal to well ABC maybe thumbs up I num sub I plus one number so thumbs up I num sub I plus one number so I plus two and then if a plus b is I plus two and then if a plus b is greater than C then we return a plus b greater than C then we return a plus b plus C because that's the permanent plus C because that's the permanent whoops foreign otherwise we'll Return to whoops foreign otherwise we'll Return to Zero Zero let's at least give it a quick run let's at least give it a quick run I believe that's the case I may think I believe that's the case I may think you can do an excessive uh proof in what you can do an excessive uh proof in what I just kind of did I think I was kind of I just kind of did I think I was kind of I wouldn't say I was okay there we go I I wouldn't say I was okay there we go I haven't done this before apparently haven't done this before apparently um huh I mean I don't think I could do um huh I mean I don't think I could do any faster so that's a little bit any faster so that's a little bit whatever whatever um um this is obviously linear time constant this is obviously linear time constant space space but I'm trying to think what I can think but I'm trying to think what I can think about a better proof proof oh no so I about a better proof proof oh no so I lied about the constant time sorry I lied about the constant time sorry I forgot the Sorting so n log n time forgot the Sorting so n log n time um you know constant space yeah I think the proof that I would say yeah I think the proof that I would say is if you could squeeze a number between is if you could squeeze a number between it then there that's I think that's it then there that's I think that's that's the way that I would phrase it that's the way that I would phrase it right meaning that if a plus b uh or a B right meaning that if a plus b uh or a B and C is a triangle if D is and C is a triangle if D is in a in a can either you know if you're trying to can either you know if you're trying to add a d That's in between then a D and B add a d That's in between then a D and B is a triangle is a triangle which of course in this case which of course in this case that means that well this number is that means that well this number is going to be smaller than ABC assuming going to be smaller than ABC assuming that D is between A and B right so that that D is between A and B right so that doesn't matter so if we have another D doesn't matter so if we have another D where B's DC is a triangle then where B's DC is a triangle then obviously obviously you know this number is strictly bigger you know this number is strictly bigger than a b and c than a b and c but I don't think that I described it but I don't think that I described it that well but I guess I proved by AC let that well but I guess I proved by AC let me know what you think let me know what me know what you think let me know what your proof is if especially if a strict your proof is if especially if a strict mathematical one maybe I could do better mathematical one maybe I could do better on a day where i'm I didn't uh you know on a day where i'm I didn't uh you know drank a bit but let me know what you drank a bit but let me know what you think that's why I have though so let me think that's why I have though so let me know what you think stay good stay know what you think stay good stay healthy to good mental health I'll see healthy to good mental health I'll see how they then take care bye bye
2024-03-25 14:17:39
976
https://i.ytimg.com/vi/m…axresdefault.jpg
976. Largest Perimeter Triangle - Day 12/31 Leetcode October Challenge
y0nvBP6gZ-0
so what you're about to see next is me solving a leak code problem from my solving a leak code problem from my course JavaScript and lead code the course JavaScript and lead code the interview boot camp where we solved the interview boot camp where we solved the 75 most important lead toward problems 75 most important lead toward problems using of course JavaScript and a using of course JavaScript and a JavaScript testing package called jest JavaScript testing package called jest anyways the links to that course are in anyways the links to that course are in the description below I hope you enjoy the description below I hope you enjoy the video the video all right so this video will be all right so this video will be dedicated to the pseudocode for elite dedicated to the pseudocode for elite code problem 152 max product so make code problem 152 max product so make sure in the terminal your seed eat into sure in the terminal your seed eat into the course directory exercises folder the course directory exercises folder and then run this just command this is and then run this just command this is gonna fail our test suite so before gonna fail our test suite so before continuing with this video I strongly continuing with this video I strongly recommend you did the maximum sub array recommend you did the maximum sub array problem from earlier on in this array problem from earlier on in this array section of the udemy course because the section of the udemy course because the way we're gonna solve this problem we'll way we're gonna solve this problem we'll build upon the dynamic programming we build upon the dynamic programming we learned from maximum sub array alright learned from maximum sub array alright with that being said let's get started with that being said let's get started so when I first saw this problem I so when I first saw this problem I thought oh I'll just take the maximum my thought oh I'll just take the maximum my maximum sub array code right just paste maximum sub array code right just paste it in and since we're doing a max it in and since we're doing a max product and not a max sum from maximum product and not a max sum from maximum sub array I'll just modify this to be a sub array I'll just modify this to be a multiplier instead and I should pass multiplier instead and I should pass just fine right well I save as you can just fine right well I save as you can see half the test pass and half fail so see half the test pass and half fail so how come our modified maximum sub array how come our modified maximum sub array code is not working let's check the test code is not working let's check the test J's file so we get an input of negative J's file so we get an input of negative 2 3 and negative 4 2 3 and negative 4 if you return 24 back right but instead if you return 24 back right but instead my code will return 3 but our code needs my code will return 3 but our code needs to count for negative numbers because to count for negative numbers because remember that when two negative numbers remember that when two negative numbers multiply it becomes a positive number multiply it becomes a positive number and we can have a larger a product as a and we can have a larger a product as a result and again the problem states they result and again the problem states they have to be continuous right just like have to be continuous right just like maximum sub array so we need to change maximum sub array so we need to change our code here to account for negative our code here to account for negative numbers for a bigger max product and how numbers for a bigger max product and how are we gonna do that let's remove the are we gonna do that let's remove the faulty code and I want to explain how faulty code and I want to explain how we're going to account for negative we're going to account for negative numbers here's the pseudo code we saw numbers here's the pseudo code we saw that input of negative 2 3 and negative that input of negative 2 3 and negative 4 4 we're gonna create two DP arrays in we're gonna create two DP arrays in parallel a max till index DP array and a parallel a max till index DP array and a min till index DP array so mental index min till index DP array so mental index will calculate the smallest product will calculate the smallest product leading up to that index okay it's like leading up to that index okay it's like the polar opposite of max so index and the polar opposite of max so index and why would we try calculate why would we try calculate the minim the smallest product leading the minim the smallest product leading up to a given index because again the up to a given index because again the more quote or the larger the negative more quote or the larger the negative number we get a larger positive number number we get a larger positive number if one of the input numbers is negative if one of the input numbers is negative now we're never going to reference this now we're never going to reference this mental index array when we're trying to mental index array when we're trying to return the result okay return the result okay so ignore these for now when our codes so ignore these for now when our codes finish we return the largest value from finish we return the largest value from our max till index array we just use the our max till index array we just use the DP min till index array to recalculate DP min till index array to recalculate the the maximum product in max the index the the maximum product in max the index but again we still return the largest but again we still return the largest value from maximal index which is 24 and value from maximal index which is 24 and so let's see how the mental index GPA so let's see how the mental index GPA rate becomes useful let's say we are on rate becomes useful let's say we are on negative 4 all right and we're trying to negative 4 all right and we're trying to we're on negative 4 in the input array we're on negative 4 in the input array and we're trying to grasp but we're and we're trying to grasp but we're trying to figure out the maximum product trying to figure out the maximum product right here at the second index of right here at the second index of maximal index so in our maximal index at maximal index so in our maximal index at index I so right here let's say our eye index I so right here let's say our eye is at index 2 math dot max is gonna be is at index 2 math dot max is gonna be whichever is larger of these three whichever is larger of these three things so which is larger negative 4 things so which is larger negative 4 negative 4 times 3 because 3 is the negative 4 times 3 because 3 is the largest product leading up to right largest product leading up to right before negative 4 in here so which is before negative 4 in here so which is bigger negative 4 or negative 12 bigger negative 4 or negative 12 well negative 4 is bigger all right well negative 4 is bigger all right which is bigger negative 4 or or which is bigger negative 4 or or negative 4 times negative 6 because negative 4 times negative 6 because again we multiply the input number times again we multiply the input number times the smallest product leading up to it the smallest product leading up to it well negative 4 times negative 6 is well negative 4 times negative 6 is bigger than just negative 4 itself so we bigger than just negative 4 itself so we say oh it's 24 and so and the min till say oh it's 24 and so and the min till index I has the exact same inputs that index I has the exact same inputs that we provide up here but now is that math we provide up here but now is that math dot min and again once we've finished dot min and again once we've finished filling out the max to index D P array filling out the max to index D P array which in which we use the mental index D which in which we use the mental index D P rate as a reference the calculators P rate as a reference the calculators max max use our code returns the largest number use our code returns the largest number in max till index I hope that made sense in max till index I hope that made sense and the next video were to implement the and the next video were to implement the pseudocode pseudocode all right so let's implement the all right so let's implement the pseudocode from our previous video so pseudocode from our previous video so make sure the terminal your still seated make sure the terminal your still seated into the course directory exercises into the course directory exercises folder and then run this jes command folder and then run this jes command again to run our test suite it will all again to run our test suite it will all fail as expected fail as expected and now let's implement that pseudocode and now let's implement that pseudocode so remember that we create a max DP or a so remember that we create a max DP or a admin DP rate till the index so I'll do admin DP rate till the index so I'll do that max to index is equal to an array that max to index is equal to an array where the first value is the first input where the first value is the first input number in the input array number in the input array sometimes 0 then I will do the same sometimes 0 then I will do the same thing for mental index why is that thing for mental index why is that because well the maximum product and the because well the maximum product and the smallest product up to index 0 assume smallest product up to index 0 assume there's only one number in is the first there's only one number in is the first number itself right that's why we set number itself right that's why we set the initial first value to be the first the initial first value to be the first input number inside of my semicolons input number inside of my semicolons actually and then to save to do a minor actually and then to save to do a minor time complexity optimization I'll say time complexity optimization I'll say let max is equal to numbs 0 this should let max is equal to numbs 0 this should be familiar to you if you did the be familiar to you if you did the maximum sub array problem from before maximum sub array problem from before and now let's iterate through the input and now let's iterate through the input array I'll say for let I is equal to 1 array I'll say for let I is equal to 1 eyes less than um strength I plus plus + eyes less than um strength I plus plus + to make my code easier to read I'll say to make my code easier to read I'll say constant um is equal to numbs at index I constant um is equal to numbs at index I and now let's fill out the corresponding and now let's fill out the corresponding max till index at the correct index spot max till index at the correct index spot and the correct index spot in mental and the correct index spot in mental index so I will say max till index at index so I will say max till index at index I is equal to whichever is larger index I is equal to whichever is larger right the input number itself the input right the input number itself the input number times the largest product to the number times the largest product to the left of it so I'd be max till index this left of it so I'd be max till index this is before it so we see I minus 1 or the is before it so we see I minus 1 or the input num input num so num times the smallest product to the so num times the smallest product to the left of it because again if our input left of it because again if our input number that are iterating on is negative number that are iterating on is negative multiplying by the smallest product to multiplying by the smallest product to the left of it could potentially result the left of it could potentially result in a large number so I'll say num times in a large number so I'll say num times mental index right the largest or the mental index right the largest or the smallest product most negative product smallest product most negative product to the left of it to the left of it and remember from the pseudocode that and remember from the pseudocode that for the correct value at that index spot for the correct value at that index spot in the DP mint index it's the same three in the DP mint index it's the same three inputs but we do math dot min instead so inputs but we do math dot min instead so I'll just copy this here and say min I'll just copy this here and say min till index I is equal to math dot min till index I is equal to math dot min same three inputs from up here and now same three inputs from up here and now let's update our Max variable which will let's update our Max variable which will be accurate right because of this be accurate right because of this setting I'll say max is equal to setting I'll say max is equal to whichever is larger the previous Max or whichever is larger the previous Max or where is in max he'll index at index I where is in max he'll index at index I right our max DP array once this for right our max DP array once this for loop finishes our max variable will now loop finishes our max variable will now be the largest product out even after be the largest product out even after taking to account negative numbers great taking to account negative numbers great so after this for loop I'll just return so after this for loop I'll just return max right and this should pass our tests max right and this should pass our tests great they do let's make sure our code great they do let's make sure our code also passes the leap code tests so I'll also passes the leap code tests so I'll head on there paste it in and we're good head on there paste it in and we're good to go to go so what's the maximum product sub-array so what's the maximum product sub-array complex the analysis time complex these complex the analysis time complex these all event right we have a for loop no all event right we have a for loop no nesting and space complexities also all nesting and space complexities also all event we created 2 DP arrays each the event we created 2 DP arrays each the same length as input right our to same length as input right our to dynamic programming arrays are the dynamic programming arrays are the maximal index and mental index and these maximal index and mental index and these arrays are both the same length as the arrays are both the same length as the input array alright so that concludes input array alright so that concludes this video this video it's me again I hope you found my it's me again I hope you found my solution video helpful and I plan on solution video helpful and I plan on releasing more free content in the releasing more free content in the future and be notified that kind of future and be notified that kind of stuff be sure to hit the like button stuff be sure to hit the like button subscribe and a little notification bell subscribe and a little notification bell icon I'll see you soon icon I'll see you soon [Music]
2024-03-21 13:12:01
152
https://i.ytimg.com/vi_w…xresdefault.webp
Solving LeetCode 152 in JavaScript (Maximum Product Subarray)
NADrbTvDYuk
hey hey everybody this is larry this is day three of the february lego day day three of the february lego day challenge hit the like button to challenge hit the like button to subscribe and join me on discord let me subscribe and join me on discord let me know what you think about today's farm know what you think about today's farm uh hopefully everyone's doing well uh hopefully everyone's doing well in general uh january has been over in general uh january has been over obviously so i'm gonna do these all obviously so i'm gonna do these all month as usual month as usual uh i would say the stock market's been uh i would say the stock market's been really kind of volatile and kind of really kind of volatile and kind of a little nuts a little nuts uh if you really want to hear people in uh if you really want to hear people in my discord have been asking me about my discord have been asking me about whether i should share some of my whether i should share some of my stories including the time where i lost stories including the time where i lost uh uh a lot of money uh let's say half a mil a lot of money uh let's say half a mil or so so i don't know if that's if these or so so i don't know if that's if these things are interesting to you leave it things are interesting to you leave it leave some in the comments below and leave some in the comments below and maybe i'll just do a maybe i'll just do a separate video or something uh today's separate video or something uh today's problem is for some two i guess the problem is for some two i guess the second iteration we'll see what this second iteration we'll see what this iteration is iteration is um um yeah so there's four numbers or four yeah so there's four numbers or four arrays oops what happened uh you're arrays oops what happened uh you're trying to find trying to find four index where they sum to zero okay four index where they sum to zero okay so this isn't that bad so this isn't that bad right so basically there are a couple of right so basically there are a couple of ways you can do it n is equal to 200 ways you can do it n is equal to 200 makes it even makes it even easier to even think about what i can do easier to even think about what i can do is just divide it into two different um is just divide it into two different um set of problems right we can have set of problems right we can have we can put force on we can put force on numbers one and nums two and then on numbers one and nums two and then on number three and nums number three and nums um basically this is becomes um basically this is becomes i guess two sum right is that the one i guess two sum right is that the one where you basically look up where you basically look up um um yeah yeah sorry i'm like my tongue is a little sorry i'm like my tongue is a little tight right now it's a little bit cold tight right now it's a little bit cold but basically what we're doing is we but basically what we're doing is we um i don't know if that's the problem in um i don't know if that's the problem in lead code so i may be making things up lead code so i may be making things up but basically let's say you have but basically let's say you have two different arrays and you're trying two different arrays and you're trying to find out whether um to find out whether um and an element from an array one plus an and an element from an array one plus an element of array two um you know whether element of array two um you know whether they they add to zero right or something they they add to zero right or something like that so basically this is a like that so basically this is a variation of that where instead of variation of that where instead of having two arrays you have four arrays having two arrays you have four arrays but and one way to do it is of course but and one way to do it is of course just dividing them to just dividing them to two different two different parts and then now you could generate parts and then now you could generate um a bigger way um a bigger way two big arrays and then you wonder one two big arrays and then you wonder one the two array algorithm on it so that's the two array algorithm on it so that's basically the way that i would think basically the way that i would think about it um and given that n is equal to about it um and given that n is equal to 200 200 you you one of the quant called big arrays can one of the quant called big arrays can be at most 200 times 2 um so that's be at most 200 times 2 um so that's going to be going to be 40 000 right so that should be good 40 000 right so that should be good enough so let's do that and we have enough so let's do that and we have let's start with let's start with um lookup let's just call it a lookup um lookup let's just call it a lookup table of table of collections.counter and this is of collections.counter and this is of course just um a hash table from mapping an object to an int so in this case we have for x in nums one for y and uh move my keyboard a little bit my my finger's a little bit cold from just coming up from up from outside so yeah so we just do this and that should be good and then now we do another one which is for x and nums uh three for y and numbers four um lookup of x plus y will give us the answer right so then now we have total is equal to zero and then we just add this and that that's uh let's run all the cases that's uh let's run all the cases um yeah basically the idea is that you um yeah basically the idea is that you know know if this x of y exists then if this x of y exists then for every combination we we just sum up for every combination we we just sum up what what was in the previous case and what what was in the previous case and as i said the way that this looks like as i said the way that this looks like you know this is just like a two two you know this is just like a two two away version except for that we generate away version except for that we generate a big version of the two away with these a big version of the two away with these things so let's give it a submit things so let's give it a submit hopefully that's good should be okay i hopefully that's good should be okay i don't know unless i missed oh okay hmm i didn't know that there'll be negative numbers so i think maybe negative but that's awkward huh did not expect but that's awkward huh did not expect this this yikes yikes okay wow what am i doing wrong here that is what that is what wow wow a penny a penny has has has gotten worse than i did twice two has gotten worse than i did twice two years ago years ago but but maybe i'm just a little bit too maybe i'm just a little bit too [Music] [Music] confident confident but hmm okay so that's at least we can get to use our debugging skill why is this wrong no this is such a weird case so what i would the first thing i would do is um you know this is kind of a big case so it it kind of [Music] [Music] let's make a smaller version of the let's make a smaller version of the arrays what i was gonna say but i was arrays what i was gonna say but i was also thinking about just different also thinking about just different things um so basically we're still things um so basically we're still looking for a case where our code is looking for a case where our code is wrong and wrong and yeah i don't think this is that's yeah i don't think this is that's well well do they all have to be the same length do they all have to be the same length oh i didn't realize they all have to be oh i didn't realize they all have to be the same length actually um i was going the same length actually um i was going to analyze it with to analyze it with them independently so uh huh them independently so uh huh that's awkward maybe my signs are wrong so let me check maybe my signs are wrong so let me check the math real quick so we have a plus b the math real quick so we have a plus b plus c plus yeah okay i got the signs plus c plus yeah okay i got the signs wrong is equal to zero so then i was wrong is equal to zero so then i was thinking about that when i was typing it thinking about that when i was typing it but then i was like okay well we worked but then i was like okay well we worked for the example cases and i guess i just for the example cases and i guess i just got a little lucky because now if you got a little lucky because now if you think about it think about it if you move this to the other side if you move this to the other side wow i am like really new today uh this wow i am like really new today uh this is very easy to get wrong so you so that is very easy to get wrong so you so that means that for here means that for here we're incrementing on this and then here we're incrementing on this and then here we need a negative version of this okay we need a negative version of this okay fine fine uh let's give it a spin oops i actually thought about this when i was writing the code but i i guess i just ran the example and looked okay um but i was like this looks a little bit awkward but i guess it could be okay i think i might have confused also a different version of this problem and then i just mixed them in my head um so let's give it a submit now uh okay cool yeah i mean this is exactly what we said and i think if you vote and this is a sin where i think i've talked about this a couple of days ago where sometimes i mean this is a sin that i do again sometimes the ones that you make silly mistakes are are the ones that you've done too many times before because you're just like oh i don't have to test this it's good and then you make a silly mistake because you underestimated your opponent and in this case i think and i i talked about the two away version and and i think if you have really done about it you would have this is very clear that this is wrong right um it's just that i did not think about it for example if the two array version uh let's say you have two arrays you have let's just say a very simple obvious thing you have ten and one and ten into the other well in this case ten plus ten is clearly not zero but because you're looking for ten and a negative ten right so this is a very obvious thing in the two example case but i just was very sloppy because i was rushing for it uh maybe because i don't know why just one of those things um but yeah i was rushing for it and clearly this is not if i had just thought about it a little bit but yeah um let's go with complexity really quick um because n is all the same so actually this is just going to be o of n squared time and and space um and yeah that's pretty much all i have for this one um and you can kind of see this very quickly because this can take at most n square space the n squared time is pretty trivial though because they're two for loops in each case um if you really want to be slightly more constant time efficient you probably should not do it this way because this does generate an entry here in the look-up table so it will probably slow down a little bit so you can have an if statement to make sure that it exists in it first um yeah i mean i was very sloppy whoops i i guess in the past i was not as sloppy yup i was not as sloppy though this code looks exactly the same [Music] yeah i don't know how i explained it last time okay just this time i did the if statement so this is actually better do they change the input i guess so because i can't imagine i wrote i wrote try it i don't know that this is more clearer um really weird but anyway silly mistake hope you avoid it um that's all i have for today stay good stay healthy to good mental health i'll see you soon enough uh hopefully you didn't make a mistake like i did i'll see you
2024-03-22 14:40:32
454
https://i.ytimg.com/vi/N…axresdefault.jpg
454. 4Sum II - Day 3/28 Leetcode February Challenge
wtaCRJ8ZepU
hey hey everybody this is larry this is day 22nd of august hit the uh lego daily day 22nd of august hit the uh lego daily challenge hit the like button subscribe challenge hit the like button subscribe and join me on discord let me know what and join me on discord let me know what you think about today's form uh so power you think about today's form uh so power four is it easy okay that's fine um four is it easy okay that's fine um there are a couple ways you can do it uh there are a couple ways you can do it uh let's see you can do it i mean you can let's see you can do it i mean you can buy just to a lookup table if it's gonna buy just to a lookup table if it's gonna look up here uh and then you know that's look up here uh and then you know that's pretty much it i mean i don't you can pretty much it i mean i don't you can construct a lookup table with you know construct a lookup table with you know in a way um there's also in a way um there's also [Music] yeah i mean i i don't know there's so many ways to do this right uh that it's a little bit silly um yeah i mean it's just basically uh uh uh even number of zeros at the end of the even number of zeros at the end of the binary is that a fun way of doing it i binary is that a fun way of doing it i don't know don't know um uh okay let's just do it the thumb way and then we'll i don't know i'm not really thinking about it right now so and and four four and n mod and n mod four is equal to zero four is equal to zero and we do it by four and that's pretty and we do it by four and that's pretty much it we just return n is equal to one much it we just return n is equal to one um um i mean there are definitely quicker ways i mean there are definitely quicker ways to do it i'm not i don't think i'm gonna to do it i'm not i don't think i'm gonna do it today uh ooh negative numbers so do it today uh ooh negative numbers so this can be wrong this can be wrong are there any no because all the power are there any no because all the power of you know if it's negative then it's always false right is that true zero negative negative 16 negative four because this isn't like the the um to the third power or something this is just whatever right all right let's give it a submit apparently i've got it one three times before so hopefully today kind of i was quite just trying to be too clever today i'm not i'm a little bit lazy today uh yeah hmm okay a lot of silly i was trying to be too clever on a lot of these things but as you can see sometimes just do it in a generic way that works every time that's fine um this is going to be linear uh in this case linear is the number of bits because well you do a right shift twice every time this iteration so that's going to be linear in the number of bits so that's pretty much it really don't really have much to say to this one um we'll play around with this one if i have but today i'm gonna try to um maybe just a little bit later in the video right well it's only a two minute video but i am going to try to do the um brian 75 uh speed one so i'm gonna skip right to that and yeah you could i'll post it on youtube even though they'll be primarily on twitch um and if you watch this a little bit later it's gonna be on youtube anyway at some point so anyway stay good stay healthy to good mental health i'll see y'all later and take care no bonus question today because we're going to do the grind so see you
2024-03-24 10:58:37
342
https://i.ytimg.com/vi/w…axresdefault.jpg
342. Power of Four - Day 22/31 Leetcode August Challenge
WKG_6yh-TMY
hey folks welcome back to another video today if you're looking at question 1673 today if you're looking at question 1673 find the most competitive subsequence find the most competitive subsequence the way we'll be approaching the the way we'll be approaching the solution is by using solution is by using a stack to keep a track of the indices a stack to keep a track of the indices that we'll be using from nouns to that we'll be using from nouns to construct the resulting area construct the resulting area in the process while you're populating in the process while you're populating the stack you'll be checking if all of the stack you'll be checking if all of the numbers the numbers that you are encountering in the numbers that you are encountering in the numbers area in area in in a for loop they are less than what in a for loop they are less than what you've already you've already seen in the stack while maintaining seen in the stack while maintaining the size of the stack to be at least k the size of the stack to be at least k so let's jump right in we need a couple so let's jump right in we need a couple of of uh a few things to set up uh a few things to set up the solution which have we have a stack the solution which have we have a stack right here we have the right here we have the the length of the array and then we have the length of the array and then we have the resultant array itself the resultant array itself and let's initial initialize the for and let's initial initialize the for loop or loop or in i equals zero from i in i equals zero from i less than n i increment and then we have a while loop this while loop is the most important part of the solution which is if while the stack is not empty and numbers of eye while it is less than the top of the stack and we have enough elements to give us k in the end k elements in the end while it is greater than k you will keep popping as soon as it gets out of the while loop you want to check that if the size of the stack is less than k only then you would push that as stack dot push i so just pushing the index not the element itself now once you're done with that for loop you want to populate the resulting array so and i is equal to k minus 1 um i greater than equal to 0 decrement i and then result of i is equal to cool so this populates the resulting cool so this populates the resulting array and in the end you would just array and in the end you would just return return the array itself let's quickly compile the array itself let's quickly compile this to see if it's okay this to see if it's okay the first test case passes everything else passes as well so let's quickly talk about the time and space complexity the time complexity of the entire solution is of n because you're looking uh you have a for loop that goes over all of the all of the numbers in in nums array and then the space complexity uh is okay since you're storing atmos k elements in the stack um and the resulting array as well um all right so that's a solution for this question if you have any questions about the way i solved it let me know in the comments below if there are any other questions that you want me to solve from lead code also let me know in the comments below please don't forget to like share and subscribe i'll see you all in the next
2024-03-20 10:53:52
1,673
https://i.ytimg.com/vi/W…MY/sddefault.jpg
1673. Find the Most Competitive Subsequence (LeetCode)
RWDhAAL8iVQ
foreign [Music] welcome back to my channel I realize I did not do the last few days of the July leap code or Juliet Code challenge recorded because I was traveling so we're starting this on Day 26 which is question number 1870 the minimum speed to arrive on time so when I submitted this would I submit this we had a rough go of it we struggled we did not do great there's definitely stuff I want to revisit and improve upon I really want to try to make this so it's like at least 50 or over on both memory and runtime but we're gonna go over the solution nonetheless because in this solution here um or in this uh kind of metric kpi here um we did get an effective solution eventually after one two three four five six wrong answers so I'm assuming other people have the same problem that I did if they didn't find if you guys are you know looking through this and you're like oh this is a question I'm gonna do um you can do this better I guarantee you but I wanted to go through my solution um and kind of explain it kind of line by line or like group by group or function by function rather so let's go through the question um I'm gonna read the question but I'm not going to go through the examples and constraints so let's jump into it so you are given a floating Point number hour representing the amount of time you have to reach the office to commute to the office you must take n trains in sequential order you are also given an integer array dist of the length n where dist I describes the distance in kilometers to the ice train ride each train can only depart at an integer hour so you need to wait between each train ride for example if the first train takes 1.5 hours you have to wait an additional 0.5 hours before you can depart on the second train uh ride at the two hour mark return the minimum positive integer speed in kilometers per hour that all the trains must travel at for you to reach the office on time or negative one if impossible to be on time tests are generated such that the answer will not exceed 10 to the 7th and hour we'll have at most two digits after the decimal point so then they give you the examples down here and then the constraints so first off I messed it up with kilometers we're not going to talk about it it's part of being American that I do not love um so let's jump into this solution this first area that you see uh here and here this is what comes pre-loaded on the page when you get there and I can show you actually hold so this is what comes I just deleted so this is what comes I just deleted this part because it just felt a little this part because it just felt a little redundant at that time redundant at that time um so as I put that back in here um so as I put that back in here uh we start with seal or like the uh we start with seal or like the ceiling ceiling um which basically defines a helper um which basically defines a helper function seal that Returns the ceiling function seal that Returns the ceiling value of the given number X value of the given number X uh if you can see here uh if you can see here um which is the smallest integer greater um which is the smallest integer greater than or equal to the original X than or equal to the original X so we then go to so we then go to this area where it checks the length this area where it checks the length of the dist or distance list and of the dist or distance list and it's greater than or equal to the hour it's greater than or equal to the hour plus one so if it basically means if if there are more distances to travel then the given time allows so the function Returns the negative one from here to here we initialize two variables left and right left starts at one right is calculated as the ceiling of the maximum value between the maximum distance in dist and dist minus one over one if the hour integer is of the hour is integer um else this this area [Laughter] so um this is essentially setting up an upper Bound for the speed um as speed is divided speed is distance divided by time right so we then go into this area which is a binary search Loop to basically find the minimum speed that we need to travel the distances within a given time so it basically just repeatedly calculates uh the middle point which would be the mid here and the left and right and then it calculates the time required to travel each distance at those given speeds and checks if the total time is less than or um like here um like here and then if the right is bound and then if the right is bound like if it's right bound it updates the like if it's right bound it updates the mid otherwise otherwise mid otherwise otherwise the left it the it's left bound the left it the it's left bound and it's updated to Mid plus one and and it's updated to Mid plus one and then we just return then we just return the the after the loop has been completed the after the loop has been completed the binary search Loop has been completed we binary search Loop has been completed we return the value of left return the value of left um which basically represents the um which basically represents the minimum speed needed to travel the minimum speed needed to travel the distances in a given time distances in a given time so I hope this kind of makes sense so I hope this kind of makes sense basically we just use the binary search basically we just use the binary search code code our binary search approach to find the our binary search approach to find the minimum minimum speed required to travel a given speed required to travel a given distance distance or a set of diff distances within a or a set of diff distances within a specified time specified time so while I didn't do great on the so while I didn't do great on the submission part of this submission part of this I hope I explain the logic okay I know I I hope I explain the logic okay I know I fumbled up a little bit but I really did fumbled up a little bit but I really did struggle with this one and they said it struggle with this one and they said it was I think medium was I think medium but to me it was actually super hard but to me it was actually super hard um and I don't know if other people kind um and I don't know if other people kind of feel the same way but of feel the same way but um if you've done this problem I would um if you've done this problem I would love to know your solution and like just love to know your solution and like just see what you did see what you did um but other than that I have the GitHub um but other than that I have the GitHub repo for all of my leak code Solutions repo for all of my leak code Solutions down in the video description link below down in the video description link below feel free to fork and clone make it feel free to fork and clone make it better make it worse have some fun learn better make it worse have some fun learn something new and that's what this is something new and that's what this is all about so I will probably do another all about so I will probably do another video video later on it's not going to be for some later on it's not going to be for some time where I rework this because I do time where I rework this because I do want to spend some time reworking it want to spend some time reworking it uh just because that's important to me I uh just because that's important to me I really want to do really want to do better my goal is to get as many lead better my goal is to get as many lead code problems done code problems done as I can and then to make them over 50 as I can and then to make them over 50 on runtime and memory just because on runtime and memory just because that's a good challenge for me that's a good challenge for me um so thank you guys for watching and I um so thank you guys for watching and I will see you guys in the next video
2024-03-25 11:28:19
1,870
https://i.ytimg.com/vi_w…Q/sddefault.webp
1870. Minimum Speed to Arrive on Time - JuleetCode Solution in Python! DAY 26
HiaYBeIBL08
That Welcome Back Friends Vtu Solid Problem Welcome Back Friends Vtu Solid Problem 1019 Conspiracy Values ​​From Labels Aa Soft 1019 Conspiracy Values ​​From Labels Aa Soft Human Body Knowing That You Would Create Human Body Knowing That You Would Create List Solution Videos In Java Applets J2 List Solution Videos In Java Applets J2 Interview Related Helpful Videos And Would Interview Related Helpful Videos And Would Greatly Spoil Like Play List Greatly Spoil Like Play List For Liquid Videos Admins Computer For Liquid Videos Admins Computer Science Programming Stop Like Date For Science Programming Stop Like Date For Search Web Result For Search List Dynamic Search Web Result For Search List Dynamic Programming Address Please Check Out To Programming Address Please Check Out To Unit Have Not A Good Example State Will Unit Have Not A Good Example State Will Help You In Preparation Of Love Interview Help You In Preparation Of Love Interview Suspended Please subscribe to the Channel Suspended Please subscribe to the Channel Sau Dus Subscription Is Helpful For This Sau Dus Subscription Is Helpful For This Channel Please Subscribe Now Channel Please Subscribe Now So Let's Look Into So Let's Look Into So Let's Look Into show when it is cut off in items you are you want to interior is values ​​in labels satisfactorily label of the element are values ​​of labels by respectful also given to winters name is wanted news limit choose Data Is Data Is Data Is The Subsidy Gas So This Day And Equal To The Subsidy Gas So This Day And Equal To Na Wanted Na Wanted Director Most Used Limit Items With The Director Most Used Limit Items With The Same Level In S10 Court Subset Is The Sum Same Level In S10 Court Subset Is The Sum Of The Values ​​In The Subject Of The Values ​​In The Subject Returns The Maximum Co Of Subsidies Returns The Maximum Co Of Subsidies 200 Basically A What This Problem Is In 200 Basically A What This Problem Is In Case Case Case 2nd shop right you will have different kind of products in the saunf saunf product will have category light and product will have price should have given his daughter value mins you can contact details like Can consider these Can consider these Can consider these type of the product right and you have to type of the product right and you have to select select slims wanted product from this slims wanted product from this Actually from these products you can see a Actually from these products you can see a disaster products and you have to swim where disaster products and you have to swim where slapped dumini slapped dumini products and you can choose from products and you can choose from any type of the product you can choose any type of the product you can choose Maximum one product for example of Maximum one product for example of Rs 800 for example if you go to shop and buy from Rs 800 for example if you go to shop and buy from English your Baingan T- English your Baingan T- shirt Silai 10315 basically so you can buy shirt Silai 10315 basically so you can buy maximum type of 1431 types from Dasha maximum type of 1431 types from Dasha basically for this product so like that you can consider this basically for this product so like that you can consider this example and example and maximum co light maximum co aa from this maximum co light maximum co aa from this products actor will smith a products actor will smith a selection so let's go selection so let's go for electrification work is for electrification work is plane mode turn on this is the value subscribe value can consider the price for example you can consider subscribe subscribe skin Problem Solved Problems But You Can Consider So What We Want To Do Is Hui Will Create So What We Want To Do Is Hui Will Create Class Products Product And Will Have To Class Products Product And Will Have To The Will Survive And Type And User The Will Survive And Type And User Constructor Against Pass Value And Type Constructor Against Pass Value And Type And What We Want To Do Sol Problem Is And What We Want To Do Sol Problem Is They are going to use so chawal important They are going to use so chawal important data structure Congress priority Q data structure Congress priority Q this is important this is important product where going to that points product object into the priority queue and amarkantak power company tarf but want the priority queue to short products in the decreasing order of the value so decreasing order value means 1501 with there lives and decreasing order If you want to have then it's just If you want to have then it's just If you want to have then it's just consider one example in more detail and will know how the answer Ujjain find right and in other stories the and in other stories the implementation more details so you can consider a implementation more details so you can consider a priority question solved will actually start like priority question solved will actually start like creating a creating a product one by product one by create product and they will put create product and they will put into priority into priority 2051 product means five the value of the 2051 product means five the value of the product and what is the time of Vinod product and what is the time of Vinod this is the value five and type is this is the value five and type is this is the value five and type is Product in Obscurity Q411 Lately Please Not The Products Of Birds In Order To Value Automatically Subscribe And Uric Acid Decreasing I Pin Were Put Into Practice Key And I Pin Were Put Into Practice Key And Torque R Priority Q Automatically List Torque R Priority Q Automatically List Mysura Reddy Mysura Reddy Mysura Reddy is the country with a rich is the country with a rich and one will be the value and three is the type and one will be the value and three is the type of the product of the product 154 start when you read this you can see and your 154 start when you read this you can see and your SIM types of SIM types of SIM types of of same type of product and this other type Sundar three types of product and basically and which can be used only one from each of the product use limit one mins you can choose one from the product and which have to Scores to Win This Scores to Win This Scores to Win This website will have to maximize the value website will have to maximize the value Basically this is a What we will do this will keep you taking Basically this is a What we will do this will keep you taking out the items one by one the out the items one by one the products item one by one from the cube and would use map products item one by one from the cube and would use map to recognize you know how many to recognize you know how many Item Platform In Type Already Item Platform In Type Already Used Keep For The Time Solid Se Besi That Ash Used Keep For The Time Solid Se Besi That Ash Map Map That Is Here To That Is Here To Cost In This Book Will Create A Cost In This Book Will Create A Variable Called S Result 10th Result Variable Called S Result 10th Result Variable Will Hold Over When You Are Doing Just Variable Will Hold Over When You Are Doing Just Returned S Result Hair Soft Will All Returned S Result Hair Soft Will All The The The Entry In That Time Prithvi Already Used One Item Of Type One Right Brothers One Item And This Is Used To Basically News One Of Type-1 Basic Mrityudand Se Used One Recent Member Of This Type Type Sunna Va Member Of This Type Type Sunna Va Surtaan Result Surtaan Result Surtaan Result Left Side Now You Will After Five Know That Already Used One Time From Ghrit Way John Reduce And Used In This One So Will Just Skipping In This Item Loot Already User 5148 Daily Will Call The Other Item Proper -2 Software How To Use -2 Software How To Use -2 Software How To Use Type-2 Suv Marg Wa Type To Have Type-2 Suv Marg Wa Type To Have Used To Watch Now Again Drive Views 521 Used To Watch Now Again Drive Views 521 Vyat Interwar Result Sunna Varidar V5 Plus Vyat Interwar Result Sunna Varidar V5 Plus 3 Nahak And Will Pol Hadith Ne This Item Sudesh 3 Nahak And Will Pol Hadith Ne This Item Sudesh Is Ignorance And Type-2 Inch One * If Is Ignorance And Type-2 Inch One * If Is Ignorance And Type-2 Inch One * If Apna Pariksha Have Used To One So They Ca n't Used To Give Its Then And After That Hui Kaur Ne Is Item Right Vikas Hui Want To Find The Total Key Items You Already Have Found To Items Date Hui Hai Viewers Ne Used to visit this Used to visit this Used to visit this item producer type three and will make an item producer type three and will make an entry improvement shot one to use of type entry improvement shot one to use of type three and toubro adv1 interwar result sun three and toubro adv1 interwar result sun hui have already got another total numbers hui have already got another total numbers quantity right choice 1232 used to five plus quantity right choice 1232 used to five plus one plus one is plus one is not one plus one is plus one is not one plus one is plus one is not move decentralized within normal rate Swadeshi approach will create product class will come in the universe will put products into priority queue in the oldest existing of values ​​are its highest value in first and now used as map 2025 track of how many items you have To update the specified cons, the To update the specified cons, the To update the specified cons, the use limit should not go more than that use limit should not go more than that use limit for the specific type 510 water use limit for the specific type 510 water solution will also give the solution, solution will also give the solution, so you can see here the result so you can see here the result from this study, from this study, just product class and laddu per this is just product class and laddu per this is The profit is yes value and type 8 and in The profit is yes value and type 8 and in a given priority queue products and it a given priority queue products and it is like decreasing order of values ​​will decide which means the basis is like decreasing order of values ​​will decide which means the basis of maths basically of maths basically maximum value will keep on top maximum value will keep on top Android operating near by values ​​and veer Android operating near by values ​​and veer and creating the and creating the and creating the Values ​​and Labels Adventures of the Rings Product * Priority Q Offer Means It Well and the Product Into R Priority Q and Fear After Death Will Create Hes Map and Waste To Organize 1205 Wild Condition Hear Where Is Food Village Items Which Can Items Which Can Items Which Can Find His Nerves And Misery Items For Find His Nerves And Misery Items For Example Research And Prosperity Fortune Should Be Tamed Example Research And Prosperity Fortune Should Be Tamed Basically They Will Katra To Basically They Will Katra To Find The Products In Priority Q Find The Products In Priority Q Software Will Keep All In The Priority Software Will Keep All In The Priority Product Which Gives Team The Highest Value Product Which Gives Team The Highest Value Product Here And You Will Check Product Here And You Will Check Product Here And You Will Check map has not had any entry for the product which has been used in will just edit the result and will adv1 entry into river map life easier to have used one product a for the time basically and will increase it is because now Actually the evening Actually the evening Actually the evening cement high heels life you already have time cement high heels life you already have time entry into them appraised you want to entry into them appraised you want to make and that is class 10th use limit use limit is given to us make and that is class 10th use limit use limit is given to us swim suit be let swim suit be let inside use limit raised and only hui and half inch inside use limit raised and only hui and half inch sir like you all sir like you all sir like you all into map with vansh yaavan more items to use for the time basically 100 villages have one in the map * data previously used items ki raat saunf example1 through use 5451 interview for type vanshu next time when And They Never Seen Before Day You Have To And They Never Seen Before Day You Have To And They Never Seen Before Day You Have To Share With You Like You Can Increase The Share With You Like You Can Increase The Tourist And Type Above Time Tourist And Type Above Time Basically Its Objectives 2 And They Will Basically Its Objectives 2 And They Will Keep In Preventing Aay Whenever They Are Keep In Preventing Aay Whenever They Are Using The Product Right And And Will Return Our Using The Product Right And And Will Return Our Result Which Is The Maximum Result Which Is The Maximum Result Which Is The Maximum a gift from this ride 100% approach to a priority queue and map is time basically some solid state called examples were given hair oil pimples and taken so let's run this is do me sun which aware getting character results year the Submit this code 200 Work code Skating accept with the active per cent and seventh 2% and memory or 90% of the time which is pretty good for this is the way you can solve Rajesh values ​​from labels problem with the help of priority one has map Justice Important To You Know Justice Important To You Know Justice Important To You Know Conflict Classification Product Between 2018 Have Conflict Classification Product Between 2018 Have Two Two Powder Objects For The Product * Powder Objects For The Product * Priority Q Opinion 100 And Thank You Can Priority Q Opinion 100 And Thank You Can Order Productive One And Wherever You Have Order Productive One And Wherever You Have A Balanced And You Are Not Used Limit A Balanced And You Are Not Used Limit Items You Can Keep Adding In Trading Items You Can Keep Adding In Trading Items Items Items basically 133 approach fennel minister at least solutions in java j2ee technology hand dial 100 concrete you know job interview related material video song torch light pen follow and java j2ee developer and you want to you know preparing for interview channel benefits to subscribe this channel to subscribe this channel to subscribe this channel subscription really helps thanks for subscription really helps thanks for watching the video
2024-03-25 17:08:12
1,090
https://i.ytimg.com/vi/H…08/sddefault.jpg
LeetCode 1090 Largest Values From Labels - Google, Amazon, Apple Interview Question.
yfXSBiRp6pA
Hello friends, our today's question is maximum ice cream bars. ice cream bars. This is a medium level question of ateleed code. This is a medium level question of ateleed code. In this question, we will be given a In this question, we will be given a variable named Eric Course, inside which variable named Eric Course, inside which we will have values, we will have values, what will be the cost of ice cream and the second variable will be given what will be the cost of ice cream and the second variable will be given to us. to us. to us. coinc has to buy maximum ice cream and tell them in the return how many maximum ice cream we can buy, then first we will buy the smallest ice cream, so this is our given example, We will give We will give We will give our cost and we will continue to mine the cost from it our cost and we will continue to mine the cost from it one by one. When our coins one by one. When our coins run out, our course will be more. In run out, our course will be more. In case it is more, we will return it to its previous value. case it is more, we will return it to its previous value. And here is our code, And here is our code, inside this, first of all, we have made it short. inside this, first of all, we have made it short. Our course which we did by checking the coin, Our course which we did by checking the coin, if it is small, then in case we called if it is small, then in case we called ice cream, which is ours, we will return the count of the cream, we will ice cream, which is ours, we will return the count of the cream, we will adrevise, we will adrevise, we will increase the count, someone will mine it, increase the count, someone will mine it, this was our code of its time this was our code of its time complexity. complexity. complexity. time complexity will be: Hey sorting time is O and people and here the time complexity because it will be N O N and if we talk about total time complexity then it will be
2024-03-22 18:20:34
1,833
https://i.ytimg.com/vi/y…r9cqphKyYs1t3XFg
Maximum Ice Cream Bars | LeetCode 1833 | Medium | Problem and Code Explanation
U3dj1y6v0TE
hey hey everybody this is Larry this is me doing week four of the uh ni by me doing week four of the uh ni by weekly premium challenge what what am I weekly premium challenge what what am I talking about but you know this problem talking about but you know this problem hit the like button hit the Subscribe hit the like button hit the Subscribe button join me on Discord let me know button join me on Discord let me know what you think about this problem 1660 what you think about this problem 1660 correct a binary tree a problem that I correct a binary tree a problem that I have not done before so I'm excited to have not done before so I'm excited to kind of give it a spin I'm still in Hong kind of give it a spin I'm still in Hong Kong right now just living life I Kong right now just living life I suppose uh yeah follow me on IG though suppose uh yeah follow me on IG though maybe not today maybe tomorrow uh you maybe not today maybe tomorrow uh you have a binary tree with a small def like have a binary tree with a small def like there is exactly one in red node where there is exactly one in red node where it's right child incorrectly points in it's right child incorrectly points in it okay so there's one note that is wrong is it a binary search tree or just regular binary tree we moove this and R node and every oh how do we not I mean oh how do we not I mean uh oh the same depth okay I was going to uh oh the same depth okay I was going to say like why like what would be the rule say like why like what would be the rule for um not using the one instead or like for um not using the one instead or like in this case also the one I suppose okay this is a medium problem though I okay this is a medium problem though I struggled a lot with the last medium on struggled a lot with the last medium on the contest so uh I mean it's not so bad the contest so uh I mean it's not so bad I think it's I think it's just m just m I mean it's going to be breaker search I I mean it's going to be breaker search I mean I'm thinking I was thinking about mean I'm thinking I was thinking about thinking about using some death for thinking about using some death for search thing but Breer search makes the search thing but Breer search makes the most sense because pref search then most sense because pref search then because they on the same depth and this because they on the same depth and this is very specific for this problem um if is very specific for this problem um if they're in the same depth then you visit they're in the same depth then you visit all the notes on the same or not you all the notes on the same or not you visit but you put it on the um on a visit but you put it on the um on a queue to be visited at the same time queue to be visited at the same time right so right so yeah okay yeah I think that should be good so let's get uh uh do they have unique whatever uh the values are unique so we could hash on the values we can also hash on the Node itself directly but it really doesn't matter I suppose so yeah so scene is right and then we can maybe just do right and then we can maybe just do seam. add seam. add of Q iser than zero uh node is equal to Q right um and then basically just C okay for next node in no left no. right right if next node is not none then yeah q. aen uh this isn't quite right yet hang on I know I'm just typing out the what you may say a template code yeah and uh okay yeah if if not not is is in scene then that if not not is is in scene then that means means that uh um that means that this is the that uh um that means that this is the bad node right the node is the bad node bad node right the node is the bad node because that and it is pointing at because that and it is pointing at something that we've already put it into something that we've already put it into the que um so yeah so that means that um no mean I think this is fine none no that right is none I think that's it right and then we can return uh otherwise do we do any do we have to oh I guess we have to return it uh and I guess we return the rout right like what is from node and to no oh that's just indicating the bad nodes I guess um how does the pointer stuff work maybe I um not quite sure let's just do um not quite sure let's just do uh at least a print statement right uh at least a print statement right node. Rue P node right something like node. Rue P node right something like that too lzy to format it okay so it that too lzy to format it okay so it does know that the two is a prad node so does know that the two is a prad node so I have to remove this node and every I have to remove this node and every node and no so not just every node below node and no so not just every node below okay um I mean there a couple ways you okay um I mean there a couple ways you can do it you just look up the parent can do it you just look up the parent which is kind of annoying to set up but which is kind of annoying to set up but not impossible right so uh so yeah so here uh uh I oh I guess it cannot be root because because there's no other node on the same level so then that we node left and then here we left and then here we want and that should be good I want and that should be good I mean now that we actually read the mean now that we actually read the problem correctly I've problem correctly I've been been trying to go too fast lately been been trying to go too fast lately but uh yeah uh okay oh okay yeah that's F that's true I I was trying to remove every child of the parents like I a little bit lazy so I'm wrong about that one but um so yeah um if parent that left you goes to no okay now it should be good I said that like four times so I have I Inspire no confidence but uh but still the idea is right I mean I think that's the um that's one takeway as well uh is that if you structure your your code and your ideas in a good general direction you can the modifications are kind of easy which is why maybe I don't pay attention that much but sometimes it bites me in the butt so I don't know what to tell you about that particular part but for this particular problem it yeah uh I think BFS is the way to go for for the reason that we mentioned is just that um because the the the the thing about pointing at a note at the same depth is the big one uh yeah um that's all I have for this one I don't really have much to say um much more to say uh this is that first oh sorry bre first search so this is going to be uh all of n or and beinging the number of notes those are all and V plus you could say per se but the number of edges is always going to be two times the number of notes at most um for left and right but this is a tree so actually there's only end noes right n minus one or sorry n minus one edges but there's an extra Edge so there's n edges so this other cases it's going to be all of n or linear time and linear space for the Q and the scene I suppose so yeah uh and in case you're wondering the scene um it hashes based on the you could say it's a reference pointer but technically in Pyon is like an ID um thing but uh but as long as you're giving the same uh reference it'll give you the same uh hash so yeah uh that's all I have for this one let me know what you think stay good stay healthy to mental health I'll see youall later and take
2024-03-20 10:18:08
1,660
https://i.ytimg.com/vi/U…axresdefault.jpg
1660. Correct a Binary Tree - Week 4/5 Leetcode October Challenge
CPAWcc78IB4
in this video we will see how to do insertion sort on the elements insertion sort on the elements in a singly linked list so insertion in a singly linked list so insertion sort is a very natural way of doing a sort is a very natural way of doing a sorting sorting so you have let's say a number of cards so you have let's say a number of cards let's say you have let's say you have two four three two four three one so first one is already sorted one so first one is already sorted so you can think of them as a cards so you can think of them as a cards cards having numbers cards having numbers and you have to arrange them in your and you have to arrange them in your hand so you will see that hand so you will see that four is more than two so it's in correct four is more than two so it's in correct position then you come here you see that position then you come here you see that 3 is 3 is less than 4 and more than 2 so you put 3 less than 4 and more than 2 so you put 3 here here between 2 and 4 now it becomes 2 3 4 between 2 and 4 now it becomes 2 3 4 1 then you look at one 1 then you look at one you see that four is more three is more you see that four is more three is more two is more so one should come here two is more so one should come here so you put one here now it becomes one so you put one here now it becomes one two three two three four so you start from first element four so you start from first element in fact second element first is already in fact second element first is already sorted and sorted and if this is current element then before if this is current element then before this everything is sorted this everything is sorted and you want to put this current at and you want to put this current at correct position correct position and so after each step we are making and so after each step we are making progress by progress by one step one more element is sorted so one step one more element is sorted so we will do it n times we will do it n times and searching can take o of and searching can take o of k times if we are at the kth step so 1 k times if we are at the kth step so 1 plus 2 plus plus 2 plus 3 plus all the way up to n or n minus 1 3 plus all the way up to n or n minus 1 it doesn't matter so time is it doesn't matter so time is of the order of n square and space of the order of n square and space o of 1 we will just keep track of a few o of 1 we will just keep track of a few node pointers to keep track of the node pointers to keep track of the current node previous node current node previous node and also uh beginning of the list and also uh beginning of the list so how we can do it in the list again so how we can do it in the list again it's very simple it's very simple let's take an example let's say we have let's take an example let's say we have 3 3 2 1 2 1 4 and make them a linked list 4 and make them a linked list so next of three is 2 1 4 so next of three is 2 1 4 and null and we are given the head and null and we are given the head pointer pointer so this is already sorted next so we so this is already sorted next so we initialize current initialize current to this one and previous here previous to this one and previous here previous is null so you can create is null so you can create a dummy node and make its next point to a dummy node and make its next point to head head so that way previous will also be valid so that way previous will also be valid always and this will also denote that always and this will also denote that we have to search after previous so we have to search after previous so current is sorted current is sorted so what we do we look at next of current so what we do we look at next of current if next of current is more than current if next of current is more than current so if next so if next is more than current then do nothing is more than current then do nothing we don't have to do anything this is we don't have to do anything this is till this point it sorted till this point it sorted next of current is also more so next of current is also more so till this point it sorted so nothing to till this point it sorted so nothing to be done here be done here just current equal to current just current equal to current next else next else that is next is less it should be less that is next is less it should be less and not equal to i think the elements and not equal to i think the elements are are unique so if next is less next is less than current then it means it's not sorted because next should be more so we will find the correct position for next so let me draw in yellow so we have to insert this next at correct position before current less than current so current is more less than current so current is more than next than next so there are a few elements here current so there are a few elements here current is here is here next is here and next is next is here and next is our current is more than next so we our current is more than next so we start from here start from here we check if it's more than next we check if it's more than next we insert before it if it's less than we insert before it if it's less than next we look for next one next we look for next one next one so till these are less than next one so till these are less than next next we keep searching once we find an we keep searching once we find an element which is more than next element which is more than next we insert next before that and what we we insert next before that and what we will need to insert that will need to insert that so there is this element its next is so there is this element its next is this one so we cast this element and we change this next pointer to point to this n and its next point to this one so if the moment we change this next pointer we lose track of this one that's why we cast it into some temp node and we will see all of this in the code then we can change this to next also some some node will be next of next so this now is gone here so this should point here the next of current so current next should be equal to current next next and then the next of this one should point to this one so these three pointer exchanges are required and we will call it start because that is the place where search will start so this is the dummy node start and its next is head and we initialize previous to start and current to head and we start searching after previous and once we find it previous is here so till previous uh previous next is less than current next current next is nothing but the previous equal to previous next so we previous equal to previous next so we keep incrementing previous keep incrementing previous so when previous is here previous next so when previous is here previous next is this one and we are inserting between previous and previous next and once we have inserted we reset previous to beginning so that next time also we search from beginning and not from here start equal to new start equal to new list node and it's list node and it's next equal to head next equal to head also current is initialized to head also current is initialized to head and previous is initialized to start and previous is initialized to start while current is there next then only we need to insert so this is the main insertion step in the insertion sort else we don't need to do anything it's already in the correct order now let's fill this insertion step this now let's fill this insertion step this is the main part is the main part so we need to find the correct position so we need to find the correct position for this current next for this current next so remember that previous is here so we so remember that previous is here so we will be comparing will be comparing always next of previous to this current always next of previous to this current next next and if it's less we keep incrementing and if it's less we keep incrementing and once and once next of previous is more we know that next of previous is more we know that we need to insert this current next we need to insert this current next after previous after previous so this thing between previous and previous next we and now when this loop terminates we and now when this loop terminates we have found the correct place for have found the correct place for current next which is between previous current next which is between previous and previous next and previous next so let's do the pointer exchanges so let's do the pointer exchanges so we save this this node previous next into a temporary variable because this now we can change this pointer so this previous next is current next and current next should be current next next this thing so this now is gone so this current next should be current next next that is this and previous next next previous next is now the node that we inserted and its next should be the temp whatever was the next of previous and we are done now we will reset the previous to start so that for the next element again it starts from beginning and not that point onwards finally we need to return start and let's see if we have done everything so this case seems fine and the solution is accepted and if we look at the time taken it's here 16 millisecond that is we are roughly better than 99 percent of all the submissions so we are in great shape now let's do the same thing in java solution is also accepted finally java solution is also accepted finally we will do it in python 3.
2024-03-21 12:55:07
147
https://i.ytimg.com/vi_w….webp?v=61b98223
Insertion Sort List | LeetCode 147 | C++, Java, Python
78jJYILq0Jc
the hacker heap in this video we will look into this problem serialize and deserialize binary tree from lead code the problem is if given a tree we need to serialize the tree into this string and if given a string we need to create a tree and return it back so before we start please like and subscribe to the channel because YouTube won't show it to other people if you didn't like the video so let's look into how actually this works this is actually pretty simple even though it's defined as an hard problem it's pretty straightforward let me explain how to do it so what are the properties of a binary tree in node can have two children left and right or a node can have one child either left or right or it can have no children at all no children that is it's a leaf node so in it can have two children or a node can have left or right or it can be a non load so these are three checks we need to do when we are trying to serialize it so let's look into this example so let's consider this tree which have a couple five so if given this read the output five so if given this read the output should be one two three and coming to should be one two three and coming to four and since there is no right child four and since there is no right child for two we will pass and null and when for two we will pass and null and when it comes to 3 there is no less child for it comes to 3 there is no less child for three so we will pass a null and then three so we will pass a null and then five the string should be this the five the string should be this the output should be this so when you look output should be this so when you look closely into that did you find anything closely into that did you find anything similar so basically what we are doing similar so basically what we are doing is a breadth-first search first we are is a breadth-first search first we are going through the root and then its going through the root and then its children and then its children so children and then its children so basically if a node doesn't have either basically if a node doesn't have either left or right we are just keeping it as left or right we are just keeping it as null if you want to look into the null if you want to look into the pseudocode it would be like up we will pseudocode it would be like up we will take a queue here is this tip whenever take a queue here is this tip whenever you are doing a breadth-first search you are doing a breadth-first search always think of a queue because that's always think of a queue because that's how you do a breadth-first search you how you do a breadth-first search you keep the nodes and then the tail nodes keep the nodes and then the tail nodes and then there chilling out so you will and then there chilling out so you will get the list in order so we will take get the list in order so we will take queue and we will push the root into Q queue and we will push the root into Q so we will loop that queue while the so we will loop that queue while the queue is not empty what we will do we queue is not empty what we will do we will pop the node pop we will name it as will pop the node pop we will name it as like current node and we will see if it like current node and we will see if it has any children has any children so if it has a left child and it doesn't so if it has a left child and it doesn't have a right child we will push the left have a right child we will push the left child value and for the right shell we child value and for the right shell we will push now so that's how we do it and will push now so that's how we do it and we want to continue this loop or until we want to continue this loop or until the queue is empty so we will have an the queue is empty so we will have an inner loop where we will check the queue inner loop where we will check the queue size so for each level we will have that size so for each level we will have that node so when it comes here when it node so when it comes here when it initially comes here it is at a initially comes here it is at a level-one so it will have one node and level-one so it will have one node and we will look through all the nodes in we will look through all the nodes in that level and then push the nodes later that level and then push the nodes later on on so when it comes to level 2 we will have so when it comes to level 2 we will have two nodes and when it comes to level 3 two nodes and when it comes to level 3 we will have two nodes so that we know we will have two nodes so that we know they are at what level and we know how they are at what level and we know how many elements should be there in that many elements should be there in that level in the first level there is only level in the first level there is only one element in the second level there one element in the second level there are two elements and in third level we are two elements and in third level we need to have four elements but since need to have four elements but since there are only two we know that we need there are only two we know that we need to add null value so let's go back and to add null value so let's go back and fill up this serialize function so now fill up this serialize function so now I'm here back at a late code so the I'm here back at a late code so the serialize function as we discussed we serialize function as we discussed we will have AQ define which will take as a will have AQ define which will take as a three node list as I said we will offer three node list as I said we will offer the root into this while queue is empty the root into this while queue is empty what we need to do is we'll get the size what we need to do is we'll get the size of the cube int size physical to Q dot of the cube int size physical to Q dot size so we got the size now we will we size so we got the size now we will we have to append all the nodes in the have to append all the nodes in the particular level in order so I will look particular level in order so I will look through all the nodes in that particular through all the nodes in that particular level level Halas and the size plus every time I Halas and the size plus every time I will pop a node which is a current node will pop a node which is a current node Q dot poll that will give me the current Q dot poll that will give me the current node so now what we need to do if the node so now what we need to do if the current node is equal to null as we current node is equal to null as we discussed so we also need to have like a discussed so we also need to have like a string builder which we will append to string builder which we will append to that P dot append off now my comma else what we need to do we need to push the left and right node to the queue first we need to append the value append off dot Val plus the same thing come up and we need to push it to the queue the current node dot left and right that's it so once we are out of this so we just need to return that string as V dot to string but look at this we are adding a comma at the end so the last element would have a comma so we need to remove that so we would set the size dot set lint off as V dot V dot length minus 1 dot 2 string that is it so now we will see how to deserialize a given string so for this utilization you'll be given a string like this 1 2 3 4 null comma null comma 5 and we need to generate a tree like this 1 4 & 5 basically these two will be null the right child for 2 and left jail for 3 are basically null so how do we do that so given a string the first step the step 1 is to split the string split the string so we do it by a start split of comma so that will give you an array like this one two three four null null and five so now we got this array how to do it so we know the first element in the array is the root so what we do we will create the node and set it as a root so tree node root is equal to new tree node and past the value one basically s of zero so now we got the new similar to the last problem we will define a queue and put this root node first and we will do the same thing but this time we will be inserting at different levels how do we do that let me explain the algorithm a little better so now we have this array we just talked this is the root node that's another Q will have the root node one right now similar to the last time while Q not empty so while Q not empty so we already got the root node one so we got the tree node now we need to insert the rest of the nodes so now what you do is I will loop through from the first element since we already had the root element so index I is equal to 1 I less than length I plus plus what I would do is pop the current element let's say it as a parent and we will pop it out from the QQ dot pop so now this is gone what we will do is s of I not equal to null we need to add that element first to the parent element as a left child so what we do like we will create a tree node new node tree node with a safai and parent dot left is equal to this new node and we would do increment the I now we got the left child we just need to check the right child if s off I not equal to null we will add it to the tree node and also we need to add to the queue queue dot add off this node we will create node and where n dot at fair and dot right basically will be this new node and again we will push back to the queue so at this time what we will have is two and three similarly we will come back and pick up two and we will add four as a left child and we will do plus plus I this time it's null we won't be adding it and then we will pop three since it is null we won't be adding it with the left child and when we do plus plus I it will go to this last index now it's fie we will add as a fourth child that's it so this two will be gone and we will pop for witch and basically the length of the array is done we won't be doing anything and we will return this root element that's it let's go ahead and cut it out so as I said the first step is to split split at comma good now we need to create a tree node root is equal to new [Music] remember this is a string so we need to your arse end of s of zero if data is your arse end of s of zero if data is equal to empty string we need to check equal to empty string we need to check we need to return null because there we need to return null because there won't be a tree at all now we got is won't be a tree at all now we got is here we will create this Q of three node going to list my bad first we'll add he got it here so wall is empty not he got it here so wall is empty not empty now we need to loop here for I is empty now we need to loop here for I is equal to 1 I less then I start length I equal to 1 I less then I start length I click this go now I will pop the parent click this go now I will pop the parent node if s of I not equal to null node if s of I not equal to null what I do is renewed just copy this we what I do is renewed just copy this we left s of hi and I need to add parent left s of hi and I need to add parent daughter left it's equal to left daughter left it's equal to left let me let chain so there won't be any let me let chain so there won't be any confusion that's child u dot add of confusion that's child u dot add of change already once we are out of here change already once we are out of here we will increment the I is I we will increment the I is I I'm not equal to null what we will do is we know right child is equal to me they can copy it sorry my bad child that's why I'm giving dot right right child that is it and Q dot a hat off watch a so once we are out of this loop let's return the root that's it let's go ahead and run it Ward cannot BT difference okay okay what's this string cannot be converted what's this string cannot be converted to bully and did I is equal to this Oh double oh sorry my bad it's a Q dot pole or remove you can use either of it not pop let's move this and try to do this if oh oh I think since we are adding a space here I think that's the problem I am adding an extra space I believe no comma let me see if it works there you go it worked let's go ahead and submit it and see if it works yeah it worked so what really happened was I give an extra space here when I am yeah extra space here when I try to append this to the stringbuilder that's caused the issue other than that it's good so pretty much this is it thanks for watching I hope I explained it clearly please like and subscribe to this channel hacker keeper I will be posting more code problems jolly little stuff thank you
2024-03-22 14:33:56
297
https://i.ytimg.com/vi/7…axresdefault.jpg
Leetcode 297 Serialize and Deserialize Binary Tree Java | Interview Prep
M6QJeFhFiPw
Ki Sachin Questions Likh Phanda Medium Bat And Its Most Stones Remove vid0 And Column Most Stones Remove vid0 And Column Soen Vivah Birds Play In The World With Soen Vivah Birds Play In The World With A Bunch Of Faults And Mid Point Meghvansh Newly A Bunch Of Faults And Mid Point Meghvansh Newly Married Stones Problem And Here Removing The Room With Date Sheet 2018 Amazing 10 Amazing 10 Amazing 10 Sharing Simro So They Can Move One To The Sharing Simro So They Can Move One To The Place And Width Remove One Liners Place And Width Remove One Liners That Som Vihar To Return Largest Possible That Som Vihar To Return Largest Possible Number Of But Can Help Only That If Studio Mind Pants Off White That If Studio Mind Pants Off White Polling Staff Is Not Advised To 9 4 Polling Staff Is Not Advised To 9 4 Picture Something On Picture Something On A live webcast begins you can't stop A live webcast begins you can't stop 1000 white happens 1000 white happens that roman's fight little that roman's fight little eyes eyes after word well center flight share next after word well center flight share next oil 2019 option problem is jhal jhal jhal lord will find wutz jhal jhal Prominent academic Prominent academic Prominent academic waterloo ki a jhal jhal waterloo ki a jhal jhal ki vipin tha ok so you can plot but video.com ki loot management ko forced ho 2014 bhi likh do 2014 bhi likh do ki recording in the apps point like button Apne feet ko hua hua Next Paneer Welcome to Go Loot Muslim's Mathur at game on Muslim's Mathur at game on ab se ka ab se ka dansh object's mobile Jhal show Vihar Vriksha Stones with first and show Vihar Vriksha Stones with first and best source Simru and Idhar film column we raw best source Simru and Idhar film column we raw And bold since loop a lot of mission And bold since loop a lot of mission And bold since loop a lot of mission simro gas on simro gas on that if this account statement is that if this account statement is a secular country interactions were a secular country interactions were recent ok just fun their forced recent ok just fun their forced sonukumar two steps taken sonukumar two steps taken that soham important vacancy lekar 0001 that soham important vacancy lekar 0001 president m rosso nuvvu and idli liquid also digit for two also digit for two also digit for two to either oppose Vihar-1 movies and there is no vacancy but 251 Shukar Maan Tu Sareen SIM Calling Facility Nuvvu Updated On Ek Shaap Main Anil Kumar Jasvir Cutting Ka Number Four In English Vighna Different Reasons Which Can Achieve Possible Number Achieve Possible Number Achieve Possible Number Maximum Volume Maximum Number Of Maximum Volume Maximum Number Of British Rule 10 Different Countries Like British Rule 10 Different Countries Like Subscribe And Take Good Yes So 19 Minutes Ago Subscribe And Take Good Yes So 19 Minutes Ago That Vax X X X Pet Or Related To Or Cut Stress And Country Why Lax You Did Or Cut Stress And Country Why Lax You Did S Wallpaper Or Loot Loot from this you zoom out to buy a judgment from this you zoom out to buy a judgment Navodaya Intermediate Verification ki sandesh ko Navodaya Intermediate Verification ki sandesh ko energy mite just a question is that was energy mite just a question is that was not reduced from zemtv110 not reduced from zemtv110 that we developed in delete that we developed in delete scientific traditional a hua tha every problem share no not every problem share no not subscribe The Side of the The Side of the The Side of the White Tiger The Amazing spider-man is subject to that obscene dancing list or that obscene dancing list or that Sudhir Vihar To Make Largest Possible that Sudhir Vihar To Make Largest Possible Number And Smooth Secretary Can Be Reduced Number And Smooth Secretary Can Be Reduced In The Middle That Effect Tried To Remove 10 Followers 1000 Results Max Plank Whose Noida And Exam Slap From Noida Organizations To Find The Note Which Will Give You That Understanding Ladakh Lake Issue Cricketer Graph To Begusarai When Connected To It ZuluTrade Test Cases Can Predict What Will Happen In The Logic Is Loot Loot Thanks So How To Select Which One Thanks So How To Select Which One Thanks So How To Select Which One remove a request from animals do not want to see YouTube channel YouTube channel that this hormone balance qualification that this hormone balance qualification on Samsung is based on the condition in on Samsung is based on the condition in porn tasv porn tasv 15909 friends exposed and of the you say 15909 friends exposed and of the you say not based on not based on not based on number 2017 problem you can you are off world 500 index festival of ireland one and a half inch of the island which is neetu's one of the best president camp remove suicide give vote to carry mode on this ireland limit to give Can Say Thanks For This Point 12th Can Say Thanks For This Point 12th Can Say Thanks For This Point 12th Maths 10th Who Maths 10th Who Is The Current National Exactly Is The Current National Exactly Bluetooth Plot Know How Do You Do Secretary Who Is Bluetooth Plot Know How Do You Do Secretary Who Is CB Editing List Abhi Can Have Wave Network Don't Want To Hand Over Love Life To Na Yourself Youtube Live One Mistake To remove with hidden cam hidden To remove with hidden cam hidden To remove with hidden cam hidden cam intermediate state weather report subscribe now to remove the phone on do loot should make that possible flight fare no no no no no you all subscribe subscribe and subscribe the Channel subscribe our Lord is provider type were engaged at the metro station 200 test very side contact number of sa actress and tours slum free city it is to ghagra hua hai how to death by students from the first pahal inventive vision election sure that suck oh god this question invest to so they can In these In these In these activities in education providers and activities in education providers and on on that Vinod Deshwal guava account after size verma a that Navratri rituals to friends if any Navratri rituals to friends if any people till fast 100 other turn on do problem people till fast 100 other turn on do problem this you sweet children Mohit reduce this you sweet children Mohit reduce account temperature is below zero account temperature is below zero hai avni computer hai avni computer hai avni computer problem video delete is to shampoo member absorbing one drops two more white its side earth the option return to text that this birthday fee no day not cast and were past two days after writing on Se Vihar Terminal Dushwaar Hai Se Vihar Terminal Dushwaar Hai Se Vihar Terminal Dushwaar Hai Loot Pathak Kam Hair Spa Loot Pathak Kam Hair Spa Central Central Tum Kaise Ho Tum Kaise Ho Ki Kinnar Remove Chehra Chandramukh Hai Loot Loot Jhali Ki Pyaaz Tomato Motorcycle Om Shivpuri Gwalior Mein Hai Om Shivpuri Gwalior Mein Hai Bluetooth And Akash Kushwaha I Want To Make Bluetooth And Akash Kushwaha I Want To Make A Gajendra Posted In The Form Of A Gajendra Posted In The Form Of A Gajendra Posted In The Form Of Line The Effigy Start From The Left And Started Running One By One Will Be Left With The Last Time Like This Hai Re Ke Bachai De Vriksha Something In Between Vaikunth Second And Third Looters Ne Google Google 202 Buddha Corner 202 Buddha Corner 202 Buddha Corner Laptop Price Churna Picture One By One In An All In One Day Is Either Thank You So You Already Know That In This Particular Ireland One Know Dealer Address All The Best Torch Light Decoration Number Of Ireland Russell Beach Dutt Beach Dutt Beach Dutt Information Yadav Subscribe 108 Why Not That Under What Why Not That Under What Will Just For The Top And How To Find The Number Mode On In Will Just For The Top And How To Find The Number Mode On In Remote Definition Of State Water Family Remote Definition Of State Water Family Discussion Subscribe Note Remote And Liquid Discussion Subscribe Note Remote And Liquid Crystal Subscribe Number Crystal Subscribe Number Crystal Subscribe Number A Person From Water Portal This Is What We Apply For Adult Flu Ward Amazon App A File In The Lap Of Way Not Subscribe To Describe The Order Of The Giver That 501 y1 More Different Directions And How Basically Happened How Basically Happened Bhojpuri video editing is becoming the last one from the files, it's Bhojpuri video editing is becoming the last one from the files, it's node, aap node, aap ki kya koi faad aur hui hai ki kya koi faad aur hui hai liye 589 madhya liye 589 madhya Jai ​​Hind solution tabs, one more approach, Jai ​​Hind solution tabs, one more approach, students union phase, students union phase, cat, this side, liquid cooling clip, want toe cat, this side, liquid cooling clip, want toe control inflation, tomato Twenty20 This version of the question on you is all the This version of the question on you is all the This version of the question on you is all the time is of this What do you can locate the time is of this What do you can locate the Indian Idol of Lord Make a decision compare Indian Idol of Lord Make a decision compare to start your browser either has in tamil to start your browser either has in tamil love you know that you are living in a production Dushman Dushman Is Channel Is Channel Is Channel 133 Proof of Birth Can They Convert Into 133 Proof of Birth Can They Convert Into Indirect Version Just But Problem Is Indirect Version Just But Problem Is I Want Divorce In Between You How To Write I Want Divorce In Between You How To Write Is Din Sadhak Can Be A Powerhouse Loot And Is Din Sadhak Can Be A Powerhouse Loot And Life Never Appeared On ALook A A New Sanaya 555 Loot Jaan Loot Jaan Loot [ Sanaya 555 Loot Jaan Loot Jaan Loot [ Praise] Has taken Find the Length of the Island of Loot This person has completed in Haryana in the world Soon I have definitely Loot This person has completed in Haryana in the world Soon I have definitely given given Sorry on a single line Sorry on a single line Sorry on a single line star somdev intuitive volume off but how will create dalenge ayapar ki music] ki a twitter sonia song tak twitter achcha source it nikla idhar aa This link police arrests of single bank This link police arrests of single bank This link police arrests of single bank fixed ofton in and ok adapter connection fixed ofton in and ok adapter connection old collection of noble definitely rate items from her all this from the old collection of noble definitely rate items from her all this from the best film and best film and best modified and did not have any soul jhalar bhi type of skin kabir team arijit singh And give them in any And give them in any And give them in any direction angry birds and came back from head to direction angry birds and came back from head to hearing these apps and liquid hearing these apps and liquid list a list a that last week underrated tasted won ki pm mix hai main abhi pm mix hai main abhi khana fab flash lights ko birthday wish tuesday a normal busy Better understand what is the Better understand what is the Better understand what is the problem into a single place of the like disgusting thing with friend disgusting thing with friend element thought in between tits set2 element thought in between tits set2 represents all kind of his cosmic soul witch usually represents all kind of his cosmic soul witch usually vikram chauhan and liquid these vikram chauhan and liquid these two two ajay ko ajay ko office loot So debt questions and if try slim So debt questions and if try slim So debt questions and if try slim up last moment 158 ​​so ruk authority can better splendor fool you should know are loot jhal pregnant chaugne waali hai jhal pregnant chaugne waali hai aap sensible ho me ka sex mein loop giver
2024-03-25 12:05:47
947
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode [947] Most Stones Removed with Same Row or Column
EwU7lV1Tpxw
Hello Hello friends, we are going to talk in today's video, if there is any problem, unique vansh if there is any problem, unique vansh only RTO, then one of my recommendations would be to do only RTO, then one of my recommendations would be to do female tuning - part-10, female tuning - part-10, you will get very good training, you will get very good training, why should you take this problem, you will come to solve this problem. why should you take this problem, you will come to solve this problem. why should you take this problem, you will come to solve this problem. very good that we have become with the country. Okay, now let's talk about the problem. What entries do I give you and give you the return of the whole structure and unique vestiges. It is okay that through notes of unique values ​​from one to two. It is okay and there are bacterial properties. Any particular note has a property in it, its left rally will be less than the value of the first root note and the life will increase, it will feel the current and all this thing will be subscribed, If If you want, then you like it very much, if you have a that this five different play list will that this five different play list will make your white different way 28 your make your white different way 28 your porn union. Okay, so don't forget to porn union. Okay, so don't forget to subscribe. If you have a problem, if subscribe. If you have a problem, if subscribe. If you have a problem, if you have to tell the numbers, then it should be simple. If you want to give you the numbers only like this, then the numbers are possible, then whatever number you are getting from the formula, then the entry is your debit * and relaxation witch one to three, if it is circular difficulty then it will become white for you, Where did it come from here? This 12345 Where did it come from here? This 12345 Where did it come from here? This 12345 is fine, so if you wanted to tell the number, then is fine, so if you wanted to tell the number, then for updates, you can tell the number of Mangalsutra, for updates, you can tell the number of Mangalsutra, but here the number is here, you have to tell the number. Is it okay to give fruits also in possible years, then it is 20. tell the number. Is it okay to give fruits also in possible years, then it is 20. tell the number. Is it okay to give fruits also in possible years, then it is 20. thing is sure that you have to explore the significance, I have to give every note a chance to become a hang out, only then you will be able to block it as a frequent one, this is why first of all I should have done one court, okay If given a chance to build a road, If given a chance to build a road, If given a chance to build a road, is there any leave given for it? If is there any leave given for it? If you move in the other direction, then you can look at the validity of 12345 ticket, travel train and such things. This is the cream, look at the validity of 12345 ticket, travel train and such things. This is the cream, this is what it is in one night, but there can be many meanings this is what it is in one night, but there can be many meanings here. inside this if you give a chance to become one then her inside this if you give a chance to become one then her future future husband 452 323 ok now in this you need to husband 452 323 ok now in this you need to click here ok click here ok subscribe Raghavi chanting penance there is no chance and free free free See this here are the four and five after that this film is a this thing edit this profile thing here I have taken cup of sugar but on one side of this the person from West Indies its quantity will be the reel The file will be fine in life The file will be fine in life The file will be fine in life and for that we will have four. Okay, and for that we will have four. Okay, so see when you make it, whenever you make it, there will be so see when you make it, whenever you make it, there will be two ways of joining it. two ways of joining it. Episode 345 You have made such a regiment Episode 345 You have made such a regiment that means when all that is dear to you will become that means when all that is dear to you will become two. two. two. such a bank, this two is okay, so that you, her, I, her body, for the return, then this is done, three, four, for 5 to 10 minutes and these two MP3s, okay, this is five entry, then There is any note on its right There is any note on its right There is any note on its right which was published in the fort itself but this is next to you, now we will fix it from now on, now it will be in the school but here you will get two structures on irrigated, Bar you will keep the to-do Bar you will keep the to-do Bar you will keep the to-do in the center and but what will you keep slaughter is in the center and but what will you keep slaughter is okay and in this 350 is the same arrangement okay and in this 350 is the same arrangement which we have initially fatal free and and 51 this is which we have initially fatal free and and 51 this is done then it can be your one share like share 123 in to is piled 1,000 Kiran Written Two Reigns Wave Raw To 1,000 Kiran Written Two Reigns Wave Raw To 1,000 Kiran Written Two Reigns Wave Raw To Family And Request To Subscribe This Is For Your Decisions Next Destination What To Do Apart From Okay Let's Turn Off The Alarm That Brother Now Finally Meet So One One One Two Okay, it is going to be played in right, it Two Okay, it is going to be played in right, it was full face, so there is valentine point in the right, now it is was full face, so there is valentine point in the right, now it is one two, it is okay if you change it, then you one two, it is okay if you change it, then you will do the antioxidant one, here will do the antioxidant one, here if you keep it one, then the right method will be done, if you keep it one, then the right method will be done, okay and if okay and if okay and if remember, then it is fine if you arrange it in front of the other and if you arrange four similarly then you can arrange it like this and it is the right method, your file is fine If you have kept your four in this fort, If you have kept your four in this fort, If you have kept your four in this fort, this is your lamp on the left, this is your lamp on the left, then means you are here on what then means you are here on what occasion, how many more Indian occasion, how many more Indian festivals are there, what are the writing and editing restrictions, festivals are there, what are the writing and editing restrictions, how many structures are you going to get from this and your marks, how how many structures are you going to get from this and your marks, how many units are you getting from here. many units are you getting from here. many units are you getting from here. is fine in the structure, out of the four, on the left, use all the switches of Pride for all customers. What am I trying to say in this, like if yours, it is free, wash it and you had kept it as one and this What can you keep in the right What can you keep in the right What can you keep in the right issue four and five Misri, the issue four and five Misri, the omen is already good, now left, there omen is already good, now left, there were two things in the left, first kept 12345, now were two things in the left, first kept 12345, now what will you keep for any thing, you will what will you keep for any thing, you will keep Rafale in this way, file 4th Meghvar's keep Rafale in this way, file 4th Meghvar's left. left. left. you will multiply this repeat a little, like for Elephant, the thing is repeated twice, in such a place, you will not write it as economic and here, if you write 2nd, then even after dropping it, you will repeat the thing twice. How did this happen four times, this happened once and this on 3821, if you buy one and a half or two like this, then by paying ₹ 5000, you can see how this charger is made. 1234 That is why the comments that miss left or right are So what will we do, we will So what will we do, we will So what will we do, we will do it in the entire property sector, we will do it in the entire property sector, we will give every person a chance to become this route and as give every person a chance to become this route and as many possible guests will be able to become in personal shirt many possible guests will be able to become in personal shirt that figure like this combination, uncle that figure like this combination, uncle can get such a combination, Amritsar is this can get such a combination, Amritsar is this affair, is anyone from there? affair, is anyone from there? affair, is anyone from there? can do this for ₹ 5, this was this thing here, how about it in the office for ₹ 5, then we will add, okay, that's why when it was free, one such thing became a fashion in his two years It will be like this, that's why it's okay friend, It will be like this, that's why it's okay friend, It will be like this, that's why it's okay friend, repeat a little like the means, first of all you have to repeat a little like the means, first of all you have to work for the root, seal is work for the root, seal is seen here, first we are worthy of working for the root, you are the one, then seen here, first we are worthy of working for the root, you are the one, then you first check you first check what all he has got in the light, then left it. what all he has got in the light, then left it. what all he has got in the light, then left it. is value and for you, family and even and right, now in the last problem I used to do verification on vegetable option, Malik used to wash one thing, one thing puts you in the test, first heaven for your form or you You call for them. You call for them. You call for them. Okay, while doing Jaishree, whatever Okay, while doing Jaishree, whatever number of codes, number of codes, whatever orientations are possible in the medical select, this loop whatever orientations are possible in the medical select, this loop thing and with the right maturity, we will thing and with the right maturity, we will meditate on both sides of the animals. Where do you come from? meditate on both sides of the animals. Where do you come from? Please use your code. Please use your code. Please use your code. court to know how this thing will be cut in the friend circle, so if you still face a problem at this time, then definitely tell me, I will definitely come and will try to tell you in a better way, if it is okay through the account, then we will Diabetes did not add much to you Diabetes did not add much to you Diabetes did not add much to you but most importantly what should you do? but most importantly what should you do? We have not issued article to the prince on April Kaushalya We have not issued article to the prince on April Kaushalya Orange Section 120BC. Orange Section 120BC. My tablet has been decided that what is the name of the government. My tablet has been decided that what is the name of the government. Editor-in-Chief. Understanding half of the ads. If you are according to That your more than one is fine, come and That your more than one is fine, come and That your more than one is fine, come and you fold it and divide it, you fold it and divide it, subscribe Alinagar, subscribe for the right, subscribe Alinagar, subscribe for the right, Nazul cream is coming home, Nazul cream is coming home, operators pomegranate gets activated, then it will operators pomegranate gets activated, then it will not work in Edison left, which is your not work in Edison left, which is your Rangers subscribe. Rangers subscribe. Rangers subscribe. brightness, then how will it work? Brother, come on stuff, you are the first one to come and go to fiber, that is why I thought that if you want to go to fiber and not to go through water, then you must have become an editor for mixer too. There our channel will come C means like when you like this is our brisbane take so be at the end of all of these so that you become the season here but what happened at the end of yours is at the end there is a null value here from Criminal Rally If the phone is for the If the phone is for the If the phone is for the rights of the child, then what is the last rights of the child, then what is the last tap? Okay, if it is right for child development, then tap? Okay, if it is right for child development, then this tap will move the condition for the contest. this tap will move the condition for the contest. So here, what will we do now? So here, what will we do now? We will not keep the channel point here, We will not keep the channel point here, do the video channel. do the video channel. do the video channel. number of fruits, whatever they are, now we will see, if you are busy like this, if you have only one note for free, then you can do it with your hands, if you I told you that you have baking soda, asked what Done, this sound is less, just Done, this sound is less, just Done, this sound is less, just edit it back, okay, do it, Hi edit it back, okay, do it, Hi Dad, how I saw it inside, Dad, how I saw it inside, give everyone a chance to become a guava, like this, 105 give everyone a chance to become a guava, like this, 105 What to do, give everyone a chance to become Tiger Woods, What to do, give everyone a chance to become Tiger Woods, oil Africa that we oil Africa that we oil Africa that we okay see how if it is consumed in fruit juice then you will worship through two, for that what will happen to you? I - the thing will go up to 151 and the rider vibrations and till the vibrations in these three till hanging, the From seven to till is fine From seven to till is fine From seven to till is fine like if it is broken then what will happen in the left like if it is broken then what will happen in the left 1782 what will come is fine for 582 now this many 1782 what will come is fine for 582 now this many surfers will be made in the last, as surfers will be made in the last, as many surfers will be made in the right then what will Shahrukh Khan do with them many surfers will be made in the right then what will Shahrukh Khan do with them first, what will be our route first, what will be our route and how many in the last and how many in the last and how many in the last here to see if you knew how this is happening, delete it today, when you have it, when you have unbroken police station, when you have route two, then read these two things in your left leg tractor, once once, delete one, there is one and there is It is okay to erase it once, it It is okay to erase it once, it It is okay to erase it once, it is pure and once, what is this, this is your is pure and once, what is this, this is your left, okay, and at this time, whoever pleases you, left, okay, and at this time, whoever pleases you, erase it once, and erase it once, and erase it once, fiber time, Udayraj Fateh, already in this. erase it once, fiber time, Udayraj Fateh, already in this. What did we see? What did we see? Envelopes of 5.02 for the first one. 0.2 or cancer Envelopes of 5.02 for the first one. 0.2 or cancer means you have got four answers. Ways for the one. What was the means you have got four answers. Ways for the one. What was the first answer? Okay, there was first answer? Okay, there was arrangement for guava and you did the conference arrangement for guava and you did the conference and the second only meeting is your life and the second only meeting is your life insurance. insurance. insurance. if you want to play your money again, then I pray to you Stuart Broad, then I want you to try again on your money, I have to make a tour here and back on my face and here. Significance for access is dependent on you and it is clear according to all the albums in each left that if you want to do every last date, then I will do it by picking your routes thoroughly, what is there Were Were and keep this palace R right I will and keep this palace R right I will give you popular okay so what will you do with this then give you popular okay so what will you do with this then all the problems here are gone and now what will we do we will all the problems here are gone and now what will we do we will keep the route and return back yes I will return the keep the route and return back yes I will return the premium okay now like premium okay now like I I I we got mercy on the solution on the basis, so all of you are getting connected as we were seeing here, tissue was 345 in two of its plates, now we have passed like this, so it is okay, I will break it. How fist abs sacrifice will come and break the record the next day, then all its cosmetics are different, this is the richest year of disturbance, I would definitely like to comment once, you have this thing, you will make some things a topic and yours, you can see for You are going to follow this chord, You are going to follow this chord, You are going to follow this chord, so if you see something, if you so if you see something, if you write it down logically for a copy, write it down logically for a copy, then you are going to have this tension forever, I am then you are going to have this tension forever, I am adopting this knowledge, adopting this knowledge, normal, you will remember it for a long time. normal, you will remember it for a long time. normal, you will remember it for a long time. you will get a lot of benefits from the Internet. Video: You have to write this directly. Similarly, the Internet has to explain to you first in your interview. After that you have to write. So, if you are interested in this and stunning this point then I will tell you It is going to be more beneficial, It is going to be more beneficial, It is going to be more beneficial, friends, I hope you will friends, I hope you will give me the explanation and vote. If you understand, give me the explanation and vote. If you understand, still you have any kind of problem, then you still you have any kind of problem, then you must tell me in the comment section. I will must tell me in the comment section. I will try to tell it on simple WhatsApp. try to tell it on simple WhatsApp. If you want, please comment on my If you want, please comment on my If you want, please comment on my you like this video then please like this video and subscribe to the channel. If you have friends then share the YouTube channel with them. Many friends will like to watch this video and see you soon You
2024-03-20 13:32:00
95
https://i.ytimg.com/vi/E…axresdefault.jpg
Unique Binary Search Trees II | Leetcode95 | BST | Recursion | Interviews
8Fua2tVEVDo
hey everyone today we are going to solve the radical question largest color value the radical question largest color value in your directed graph which involves in your directed graph which involves finding the largest number of nodes in finding the largest number of nodes in your path with the same color in in your your path with the same color in in your directed graph so in this problem each directed graph so in this problem each node in the graph is associated with a node in the graph is associated with a color represented by a lowercase letter color represented by a lowercase letter so like a b a c a and uh so looks like a so like a b a c a and uh so looks like a a represents red color and the B a represents red color and the B represents purple represents purple and the C represents and the C represents um blue um blue so the goal is to find the largest value so the goal is to find the largest value of color such that there is a path in of color such that there is a path in the graph that contains all nodes of the graph that contains all nodes of that color so this means that we want to that color so this means that we want to find the highest frequency of a color in find the highest frequency of a color in any pass in the graph that visits all any pass in the graph that visits all nodes of that corrupt for example if the nodes of that corrupt for example if the graph contains nodes with colors like a graph contains nodes with colors like a b and c b and c and there is a path like a zero two and there is a path like a zero two three four so in in this pass we can three four so in in this pass we can find the three a right so index 0 index find the three a right so index 0 index 2 and the index four right and then one 2 and the index four right and then one blue blue I think X3 so in this case I think X3 so in this case um a is a like a highest frequency of um a is a like a highest frequency of the colors so that's why in this case the colors so that's why in this case output is 3. before I start my output is 3. before I start my explanation so let me introduce my explanation so let me introduce my channel so I create a lot of videos to channel so I create a lot of videos to prepare for technical interviews I prepare for technical interviews I explain all the details of all questions explain all the details of all questions in the video and you can get the code in the video and you can get the code from GitHub for free so please subscribe from GitHub for free so please subscribe my channel hit the like button or leave my channel hit the like button or leave a comment thank you for your support a comment thank you for your support okay so let me explain with this example okay so let me explain with this example so to solve a discussion now so we will so to solve a discussion now so we will use like a breast first search to use like a breast first search to Traverse the graph Traverse the graph and to keep the data we use like a 2d and to keep the data we use like a 2d array so this is a 2d dynamic array so this is a 2d dynamic programming so why do we use a 2d array programming so why do we use a 2d array so so actually we have to keep track of two actually we have to keep track of two datas so one is a current position datas so one is a current position and uh the other is a number of colors and uh the other is a number of colors so that means so if we uh index 2 so so that means so if we uh index 2 so value two so how many num how many each value two so how many num how many each color we have so far like a four red or color we have so far like a four red or purple or blue purple or blue so that's why we have to keep track of so that's why we have to keep track of two two datas so that's why we use like two two datas so that's why we use like a 2d array a 2d array and uh so for 2D array um so and uh so for 2D array um so this question this question um um in this question uh so each English in this question uh so each English letter represents uh like some colors so letter represents uh like some colors so potentially we have like a 26 potentially we have like a 26 colors from A to Z right so that's why colors from A to Z right so that's why um this length of row should be 26 um this length of row should be 26 because of a space program on the screen because of a space program on the screen let me write down until C so usually 2z let me write down until C so usually 2z so basically we iterate through all so basically we iterate through all vertex like one by one vertex like one by one and we start from zero because any in and we start from zero because any in this question uh any vertex don't go to this question uh any vertex don't go to the robotics the robotics so that's why it's good to start so that's why it's good to start from zero and so let's begin from zero and so let's begin first of all um first of all um so now we are zero here the robotics so so now we are zero here the robotics so current color is a right so which is red current color is a right so which is red in this case update 0 0 to 1. and then take the neighbor node so let's go to one so let's take this bus when we need at vertex one so first of all compare each color with corresponding previous vertex color so that means zero one passes 0 0 1 1 plus 0 1 and 1 2 passes zero two so first of all we'll check the one zero versus zero zero so zero zero is one so one zero is zero so one is a bigger than zero in that case update this one to one so one so one and then take one one and then take one one but they are same so we don't do but they are same so we don't do anything anything and check the one two buses still two so and check the one two buses still two so they are same we don't do anything and they are same we don't do anything and the check until Z so in the end we get the one zero zero zero zero zero zero until Z and then um next we try to move buttocks from one buttocks one to somewhere so but before that um don't forget the current color so current color is a purple so popular is a one so B and then um try to move somewhere but and then um try to move somewhere but there's no but it's from uh index in there's no but it's from uh index in about X1 about X1 so we finished robusting for this bus so we finished robusting for this bus so okay so far so what does this numbers so okay so far so what does this numbers means that means so if we uh index one means that means so if we uh index one we have we have um one color um one color for it and then one color for for it and then one color for purple so let's check for this bus one purple so let's check for this bus one left color one purple color so that's left color one purple color so that's why our why our so when we see the these 2D metrics so so when we see the these 2D metrics so it's easy to understand like uh when we it's easy to understand like uh when we after one so red is one proper is one so okay oh oops let's move this bus so we already added the last one so move two so we do the same thing again compare each color at two with a so in this case one bus is zero so one so in this case one bus is zero so one is a great thousand they're also up to is a great thousand they're also up to date date two zero two one two zero two one and compare two and plus as still one and compare two and plus as still one but they are saying we don't do anything but they are saying we don't do anything so 2 2 and 0 2 they are saying we don't so 2 2 and 0 2 they are saying we don't do anything until Z so in the end we so do anything until Z so in the end we so at the Row 2 at 2 so we get like a one at the Row 2 at 2 so we get like a one zero zero zero zero zero one two Z zero zero zero zero zero one two Z and then again uh and then again uh check enabling check enabling so we have so three so that's why uh so we have so three so that's why uh there are paths to go then so let's move there are paths to go then so let's move from two to three but before that don't from two to three but before that don't forget uh the current color forget uh the current color so current color is red so so current color is red so 2 0 outputate two zero to two so okay uh before we move to three so let's check so if we are about X2 so there is a path only from zero so this pass has two little colors so that's why two zero is a two and the other color should be zero right so looks good so let's move three again uh compare each color with a like a previous vertex two in this case two so um compare three zero versus two zero so two is a greater than zero so update three zero with these two so two and the other colors should be zero so we don't update anything until Z and then again take a neighboring we have Vertex 4 from C so let's move but uh so again before move to from three to four don't forget other current color so color is uh blue so update 3 to with one so when we are at vertex 3 so we have two that color and one blue color so let me let me change the color so let's so this bus we have a red two red color and one blue color yeah it looks good so let's move to four again we do the same thing compare each color with like a previous 2 is a greater than zero so update two 2 is a greater than zero so update two and uh and uh so four one passer three one zero zero so four one passer three one zero zero we don't do anything and then four two we don't do anything and then four two passes three two so the previous color passes three two so the previous color is blue is blue so that's why uh we have a one blue so so that's why uh we have a one blue so one is a greater than zero so update one is a greater than zero so update this zero to one this zero to one and the other color should be zero right and the other color should be zero right so and then so and then um um next try to move from four to somewhere next try to move from four to somewhere but before that don't forget the current but before that don't forget the current error red so for zero update four zero error red so for zero update four zero two three right two three right so when we are in the butt X4 so when we are in the butt X4 so so yeah this bus yeah this bus we have three car uh three let and one we have three car uh three let and one blue three Nets and one blue blue three Nets and one blue and then I'll try to move somewhere but and then I'll try to move somewhere but there is no pass then also we finish there is no pass then also we finish traversing traversing and uh and uh after that after that um take the max number so this one um take the max number so this one so that's why um we should return three so that's why um we should return three in this case in this case yeah so that is our main idea to solve yeah so that is our main idea to solve this question this question I think uh this program is quite wrong I think uh this program is quite wrong so I try to explain a little by little so I try to explain a little by little and as simple as possible and as simple as possible so yeah with that being said let's get so yeah with that being said let's get into the code into the code okay so let's write a code first of all okay so let's write a code first of all um create a direct graph with other Json um create a direct graph with other Json list so graph equal default addict list so graph equal default addict and at least and at least and create a in in degree and create a in in degree equal equal um initialized with zero um initialized with zero multiply length of multiply length of um colors um colors so so in degree e in the degree of in degree e in the degree of vertex is the number of vertex is the number of xg's going to the yeah so we call it in degree yeah so we call it in degree itself itself for H in edges for H in edges so so if if at the 0 at the 0 equal H one equal H one so this is a outer degree and this is a so this is a outer degree and this is a in degree so in degree so out degree and in degree are equal in out degree and in degree are equal in that case it's a circle so in that in that case it's a circle so in that in the case just return minus one the case just return minus one if not the case add a graph so key if not the case add a graph so key should be in outer degree so zero should be in outer degree so zero and uh and uh values should be in degree so h values should be in degree so h and one so that means from this vertex and one so that means from this vertex uh going to this vertex uh going to this vertex and then and then count uh in number of in degree count uh in number of in degree so in the query and the key should be H so in the query and the key should be H and the one and the one plus equal one plus equal one after that so we talk about the graph after that so we talk about the graph with a breast for such so we use a DQ so with a breast for such so we use a DQ so Q equal KQ Q equal KQ and the greater list I for I in length and the greater list I for I in length and the length of and the length of Kara Kara and if current position equals zero current position equals zero so why we check zero here so because if so why we check zero here so because if in degree of vertex is zero that means in degree of vertex is zero that means uh we don't have like a we don't need a uh we don't have like a we don't need a any prerequisite vertex any prerequisite vertex that needs to be visited first that needs to be visited first so this means so this means this vertex can be like a fast vertex to this vertex can be like a fast vertex to drop us a graph drop us a graph so by starting place for such from these so by starting place for such from these nodes with zero in degree we ensure that nodes with zero in degree we ensure that we are starting from the root of the we are starting from the root of the graph and visit all nodes in valid order graph and visit all nodes in valid order so that's why we check here so that's why we check here and then after that and then after that create a DP list equal create a DP list equal so as I explained earlier zero multiply so as I explained earlier zero multiply 26 because uh there are there are 26 26 because uh there are there are 26 alphabet in the world so that's why for alphabet in the world so that's why for underscore in Orange and ranks underscore in Orange and ranks of arrows of arrows so yeah I bought other piece here so yeah I bought other piece here and then um and then um initializer like a Max initializer like a Max color equals zero this is a return value color equals zero this is a return value and then starts traversing while Q and then starts traversing while Q and the first of all um and the first of all um part six part six equal Q dot pop left equal Q dot pop left so take the first vertex from Q so take the first vertex from Q and then get the current color so color and then get the current color so color equal so to get the current color I use equal so to get the current color I use a ASCII value so Ord in the Karas and a ASCII value so Ord in the Karas and the current politics the current politics minus minus ORD and the ORD and the a a so what I'm so what I'm doing here is that so I'm not sure exact doing here is that so I'm not sure exact ASCII code but if ASCII code but if ASCII value of a ASCII value of a is 100 is 100 so B should be 101 and the C should be so B should be 101 and the C should be 102 and the D should be 103 something 102 and the D should be 103 something like that so if I like that so if I subtract a value of a from current color subtract a value of a from current color so every time we get direct correct so every time we get direct correct number so that's why uh I subtract a number so that's why uh I subtract a from current a color and then so as I explained earlier before we move to um azerobatics don't forget so don't forget uh to update the uh 2D Matrix so vertex and uh Cara plus equal one and then take the max color equal Max color should be current Max color versus so after that check the neighbor so after that check the neighbor buttocks so for buttocks so for neighbor neighbor in graph graph in graph graph in the current vertex in the current vertex so every time we take the neighbor so every time we take the neighbor robotics robotics now first of all add minus one to uh in now first of all add minus one to uh in degree degree so neighbor minus equal one after that so neighbor minus equal one after that as I explained earlier uh check the each as I explained earlier uh check the each color color already presented by uh like an English already presented by uh like an English lower character lower character in lens and the 26 in lens and the 26 and the DP and then never and the DP and then never in the character in the character equal Max equal Max and I want the same thing this one and I want the same thing this one passes passes um um the other is DB vertex and C the other is DB vertex and C so this is like a previous vertex and so this is like a previous vertex and this is a like a current vertex this is a like a current vertex and uh if a previous vertex has a and uh if a previous vertex has a bigger number update current position bigger number update current position with a previous number and then oops after that if in degree and the neighbor equals zero in the case that can be this current vertex can be like a start startling point to two of us like a father so that's why add current then finish your best for such after then finish your best for such after that check any and E in degree that check any and E in degree in that case we should be down -1 in that case we should be down -1 so this line of code is checking whether so this line of code is checking whether there are any remaining vertex with there are any remaining vertex with non-zero in degree after traversing the non-zero in degree after traversing the graph graph if there are any it means that there if there are any it means that there must be at least one Circle in the graph must be at least one Circle in the graph because of those but vertices have like because of those but vertices have like incoming edges that cannot be resolved incoming edges that cannot be resolved so that's why we should return -1 so so that's why we should return -1 so indicate that there is no path that indicate that there is no path that contains all nodes of a single color contains all nodes of a single color and then and then um if not the case just return Max color um if not the case just return Max color yeah so that's it let me submit it sorry yeah so that's it let me submit it sorry uh this program should be inside of this uh this program should be inside of this for Loop for Loop so so like this like this then so let me submit it yeah looks good then so let me submit it yeah looks good in the time complexity of this solution in the time complexity of this solution should be order of B plus e so V is the should be order of B plus e so V is the number of vertex and the E is the number number of vertex and the E is the number of edges in the graph so this is because of edges in the graph so this is because we troubles the graph using a press we troubles the graph using a press first search visiting each vertex and first search visiting each vertex and each edges only once so space complexity each edges only once so space complexity should be order of V multiply K plus e should be order of V multiply K plus e so B is a number of vertex in the graph so B is a number of vertex in the graph so K is the number of possible colors 26 so K is the number of possible colors 26 in this case and the E is the number of in this case and the E is the number of edges in the graph edges in the graph so this is because we create a 2d so this is because we create a 2d metrics for dynamic programming so that metrics for dynamic programming so that is a v multiplier okay is a v multiplier okay so to store the count the count of each so to store the count the count of each color at each node color at each node and then we create a Json list to and then we create a Json list to represent the edges of the graph which represent the edges of the graph which take up order of E take up order of E space and also we use a DQ space and also we use a DQ implementables for such algorithm which implementables for such algorithm which can take up to order of B can take up to order of B space in the worst case if graph is a space in the worst case if graph is a like a straight line like a straight line yeah so that's all I have for you today yeah so that's all I have for you today if you like it please subscribe the if you like it please subscribe the channel hit the like button or leave a channel hit the like button or leave a comment I'll see you in the next comment I'll see you in the next question
2024-03-25 11:12:45
1,857
https://i.ytimg.com/vi_w…xresdefault.webp
Largest Color Value in a Directed Graph - LeetCode #1857 with Python, JavaScript, Java and C++
D3izahCCads
welcome ladies and gentlemen boys and girls today i want to solve another girls today i want to solve another problem which is partition list so problem which is partition list so basically this is the best problem it basically this is the best problem it gets like from my side okay let's see gets like from my side okay let's see what the question is the question is what the question is the question is saying like we given the head of a saying like we given the head of a league list and a value x partition league list and a value x partition partition it's just that all nodes less partition it's just that all nodes less than x comes before the node greater than x comes before the node greater than or equal to x okay so what is than or equal to x okay so what is saying like we are given something x so saying like we are given something x so s can be any value is over here 3 so s can be any value is over here 3 so what we have to do we have to put what we have to do we have to put less than 3 less than less than 3 less than less than three over here over here and less than three over here over here and greater than three over here okay so greater than three over here okay so i hope this thing makes some sense to i hope this thing makes some sense to you guys like what the question is you guys like what the question is saying okay so let's just look at over saying okay so let's just look at over here like uh how we're gonna do this so here like uh how we're gonna do this so i will just take uh okay instead of i will just take uh okay instead of taking to the whiteboard should i take taking to the whiteboard should i take you to the right way i will take you to you to the right way i will take you to the whiteboard okay so let me it is the whiteboard okay so let me it is everything from over here everything from over here and here we go let me gentlemen so what and here we go let me gentlemen so what i will do i will just first of all i will do i will just first of all create two uh two dummy dummy dummy node create two uh two dummy dummy dummy node okay dummy list so i will call it okay dummy list so i will call it beforehand and after head okay so beforehand and after head okay so beforehand means like the value less beforehand means like the value less than x will attach on this dummy list than x will attach on this dummy list okay and initially it's value zero so i okay and initially it's value zero so i will say this value zero and after has a will say this value zero and after has a means the means the value greater than or equal to x will value greater than or equal to x will come over here on this list okay and come over here on this list okay and then we will join them together okay all then we will join them together okay all right so let me just take you sorry let right so let me just take you sorry let me just take that following example we me just take that following example we have something like one four three two have something like one four three two five two we have one four three two five five two we have one four three two five two two so i will do it over here we have one so i will do it over here we have one four three two five two okay so like four three two five two okay so like this like this this this this this so this like this this this this this so they're pointing they're pointing my mistake i just drew it very bad so my mistake i just drew it very bad so okay let me just erase it and i will do okay let me just erase it and i will do it good for you only for you guys so it good for you only for you guys so make sure to hit and like this video i'm make sure to hit and like this video i'm just doing only for you here we go just doing only for you here we go ladies and gentlemen so okay i just draw ladies and gentlemen so okay i just draw it so we have something like this okay it so we have something like this okay and we have to put it over here and our and we have to put it over here and our x is three our x is three so it will x is three our x is three so it will like to uh the value before the three like to uh the value before the three will come on the beforehand so this will come on the beforehand so this before and a value after the three will before and a value after the three will come over here after the three or equals come over here after the three or equals to three will come over here on the to three will come over here on the after so i will use two i will use two after so i will use two i will use two pointer uh before and after okay so i pointer uh before and after okay so i will just probably before and after so will just probably before and after so the people pointer will check so it will the people pointer will check so it will check if my head value head value is check if my head value head value is less than x then what i will do i will less than x then what i will do i will point it over here i will point to my point it over here i will point to my over here so in this one is less than over here so in this one is less than one is less than three so it will come one is less than three so it will come over here it will come over now on this over here it will come over now on this one i will check is is less than three one i will check is is less than three it will say no is greater than three so it will say no is greater than three so what will happen i will use my after what will happen i will use my after pointer and it will come over here on my pointer and it will come over here on my after head okay similarly on this one i after head okay similarly on this one i will check is it uh greater than three will check is it uh greater than three or equal to three it will say it is or equal to three it will say it is equal to three so similarly i will equal to three so similarly i will attach over here now on this one it will attach over here now on this one it will check it is check it is greater than three or equals two people greater than three or equals two people say neither is greater than neither say neither is greater than neither equal equals it is less than three so equal equals it is less than three so what will happen i will add to my before what will happen i will add to my before head over here are you using my before head over here are you using my before pointer okay on in this one i will check pointer okay on in this one i will check is it less than three it will say no it is it less than three it will say no it is greater than three so what will is greater than three so what will happen i will add it over here on my happen i will add it over here on my after hand now on this one i will check after hand now on this one i will check is it greater than or equal to three it is it greater than or equal to three it will say no it is neither greater than will say no it is neither greater than three or nine it neither equals to three three or nine it neither equals to three it is less than three so what will it is less than three so what will happen i will attach over here okay so happen i will attach over here okay so we just uh just completely traverse we just uh just completely traverse our our original linked list so what will happen original linked list so what will happen it look my head my original hand will it look my head my original hand will point to the null once my original head point to the null once my original head points to that and so what what i will points to that and so what what i will do i will say okay so it means we just do i will say okay so it means we just done it then i will make i will say my done it then i will make i will say my after after dot next is my after pointer my after dot next is my after pointer my after dot next points to null okay now now we dot next points to null okay now now we have to join them together now we have have to join them together now we have to join beforehand and after that to join beforehand and after that together okay then what i will do let me together okay then what i will do let me just let me zoom it out just let me zoom it out to get some more extra space to get some more extra space okay so now guys what i will do i'll okay so now guys what i will do i'll just simply say do one thing attached to just simply say do one thing attached to my before uh dot next over here so my my before uh dot next over here so my before note next will come like before note next will come like something like one two two and it will something like one two two and it will it will attach this one it will attach this one aft after the head after hair after head aft after the head after hair after head dot next why because initially we have dot next why because initially we have zero so i i don't want zero i want from zero so i i don't want zero i want from the four so it will come something like the four so it will come something like four four three three five and finally none so that's our oh five and finally none so that's our oh that's our all the uh list like uh like that's our all the uh list like uh like partition is that what we the what the partition is that what we the what the question wants from us so ladies and question wants from us so ladies and gentlemen i hope you like this idea may gentlemen i hope you like this idea may this give you some i like how we're this give you some i like how we're going to show this because this is a going to show this because this is a very easy question believe me it's very very easy question believe me it's very easy code very easy to do so let me just easy code very easy to do so let me just move it over there okay so okay so you move it over there okay so okay so you will definitely go to understand believe will definitely go to understand believe me you'll definitely understand so list me you'll definitely understand so list no i will say what i will say i will say no i will say what i will say i will say beforehand beforehand so i'm creating my so i'm creating my dummy list over here so dummy list over here so is the new is the new list node initially value i will give list node initially value i will give give it 0 because i love to give zero give it 0 because i love to give zero okay and list okay and list note note before before before will be our uh beforehand before will be our uh beforehand okay because it's a pointer before the okay because it's a pointer before the pointer okay and it's pointing to the pointer okay and it's pointing to the beforehand okay it's like initially at beforehand okay it's like initially at over there now we get list note after over there now we get list note after head head after head is the new after head is the new list list no initial value zero no initial value zero and my after is after i will get an and my after is after i will get an after pointer and after point is after pointer and after point is initially at after head initially at after head after after is at my after is at my after head okay so i hope this thing makes head okay so i hope this thing makes some sense to you guys okay so now what some sense to you guys okay so now what i will do in general i will turn up i will do in general i will turn up while loop my while loop will run till while loop my while loop will run till my head my head node equals to node so my head does not node equals to node so my head does not reach or not reach or not once it will then i will simply stop once it will then i will simply stop traversing it okay in this one what i traversing it okay in this one what i will do i will check if will do i will check if my head dot head dot well my head dot head dot well is less than x if that's so then what i is less than x if that's so then what i will do i will say before will do i will say before don't next before dot next because don't next before dot next because you know i have to point before the you know i have to point before the using before pointer so initially i using before pointer so initially i might before head is at zero so i have might before head is at zero so i have to point after it so obviously before to point after it so obviously before dot next because to my head i will put dot next because to my head i will put my head value over there and i have to my head value over there and i have to update my before pointer so my now my update my before pointer so my now my before pointer will come on my headphone before pointer will come on my headphone okay before x 2 okay before x 2 before so next so i just upgrade over before so next so i just upgrade over here similarly over here as for the here similarly over here as for the condition if my x is greater than equals condition if my x is greater than equals to my hair value so i will attach to my to my hair value so i will attach to my after head so i will say else whatever after head so i will say else whatever you have to do after you have to do after go go next next uh equals to head and update your after uh equals to head and update your after as per the above which i told you as per the above which i told you similarly what will happen initially i similarly what will happen initially i might dummy one i will come over on my might dummy one i will come over on my like it's pointing to the my next one it like it's pointing to the my next one it pointed to my head now i have to update pointed to my head now i have to update my after pointer so my after pointer so my after is initially at one time so it my after is initially at one time so it will come on my head now okay on the new will come on my head now okay on the new node okay it will come on the new node node okay it will come on the new node not head over no no not head over no no after door after door next okay so i also this thing is very next okay so i also this thing is very clear okay so finally what last thing we clear okay so finally what last thing we have to do i have to upgrade my head as have to do i have to upgrade my head as well because you know every time we have well because you know every time we have to update you can either update in the to update you can either update in the using if loop but you know make try to using if loop but you know make try to make the shoot as short as possible make the shoot as short as possible so it's very helpful to see it's a very so it's very helpful to see it's a very good good thing okay and finally after good good thing okay and finally after coming after coming out of this loop coming after coming out of this loop what we have to do i have to simply uh what we have to do i have to simply uh is okay i have to simply say after dot is okay i have to simply say after dot next my after value is null so it will next my after value is null so it will be like once i i'm on the end thing i be like once i i'm on the end thing i will say my just point my after rule my will say my just point my after rule my null okay okay here we go null okay okay here we go now what we have to do i have to say my now what we have to do i have to say my before don't next before don't next will be my after will be my after head head don't don't next what i'm doing i'm just joining next what i'm doing i'm just joining them together so after the month before them together so after the month before what next so you know i'm on the before what next so you know i'm on the before one so attached to the next video online one so attached to the next video online after that my before pointer i test my after that my before pointer i test my after hand don't necessarily you know after hand don't necessarily you know like after i had like what we have over like after i had like what we have over here i will take you to this test case here i will take you to this test case so it means like we are on the uh so it means like we are on the uh we are we are on the over here so i have we are we are on the over here so i have to attach over here i have to attach to attach over here i have to attach over here so i use before but next over here so i use before but next what i have to attach after head value what i have to attach after head value after this value because we don't want after this value because we don't want zero we don't want zero we want from zero we don't want zero we want from over here okay that's what i'm that's over here okay that's what i'm that's what i'm doing over here right so i also what i'm doing over here right so i also like this thing with some sense like i like this thing with some sense like i cannot best to explain each line of code cannot best to explain each line of code what we are doing over here and why we what we are doing over here and why we are doing it like this that's my main are doing it like this that's my main motive is so motive is so please like this video please guys okay please like this video please guys okay thank you very much okay so now finally thank you very much okay so now finally what i have to do i have to return my what i have to do i have to return my before hand next before head to next before hand next before head to next similarly let me stick to the my white similarly let me stick to the my white board board if you look at over here i have to if you look at over here i have to return after this one after this one return after this one after this one note this one this one is we just go to note this one this one is we just go to to save the list we just go to save the to save the list we just go to save the list okay this thing will just go to list okay this thing will just go to save the list okay okay so ladies and save the list okay okay so ladies and gentlemen just all the code let me just gentlemen just all the code let me just run this code to see any compilation run this code to see any compilation error do we face so we will get to that error do we face so we will get to that okay and here we go we just get okay and here we go we just get something over here okay my spelling something over here okay my spelling mistake b e mistake b e f f o r e b for head darkness so o r e b for head darkness so spelling mistakes happen so it's not a spelling mistakes happen so it's not a big deal big deal engine engineers do a mistake because engine engineers do a mistake because that's why we are engineers we do that's why we are engineers we do mistake we solve the mistakes mistake we solve the mistakes so cheers to engineers okay so let me so cheers to engineers okay so let me just submit score and i will tell you just submit score and i will tell you the space complexity and the time the space complexity and the time complexity and let's see it's accepting complexity and let's see it's accepting all the tests and here we go ladies and all the tests and here we go ladies and gentlemen so it's going very well okay gentlemen so it's going very well okay so in this one the time complexity is so in this one the time complexity is our big o of n to go n okay because we our big o of n to go n okay because we are just traversing on the original no are just traversing on the original no not original linked list uh iteratively not original linked list uh iteratively okay we are traversing on our okay we are traversing on our uh iteratively on our original linked uh iteratively on our original linked list oh because we are changing number list oh because we are changing number of nodes and n number of nodes okay and of nodes and n number of nodes okay and the space complexity is our bigger one the space complexity is our bigger one why because we are not using again any why because we are not using again any extra memory no extra spaces that's why extra memory no extra spaces that's why i love linked list people we are dealing i love linked list people we are dealing with most of the time we are dealing with most of the time we are dealing with space complexity because one so with space complexity because one so thank you ladies and gentlemen for thank you ladies and gentlemen for watching this video i hope this thing watching this video i hope this thing makes some sense if you still have any makes some sense if you still have any doubt just do let me know in the comment doubt just do let me know in the comment section if you still don't understand section if you still don't understand anything i will suggest you to watch anything i will suggest you to watch this video again because you will this video again because you will definitely understand and thank you definitely understand and thank you ladies and gentlemen for watching this ladies and gentlemen for watching this video i will see you in the next one video i will see you in the next one till then take care bye bye and i love till then take care bye bye and i love you guys believe me i love you take care you guys believe me i love you take care bye
2024-03-20 12:42:24
86
https://i.ytimg.com/vi/D…axresdefault.jpg
Partition List | LEETCODE - 86 | Easy solution
EZE8ctn7fAI
Hi gas welcome and welcome back tu my channel so today our problem is maximum length so today our problem is maximum length of repeated so in this problem statement of repeated so in this problem statement what have we given here name van and what have we given here name van and namas tu de rakha hai ok what do we have to do namas tu de rakha hai ok what do we have to do na find the maximum length na find the maximum length na find the maximum length submerre which is present in both, okay, so let us understand through the example that the problem is exactly ours, after that we will see how we can solve it. Okay, so what have you given us here? The The The numbers are kept, you are fine, what do we have to do, we have to numbers are kept, you are fine, what do we have to do, we have to see from here and that is of maximum length, so that length has to be given to see from here and that is of maximum length, so that length has to be given to us after turning. Okay, so us after turning. Okay, so here you can have one length also, here you can have one length also, it can also be of left, three length. it can also be of left, three length. it can also be of left, three length. can also be of four length. It can also be of four length. Okay, so we have to calculate the naximum and give its length. Look, your van van is matching, you are matching 3 3, it means that You are also a van, you are also a You are also a van, you are also a You are also a van, you are also a van, it is also of two length, now you van, it is also of two length, now you will see here, then it is also of three length 3 2 1 3 2 will see here, then it is also of three length 3 2 1 3 2 1 This is of three line, is it of four line, is it 1 This is of three line, is it of four line, is it of four line, but if not, then of four line, but if not, then what is your maximum? what is your maximum? what is your maximum? what will you do by turning it here? Now how will we solve this problem? Look, our solution here will be based on sliding window, it is okay because this is the one which will give you the most optimized solution. Here you will get the time complexity of M*N, I will tell you how it happened and here you will see the space first time, you are three, you are one, first time, you are three, you are one, okay, this is what we have given, what will we do, we will okay, this is what we have given, what will we do, we will keep 7 here and we will keep all these four here. keep 7 here and we will keep all these four here. Van Van tu three, we will do this in the first step. We have done it. Is he tu three, we will do this in the first step. We have done it. Is he matching here? Is he matching me? We matching here? Is he matching me? We still have zero. Then still have zero. Then what will we do in the second step: Van tu three tu van seven. We will place four here and van one. van seven. We will place four here and van one. van seven. We will place four here and van one. 3 here. We have the right to match. I am doing the match. We did not match anything in the second step too. Then we will go to the third step. 1 2 3 2 1 7 There will be four here, there will be van here, there will If it is here, it will be one, If it is here, it will be one, If it is here, it will be one, you have matched the you have matched the length, right, so far, you have got the length, length, right, so far, you have got the length, okay, then we will go to the fourth step, if okay, then we will go to the fourth step, if you are three, you will be 7, here it will be you are three, you will be 7, here it will be four, here it will be one. four, here it will be one. four, here it will be one. be there, here there will be three, okay is it matching, if not even one is matching, then nothing has matched, now we will go to the step again, okay 1 2 3 21, here there will be 7, What will be your What will be your What will be your van here, you will be here, there will be three, is van here, you will be here, there will be three, is one matching or not, one matching or not, then we will go to step six, van, you are then we will go to step six, van, you are three, you are ok, what will be yours, here, what will be 7, three, you are ok, what will be yours, here, what will be 7, here will be four, here will be van here will be four, here will be van Tu here van Tu here van Tu here van is ok, so 7 here will be four here, here is ok, so 7 here will be four here, here van, here you are doing van, here you are doing 3 3 line here, is this match happening, are all three matching in this, so what is now in place of van, It is done, it It is done, it It is done, it is okay, we will is okay, we will move further, we will move further, we will see further, we will see till here, it is okay because starting see further, we will see till here, it is okay because starting from here, we have seen the light, we will make all the elements overlap till here, we are done till here, make all the elements overlap till here, we are done till here, now these two are left 1 2 3 now these two are left 1 2 3 now these two are left 1 2 3 What will we do here? We will keep the three here. We will keep 2 here. Is 147 matching? Is it not matching? Okay, so far our three is the maximum, then we will go to the ninth step. 1 You will put three here, you here, You will put three here, you here, van here, okay now let's leave it because we started from here, started from its beginning, from here back to its starting, we reached here, Now we have come till the Now we have come till the Now we have come till the initial stage, we have come till its beginning, initial stage, we have come till its beginning, so it is done, now we will not look further beyond this, so it is done, now we will not look further beyond this, whatever we have got now will be whatever we have got now will be our maximum answer, then how will we solve this problem, our maximum answer, then how will we solve this problem, see, I mean, I see, I mean, I told you that in this way. told you that in this way. told you that in this way. how our code will be, what will we do here, we will have to take care of the index in both the tables, okay, so here when there is zero, we are taking four here, we are getting Here we are Here we are Here we are seeing that our a is 01 when a is seeing that our a is 01 when a is taking two elements here so taking two elements here so what is our a is three and four is a what is our a is three and four is a okay then here you are seeing 0 1 2 okay then here you are seeing 0 1 2 when a is when a is when a is three, a is 4, then what are you seeing here, zero van, become 01234 of four length, then become 01234 of four length, then what will happen to you here. what will happen to you here. what will happen to you here. zero, sorry, zero, van, three, four, what will happen from here, zero, van, three, this is its here from van to 4, its from 1, zero to three, then what is its case If 3 is 4 then what is its 0 1 If 3 is 4 then what is its 0 1 If 3 is 4 then what is its 0 1 2 is it ok 3 4 This is zero van tu hai which 2 is it ok 3 4 This is zero van tu hai which will be the overlap part ok will be the overlap part ok we will get it matched so this zero van tu three four is its three four we will get it matched so this zero van tu three four is its three four Its zero van is zero van Its zero van is zero van ok so now we come, I will show you the code so now we come, I will show you the code part, after that again I will part, after that again I will explain to you how we have done it, it can happen for you explain to you how we have done it, it can happen for you that what you see here, we have Ijj Ka Ise I Kae that what you see here, we have Ijj Ka Ise I Kae Ise Ji Ka. Ise Ji Ka. Ise Ji Ka. mind that it is okay to start from where, it may be different in your approach, yours may be different, our approach may be different, it means look, when you have a question about pattern printing, We We We solve it in different ways, we solve it by applying different conditions, solve it in different ways, we solve it by applying different conditions, you you can do it in this also, it is not necessary that you match our can do it in this also, it is not necessary that you match our solution, if you match our solution, solution, if you match our solution, then I will tell you how we did it. then I will tell you how we did it. Okay, so look, we have done it here. Okay, so look, we have done it here. Okay, so look, we have done it here. two IGs, how did we create them, what did we do here - starting from N + 1 and we will take it up to M. Okay, and what will we do with it from zero to less, we will take it up Okay, Okay, Okay, so what will we do in this, see so what will we do in this, see what looping we have done, let me what looping we have done, let me show you what we will show you what we will do, see what is its length, I is do, see what is its length, I is yours, its is five, its is five, okay, both of them are yours, its is five, its is five, okay, both of them are 5, MB is ours, 5 and the end 5, MB is ours, 5 and the end is also our five. what will we do? We will start from -4. Okay, we will what will we do? We will start from -4. Okay, we will go till our fourth because this is go till our fourth because this is your mines end plus van till the end there will be only four, so it will be four. Okay, mines start from mines four, so what about yours? start from mines four, so what about yours? We have taken this from zero till the end i.e. from We have taken this from zero till the end i.e. from zero till your four. Okay, so your zero till your four. Okay, so your Jab I - 4, what will be yours, zero will be Jab I - 4, what will be yours, zero will be one, you will be three, four will be one, you will be three, four will be okay, this will happen, isn't it, okay, this will happen, isn't it, all these all these all these both of them when we add them. We will see whether there are mines or not. Are there mines? There will be mines in this case also. There will be mines in this case also. There will be mines in this case also. So what will we do in the case of mines? We will not Because the index Because the index Because the index should not be in the minus but when you add these two then should not be in the minus but when you add these two then it will be four and you will get it will be four and you will get zero. Okay, in the first case we need only 0 and 4. zero. Okay, in the first case we need only 0 and 4. How to get zero? If we do I + How to get zero? If we do I + J then we will get zero. J then we will get zero. J then we will get zero. do this then we will get 4, these are the two we wanted, then in the second condition, what did we want, zero one, three four, we wanted right, so we came here again, what will happen to us, what will happen to us -3 and this will be ours, what will Three four will be this then Three four will be this then Three four will be this then look here I + J, in this case there will be minus, in this look here I + J, in this case there will be minus, in this case also there will be minus, in this case also there will be case also there will be minus, in this case also there will be minus, then what will happen in this case zero, minus, then what will happen in this case zero, then what will this be yours, three will be then what will this be yours, three will be in this case, in this case, okay then I. okay then I. okay then I. van So what will be your four in this case will be three four got it and zero van got this is what you wanted na let us see in a second here zero van three four this is what you Okay, so Okay, so Okay, so this is the condition we have done here, look, we will this is the condition we have done here, look, we will start from -1, less till M, we will do start from -1, less till M, we will do I + + count, we will take one and K, we will I + + count, we will take one and K, we will start from zero, less than the end, we will start from zero, less than the end, we will take S plus, we will see I + take S plus, we will see I + take S plus, we will see I + is your less, give it zero, then continue. When I + J, give your less greater, equals, you will be M, then it will be time break. We do not need to look further, that is, we will go till A, so we do Na, till here M will Na, till here M will Na, till here M will go till A, so we will not see, go till A, so we will not see, okay, okay, what will happen after that, what will happen after that, here you will see again whether here you will see again whether I + J is I + J is matching both in I + K, what if it is matching matching both in I + K, what if it is matching i.e. the overlapping part. i.e. the overlapping part. i.e. the overlapping part. he matching? Was he matching? Do corn plus plus and no in maximum account. What do you do? Update the account. Ok then you will be updated here. If your adervise is not matching then If it goes okay, If it goes okay, If it goes okay, then finally what will you do? Maximum you will then finally what will you do? Maximum you will return it here. Okay, I hope return it here. Okay, I hope you have understood the problem. If you you have understood the problem. If you liked the video, then please like, share liked the video, then please like, share and subscribe. Many people say that if and subscribe. Many people say that if you do not run and show it, then I you do not run and show it, then I you do not run and show it, then I also showing by running that it is yours to submit, it is ok
2024-03-21 10:42:01
718
https://i.ytimg.com/vi/E…axresdefault.jpg
718. Maximum Length of Repeated Subarray || Sliding Window || TC:o(mn) SC: o(1)
k5Im14rNUFA
Hello guys welcome to my video problem in half an hour school principal in half an hour school principal rickshaw rickshaw blurred multiple quality basically office let them between blurred multiple quality basically office let them between the left and right in this slide as an example to the left and right in this slide as an example to one's and supporters one's and supporters 1234 this 1234 this youth to-do list related to give till very youth to-do list related to give till very 153 153 153 Is The Activist Arundhati Maurya Three Elements Which Will Be Two Three Inch Plus Form No No No Answers For Multiple Subscribe Subscribe You Will Find The First And Subscribe You Will Find The First And Last Last Over All This When You Will Get Answers To All Over All This When You Will Get Answers To All Of Of Of Here Chappal Electricity Office And Takshashila Mountain In Recent Years Even Vikram So Let's Observed Across Mister Talented To Beawar Road Turn Off Switch Parts Of The No. 1 Class And Liberation Army Village That's Our Norms Victor Is Dust The Amazing Inside A Used For Used For This Is Used To Make The This Is Used To Make The Summary Of Summary Of The Chapter To Do The Use The Chapter To Do The Use Of Which Of Which Is The The The The Play List You Can Return Number Dot Big Be Play List You Can Return Number Dot Big Be Dot Big Guide Plus Loot Question A First Dot Big Guide Plus Loot Question A First Question Question and what you want to do you want to write what you want to include and what you want to do you want to write what you want to include or exclude Subscribe Finally Bigg Boss You Answer This Subscribe Finally Bigg Boss You Answer This Simple And Give You A This letter is given to the students by DC SP DS This letter is given to the students by DC SP DS This letter is given to the students by DC SP DS working ki Surajkund spine and SMS code and see its working on this occasion Sudhir WhatsApp problem all this prostate problem with his approach s every time but if any problem from time complexity while admitting then I will Have to I am fighting over all this element will have to hydrate over all elements ok so let's pray inquiry super career maximum your writing for all elements video prem* and time complexity of making and qualities you maximum guided over all the elements from i don't want Difficult Just doing turn off name every time makes it very positive Guddu It's interests of them into one time when you can improve time complexity Improve time for kids basically events to develop It's already sold in the villages located Sudhir Vats Radhe Restore The Radhe Restore The Radhe Restore The Duke 390 Mode Switch To Paani Next Time Duke 390 Mode Switch To Paani Next Time Aisi 151 Plus To Equal Than To Aisi 151 Plus To Equal Than To 363 Shyam 363 Shyam Time Aisi Time Aisi 16 Plus Ko Difficult And Spontaneous 16 Plus Ko Difficult And Spontaneous Word And Doing Paper Quilling Assam Word And Doing Paper Quilling Assam Artist Ok What Is This Are Meaningless Ko K Artist Ok What Is This Are Meaningless Ko K Swarnim Doing This App Will 10060 Someone Tell The First In Next End Someone Tell The First In Next End Someone Tell The First In Next End Singer Support Okay By Bigg Boss-1 Plus Singer Support Okay By Bigg Boss-1 Plus Two Give Me Three Now Taylor Index Of Two Time Two Give Me Three Now Taylor Index Of Two Time Singh Including Six Wickets Three Plus Two Plus One Gives Singh Including Six Wickets Three Plus Two Plus One Gives Milk That Deep Waters And Such Now In Milk That Deep Waters And Such Now In Third In Next Year Singer Sex Third In Next Year Singer Sex Third In Next Year Singer Sex Someone Plus Two Plus Plus Polytechnic He 12012 Help Reduce Knowledge Se Foreskin Mexico Or Not I Want The Time Between The Gaines 12345 Vibrator All This Element And Assam Back Water Into A Busy Schedule Look Pear 100MB Look At The Third And Extended To Two or Three Listen What Two or Three Listen What Two or Three Listen What is Mean Disruptive is Mean Disruptive Photo Volume My Time Stand Up Till the Up to Photo Volume My Time Stand Up Till the Up to the Second Value My Support OK But That Want I Want the the Second Value My Support OK But That Want I Want the Center Someone Like You Will Center Someone Like You Will Find That This Particular Volume and This Find That This Particular Volume and This Particular Value Print Android Particular Value Print Android Subscribe Distic and Destroy Subscribe Distic and Destroy Subscribe Distic and Destroy Man A Lips Middle Verify Happiness-Prosperity Dasham Between A Sworn In Gold Loot-Loot Third Intake Dasham Appeal 3D Extend OK Next Summary Text Me I Want The Song From The First To The Third And You Will Look At The Liquid 1001 Liquid 1001 Liquid 1001 And Orders From Someone To Keep Them In This And Orders From Someone To Keep Them In This World Channel Subscribe 10 2010 - 999 Safar Answer World Channel Subscribe 10 2010 - 999 Safar Answer You Can See But Two Plus Plus Form Is You Can See But Two Plus Plus Form Is Equal To 9 During Cigarette Co Police Youth Equal To 9 During Cigarette Co Police Youth Ki Bigg Boss Now This Third In Next What Ki Bigg Boss Now This Third In Next What Is A Vast Umpire Is A Vast Umpire Is A Vast Umpire and element stand what you want some of orders for animals what you want you can only marine elements of view after to remove samadhi di now 200 chennai express delink rating system up to third next hair removing them with all the best And You Get You An Answer Receiver Answer OK What Do You Speak Scheduled Casts And Modified Food Little But Another Factor Se Paun Inch Subscribe to subscribe and subscribe subscribe the the Video then subscribe To My Video then subscribe To My [Music] [Music] That Tractor Rituals for Advanced That Tractor Rituals for Advanced Scientific To How To Calculate Appreciates And Sorrow And Simple Person Succulent Samet Yusuf 12356 Question Recirculating At That Time Digits Stand For Others What They Want That To Point Is Equal To Zero Oil The Number Road Price Subscribe School Meeting Ka Tilak Particular Time To What We Will Then element element 66 is oh enemy love sad him cod salary to what will and wish them will play these figures listen for oneplus element training jaswant privacy in secondary 12th part plus two three layer riding on current Volume Waste Volume Waste Volume Waste Placement Yourself Improve Traffic Jam Lettuce Placement Yourself Improve Traffic Jam Lettuce Element ₹500 And The Current Element Element ₹500 And The Current Element Is Point To You Will Get Five The Is Point To You Will Get Five The Value Of The President 300 Five Plus Value Of The President 300 Five Plus Pimple 285 Rates Will Be Focal Point Its Pimple 285 Rates Will Be Focal Point Its Western And Southern Student Nurses Western And Southern Student Nurses Scientific Noida - One Will Not Scientific Noida - One Will Not Scientific Noida - One Will Not equal to zero is later just give light condition oh that is equal to 100 waste connection shift fennel IEA is just speak volumes of eye - 110 edit ok now crotch traffic absolutely low 210 itna This This This Code For Jab School Commented Last Will Not Code For Jab School Commented Last Will Not Take Into What Should We Do To Return Take Into What Should We Do To Return More Answer More Answer Story Click Subscribe Button On Right Side - - - 100 Giver If 100 Giver If Not Subscribe Not Subscribe 200 Grams Post Which Should Work Late Only 200 Grams Post Which Should Work Late Only Front Lagot And See Now Compiler Expected And Now Compiler Expected And Now Compiler Expected And Specification Specification A Woman And See What Is The Earth Africa Animation Hua Tha Hai Pimple Aur Laddu Conference Sewerage Working That Checked Shirt United Thank You Will Be
2024-03-24 10:01:13
303
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode Range Sum Query - Immutable || Intuition + Example + Code
A0g1ryt2lz0
hi everyone today we're gonna talk about one more question on binary search so one more question on binary search so name of the question as you can see is name of the question as you can see is search insert position this question is search insert position this question is a standard question and this question is a standard question and this question is from lead code from lead code let's read the question given a sorted let's read the question given a sorted array of distinct integers and a Target array of distinct integers and a Target value return the index if the target is value return the index if the target is formed if not return the index where it formed if not return the index where it would be if it was in inserted in the would be if it was in inserted in the order what this means is like for order what this means is like for example you have an example you have an let's take this example right example let's take this example right example number two where you have a sorted array number two where you have a sorted array one three five six and the target value one three five six and the target value is 2. S2 is not present in the array is 2. S2 is not present in the array what they want us to do is we want they what they want us to do is we want they want us to give us the index where this want us to give us the index where this target could be inserted in the array target could be inserted in the array such that after inserting the target such that after inserting the target value in the array the array still needs value in the array the array still needs to be in a sorted order so for example to be in a sorted order so for example in one three five six if you put the in one three five six if you put the target value 2 2 should be the second target value 2 2 should be the second element right because 1 2 3 5 6 will be element right because 1 2 3 5 6 will be then assorted array so the index at then assorted array so the index at which this target value needs to be which this target value needs to be inserted in the array is going to be inserted in the array is going to be index number one which will be your index number one which will be your output output if you look at the another example which if you look at the another example which is one three five six and the target is one three five six and the target value is 5 as 5 the target value is value is 5 as 5 the target value is already present in the array we have to already present in the array we have to just return the index at which we found just return the index at which we found this target value which is index number this target value which is index number two zero one two this is the index so as two zero one two this is the index so as you can see from the sample inputs and you can see from the sample inputs and outputs there are two things which are outputs there are two things which are clear one is the target value is there clear one is the target value is there we just need to give the index and the we just need to give the index and the index needs to be zero based index index needs to be zero based index meaning that we have to start the meaning that we have to start the indexing from 0 second is if the target indexing from 0 second is if the target value is not present in the array we value is not present in the array we need to give the index at which this need to give the index at which this target value can be inserted in the target value can be inserted in the array such that the resultant array array such that the resultant array still should remain sorted right so still should remain sorted right so these are two things we need we know these are two things we need we know again in the question they have again in the question they have mentioned that we have to do this using mentioned that we have to do this using what uh given the time complexity which what uh given the time complexity which they are looking at they want a Time they are looking at they want a Time complexity of O of login as you know of complexity of O of login as you know of login is a logarithmic time complexity login is a logarithmic time complexity and the most famous algorithm which and the most famous algorithm which takes logarithmic time complexity is takes logarithmic time complexity is binary search so this is a hint for us binary search so this is a hint for us to you know solve this question using by to you know solve this question using by research so let's see how we can you research so let's see how we can you know manipulate a standard binary search know manipulate a standard binary search algorithm to solve this question algorithm to solve this question this question actually employs you know this question actually employs you know one of the famous observation of binary one of the famous observation of binary search which we are going to see through search which we are going to see through a example let's take an example of an a example let's take an example of an array which is sorted one three four array which is sorted one three four seven nine and let's say we want to uh seven nine and let's say we want to uh you know find the target value 8. as you you know find the target value 8. as you can see 8 is not present in the array can see 8 is not present in the array let's try to apply a standard binary let's try to apply a standard binary search on this array and see what we get search on this array and see what we get the index are going to be 0 1 2 3 and 4. the index are going to be 0 1 2 3 and 4. as we know low at is the first index is as we know low at is the first index is going to be 0 high is going to be 4 going to be 0 high is going to be 4 middle value middle value can be 0 plus 4 by 2 which is 4 by 2 can be 0 plus 4 by 2 which is 4 by 2 which is nothing but two so a of mid which is nothing but two so a of mid as compared to your target value right a as compared to your target value right a of mid as you can see a of 2 is nothing of mid as you can see a of 2 is nothing but 4 so 4 and 8 so 4 is less than the but 4 so 4 and 8 so 4 is less than the target value if a of mid is less than target value if a of mid is less than the target value we are going to go and the target value we are going to go and search in the this half of your array search in the this half of your array right so what changes yours your low right so what changes yours your low becomes equal to Mid plus 1 right becomes equal to Mid plus 1 right pyramid is nothing but 2 2 plus 1 is 3. pyramid is nothing but 2 2 plus 1 is 3. so now we have low equal to so this is so now we have low equal to so this is one iteration right low equal to 3 and one iteration right low equal to 3 and high is going to be 4. high is going to be 4. yes now let's move on let's try to find yes now let's move on let's try to find out the middle value here metal is going out the middle value here metal is going to be 3 plus 4 Pi 2 which is nothing but to be 3 plus 4 Pi 2 which is nothing but 7 by 2 which is equal to 3 okay so two 7 by 2 which is equal to 3 okay so two threes are 6 so this is 3. so what is 3 threes are 6 so this is 3. so what is 3 what is a of mid which is your 3 at what is a of mid which is your 3 at third index we have number seven so third index we have number seven so let's compare seven let's compare seven and a Target value which is eight seven and a Target value which is eight seven and eight if you see what is the uh and eight if you see what is the uh relation 7 is less than the target value relation 7 is less than the target value if that's the case what we need to do if that's the case what we need to do again your low is equal to Mid Plus 1. again your low is equal to Mid Plus 1. right so if low is mid plus 1 initially right so if low is mid plus 1 initially low value was 3 numbered is equal to 3 low value was 3 numbered is equal to 3 so met plus one is nothing but 3 plus 1 so met plus one is nothing but 3 plus 1 which is equal to 4 high is also equal which is equal to 4 high is also equal to 4 correct if I have to find out to 4 correct if I have to find out middle of this obviously it's going to middle of this obviously it's going to be equal to 4 itself y because 4 plus 4 be equal to 4 itself y because 4 plus 4 by 2 which is nothing but 8 by 2 which by 2 which is nothing but 8 by 2 which is nothing but 4 correct so what is a of is nothing but 4 correct so what is a of four a of four is nine what is the four a of four is nine what is the relation between the middle value and relation between the middle value and the target value 9 is greater than 8. in the target value 9 is greater than 8. in this case what we do in a standard this case what we do in a standard binary search high is equal to Mid minus binary search high is equal to Mid minus one the value of your high is currently one the value of your high is currently four mid minus 1 is 4 minus 1 which is four mid minus 1 is 4 minus 1 which is equal to three so what we are looking at equal to three so what we are looking at is low equal to 4 and high is is low equal to 4 and high is pointing to 3. now this is going to this pointing to 3. now this is going to this is where a binary search a standard is where a binary search a standard binary search is going to stop why binary search is going to stop why because the condition low less than or because the condition low less than or equal to high is not satisfied by these equal to high is not satisfied by these values correct and we are going to values correct and we are going to usually we halt a binary search and we usually we halt a binary search and we return minus 1 outside the while loop I return minus 1 outside the while loop I hope you remember if not you can check hope you remember if not you can check out my video about the standard binary out my video about the standard binary search okay so what we're getting here search okay so what we're getting here is after you finish this this is where is after you finish this this is where you your binary search is going to stop you your binary search is going to stop now let's look at these values and let's now let's look at these values and let's revisit the array so the array we were revisit the array so the array we were started with this one three four seven started with this one three four seven nine so let's try here one three four nine so let's try here one three four seven nine let's write the you know um seven nine let's write the you know um what to say about the indices which we what to say about the indices which we can have is index 0 1 2 3 and 4. the can have is index 0 1 2 3 and 4. the target value which we were looking at target value which we were looking at was basically eight correct after the was basically eight correct after the binary search is over right your low is binary search is over right your low is pointing to index number four and you pointing to index number four and you see this flow is pointing to index see this flow is pointing to index number four think about this if you have number four think about this if you have part 2 insert the target value in this part 2 insert the target value in this sorted array how would your array you sorted array how would your array you know change and it would become 1 3 4 7 know change and it would become 1 3 4 7 after 7 we would have 8 and 9 why after 7 we would have 8 and 9 why because we want to maintain the sorted because we want to maintain the sorted uh sequence of the array indices would uh sequence of the array indices would be 0 1 2 3 4 and 5 right 8 would be be 0 1 2 3 4 and 5 right 8 would be inserted at index number four correct inserted at index number four correct and if you see somehow your low value and if you see somehow your low value after the binary source is over the low after the binary source is over the low index rate the low variable is also index rate the low variable is also having the value 4. can you see this yes having the value 4. can you see this yes so this is what actually happens in a so this is what actually happens in a standard binary search you know you do standard binary search you know you do not have to do anything this is one of not have to do anything this is one of the observation of a binary search the observation of a binary search algorithm in the standard binary algorithm in the standard binary research algorithm the if you are if the research algorithm the if you are if the target value is present in your array so target value is present in your array so obviously you are going to return from obviously you are going to return from mid right wherever you are conditioned mid right wherever you are conditioned your the middle value is equal to the your the middle value is equal to the Target value you return the index right Target value you return the index right which is the index or in which mid value which is the index or in which mid value is stored right if the target value is is stored right if the target value is not present and if you finish your not present and if you finish your binary research right the while loop is binary research right the while loop is over where this condition is no more met over where this condition is no more met what we do is after that whatever where what we do is after that whatever where the low index is pointing to is low the low index is pointing to is low index is actually pointing to that index index is actually pointing to that index where the target value should be where the target value should be inserted in the array such that the inserted in the array such that the array resultant array is in a sorted array resultant array is in a sorted format right so the answer to our lead format right so the answer to our lead code questions we were looking at here code questions we were looking at here this one search insert position would be this one search insert position would be a standard binary search algorithm as a standard binary search algorithm as you can see here the only difference is you can see here the only difference is your instead of returning -1 which we your instead of returning -1 which we usually do to say that we do not find we usually do to say that we do not find we have not found the element we are going have not found the element we are going to return the value low as we saw on the to return the value low as we saw on the Whiteboard that low is going to store Whiteboard that low is going to store the index where this target value needs the index where this target value needs to be inserted if this target value is to be inserted if this target value is already present in the array as usual already present in the array as usual whenever this condition is met a of net whenever this condition is met a of net is equal to equal to Target you can is equal to equal to Target you can simply return now the standard binary simply return now the standard binary search has a Time complexity of of login search has a Time complexity of of login I have used the iterative version so I have used the iterative version so space complexity is also constant which space complexity is also constant which is O of one so the entire solution has is O of one so the entire solution has been possible in oauth login been possible in oauth login time complexity hope this helps time complexity hope this helps let's look at one function you know let's look at one function you know which has been provided by Java that is which has been provided by Java that is called as arrays.binary search like called as arrays.binary search like similar to your arrays.sort Java similar to your arrays.sort Java provides us some standard functions uh provides us some standard functions uh you know which which actually has the you know which which actually has the implementation of binary search and log implementation of binary search and log of n time and that is binary search here of n time and that is binary search here you have to as you can see on the screen you have to as you can see on the screen you basically need to provide your this you basically need to provide your this function with an array of you know function with an array of you know integers like me if you want to sort integers like me if you want to sort your integer I mean you want to find your integer I mean you want to find some Target you know in your integer some Target you know in your integer array and the target value which you're array and the target value which you're looking at so this is going to you know looking at so this is going to you know give you an index which is again zero give you an index which is again zero based right so whenever you have a need based right so whenever you have a need like in this question which we just saw like in this question which we just saw where you just want to use a standard where you just want to use a standard binary search and not write the entire binary search and not write the entire code but simply you can use this code but simply you can use this function straight forward right one uh function straight forward right one uh interesting thing about this function is interesting thing about this function is that if a particular element which that if a particular element which you're trying to search okay if it is you're trying to search okay if it is not present in the array this function not present in the array this function is going to return you an index which is is going to return you an index which is negative but more importantly it returns negative but more importantly it returns in this particular format it returns in in this particular format it returns in the form format of minus insertion point the form format of minus insertion point minus 1. now what is insertion point the minus 1. now what is insertion point the insertion point is basically again which insertion point is basically again which we spoke about is the point the index at we spoke about is the point the index at which this target element would be which this target element would be present if I had to insert that Target present if I had to insert that Target value in my sorted array like for value in my sorted array like for example if I have an array like this example if I have an array like this which is sorted one three four seven which is sorted one three four seven nine and I wanted to like we took the nine and I wanted to like we took the same example right on the Whiteboard and same example right on the Whiteboard and if I wanted to you know insert the if I wanted to you know insert the number eight which is my target value in number eight which is my target value in this uh sorted array 8 would be actually this uh sorted array 8 would be actually inserted at index number 4 which is inserted at index number 4 which is after 7 there would be an 8 here right after 7 there would be an 8 here right so this particular so this particular um if you use arrays.binary search and um if you use arrays.binary search and you know send the element you know your you know send the element you know your target value as 8 what it is going to do target value as 8 what it is going to do is it is going to send you an index of is it is going to send you an index of minus 4 4 is where actually the 8 should minus 4 4 is where actually the 8 should have been inserted in your have been inserted in your um and sorted array and minus one so um and sorted array and minus one so basically 4 becomes insertion point so basically 4 becomes insertion point so minus insertion point minus 1 which is minus insertion point minus 1 which is equal to minus five so this area is not equal to minus five so this area is not buying research is going to then you buying research is going to then you know send you back minus 5 5. now as you know send you back minus 5 5. now as you know that whenever an element is not know that whenever an element is not found you know this function Aries or found you know this function Aries or binary search is going to return the binary search is going to return the negative value secondly there is a negative value secondly there is a standard in which it's going to uh you standard in which it's going to uh you know written like it's a formula you know written like it's a formula you know which it follows using this formula know which it follows using this formula you can definitely find out the you can definitely find out the insertion point right for example if I insertion point right for example if I because it's minus insertion point minus because it's minus insertion point minus 1 if I want to actually find out the 1 if I want to actually find out the index at which I should be inserting index at which I should be inserting this element in my sorted array would be this element in my sorted array would be minus whatever index it's returned like minus whatever index it's returned like for example minus of minus 5 plus for example minus of minus 5 plus basically minus of minus 5 plus 1 which basically minus of minus 5 plus 1 which is going to give you basically 4 right is going to give you basically 4 right let's run this app actually I have let's run this app actually I have already you know ran and got the output already you know ran and got the output here you can see it can be inserted at here you can see it can be inserted at index number four here you can see two index number four here you can see two uh you know lines saying the same thing uh you know lines saying the same thing and the reason is what I've done is you and the reason is what I've done is you know I have also also you know written know I have also also you know written the function search insert which is the function search insert which is taking the standard binary search right taking the standard binary search right which we just saw in Elite code uh which we just saw in Elite code uh solution so this is the code which I solution so this is the code which I have written using standard binary have written using standard binary search and and return low right whatever search and and return low right whatever function whatever value the search function whatever value the search insert does is the same value which I insert does is the same value which I can obtain using simple one like just can obtain using simple one like just two lines of code like calling you know two lines of code like calling you know standard arrays.binary search and then standard arrays.binary search and then applying this uh you know addition of applying this uh you know addition of one that's all right so you can keep one that's all right so you can keep that in mind whenever you have standard that in mind whenever you have standard binary search uh examples and you not binary search uh examples and you not need to write the entire code you can need to write the entire code you can simply use Addis dot binary search simply use Addis dot binary search similarly if you have a collection and similarly if you have a collection and you want to and it's sorted and you want you want to and it's sorted and you want to you know search in that collection to you know search in that collection again use similar like arrays.binary again use similar like arrays.binary search you also have search you also have collections.binary search which also collections.binary search which also functions in the similar manner hope functions in the similar manner hope this helps uh keep practicing and this helps uh keep practicing and subscribe to my channel bye
2024-03-20 08:50:26
35
https://i.ytimg.com/vi/A…axresdefault.jpg
Search Insert Position | Java | Leetcode 35 | Binary Search
ZNkquA2htPM
we're going to take a look at a legal problem called different ways to add problem called different ways to add parentheses so given a string expression parentheses so given a string expression of numbers and operators return all of numbers and operators return all possible results from computing all the possible results from computing all the different possible ways to group numbers different possible ways to group numbers and operators and operators together so you might return the answer together so you might return the answer in any order so you can see here we have in any order so you can see here we have an example right so you can see this an example right so you can see this this function that we're going to write this function that we're going to write it takes a string expression and we want it takes a string expression and we want to return it list of integer as a result to return it list of integer as a result of how many of how many numbers were right basically like how numbers were right basically like how many uh possible ways to group numbers many uh possible ways to group numbers and operators together right so you can and operators together right so you can see here one way we can do is basically see here one way we can do is basically we group you know the first two numbers we group you know the first two numbers right so right so two one once we get the you know the two one once we get the you know the total value of two minus one we can use total value of two minus one we can use that which is one minus one right so at that which is one minus one right so at the end we just get the total value of the end we just get the total value of one minus one which is zero right the one minus one which is zero right the other way we can do is we can group other way we can do is we can group those two ones together and this will those two ones together and this will give us zero so two minus zero give us zero so two minus zero right two minus the remaining value right two minus the remaining value which is going to be two right so you which is going to be two right so you can see we have two values so we can see we have two values so we basically try to keep track of all the basically try to keep track of all the sum right so we have a zero here we have sum right so we have a zero here we have a two here so at the end we're returning a two here so at the end we're returning that in a list of integer now you can that in a list of integer now you can see we have another complicated example see we have another complicated example here so you can see we have two times here so you can see we have two times three minus four times five so you can three minus four times five so you can you can see here one way we can do it is you can see here one way we can do it is we we can first get the sum or the value we we can first get the sum or the value of this which is 20 right once we get of this which is 20 right once we get that we can get 3 minus 20 which is that we can get 3 minus 20 which is negative 17 negative 17 and then negative 17 times 2 right which and then negative 17 times 2 right which is going to be is going to be negative 34 right so that's one way we negative 34 right so that's one way we can do it the other way we can do is can do it the other way we can do is maybe like we can you know start to maybe like we can you know start to group group by just this first right which is 20 by just this first right which is 20 right and then we can also group those right and then we can also group those two first so that's 6 minus 20 this will two first so that's 6 minus 20 this will give us 6 minus 20 will be will be give us 6 minus 20 will be will be negative 14 right so that's one way we negative 14 right so that's one way we can do it the other way we can do is can do it the other way we can do is maybe we can group those two right once maybe we can group those two right once we group those two together you can see we group those two together you can see this minus this will give us this minus this will give us negative one right so if we have two negative one right so if we have two times negative one times five right so times negative one times five right so in this case what's gonna happen is we in this case what's gonna happen is we can group those two together so that can group those two together so that will give us negative two times will give us negative two times five right or in this case we can also five right or in this case we can also group two times negative five right this group two times negative five right this will turn into negative five so in this will turn into negative five so in this case 2 times negative 5 will also give case 2 times negative 5 will also give us negative 10. so that's why you can us negative 10. so that's why you can see we have 2 negative 10 here right it see we have 2 negative 10 here right it doesn't matter if you group those two doesn't matter if you group those two together or those two together the end together or those two together the end result will give us two negative fives result will give us two negative fives here so and then the other thing we can here so and then the other thing we can also group is we can also group by also group is we can also group by this one right here so let's say we this one right here so let's say we group two times three first which will group two times three first which will give us six right so six minus four give us six right so six minus four times five times five okay and then what else we can do is okay and then what else we can do is maybe we can group those two together so maybe we can group those two together so that will give us two times five so this that will give us two times five so this will give us ten right and you might will give us ten right and you might also be thinking like okay what if what also be thinking like okay what if what if we just group if we just group you know like try to group four times you know like try to group four times five together maybe we have like six five together maybe we have like six minus 20 right but you can see 6 minus minus 20 right but you can see 6 minus 20 we already done it we already done it 20 we already done it we already done it like right here right because you can like right here right because you can see here see here uh in this case 6 2 2 times 3 is 6 uh in this case 6 2 2 times 3 is 6 4 times 5 is which is 20 so 6 minus 20 6 4 times 5 is which is 20 so 6 minus 20 6 minus 20 is negative 14. we already done minus 20 is negative 14. we already done it so we cannot have it so we cannot have you know duplicate group together right you know duplicate group together right so in this case it's pretty much we so in this case it's pretty much we already group those two together and we already group those two together and we also have to group those two together so also have to group those two together so we already done it so we don't have to we already done it so we don't have to do the same uh group together right do the same uh group together right basically we can have the same result basically we can have the same result value right but we cannot have the same value right but we cannot have the same grouping so in this case how come people grouping so in this case how come people to solve this problem so let's before to solve this problem so let's before let's talk about how we solve this let's talk about how we solve this problem let's look at the constraints problem let's look at the constraints right so the constraints you can see right so the constraints you can see here the expression.length which is the here the expression.length which is the size of the string is between 1 to 20. size of the string is between 1 to 20. and for the string we only have addition and for the string we only have addition subtraction and multiplication we do not subtraction and multiplication we do not have division at all so in this case uh have division at all so in this case uh so basically based on the constraints so basically based on the constraints right like there could also be a right like there could also be a situation where the expression or the situation where the expression or the input input uh that we have could be for example uh that we have could be for example maybe like just one number right like maybe like just one number right like one right if it's just one then the one right if it's just one then the output output should also should also be one right so that's something that be one right so that's something that the question didn't really you know that the question didn't really you know that we want to clarify we want to clarify uh before doing this question right if uh before doing this question right if it's just one num if just one value it's just one num if just one value right if there's only one value there's right if there's only one value there's no addition no subtraction at all then no addition no subtraction at all then we want to return the same value as it we want to return the same value as it is right is right but in this case we want to return a but in this case we want to return a list of lists of integers so in this list of lists of integers so in this case there's gonna be one case there's gonna be one and let's say input is you know let's and let's say input is you know let's say the input say the input is equal to um is equal to um in this case in this case 2 minus 1 right so the output should 2 minus 1 right so the output should just be like 1 right because there's no just be like 1 right because there's no way that we can group the only way we way that we can group the only way we can group is two minus one right can group is two minus one right so in this case you can see these are so in this case you can see these are some other examples and now let's take a some other examples and now let's take a look at how we can be able to solve this look at how we can be able to solve this problem problem so the brute force approach to solve so the brute force approach to solve this problem is basically we can travel this problem is basically we can travel with all the combinations that we have with all the combinations that we have right we can try with each and every right we can try with each and every single substring um basically single substring um basically for example in this case let's say we're for example in this case let's say we're breaking the string into half right breaking the string into half right let's say if i group those two strands let's say if i group those two strands together right or in this case those together right or in this case those elements together and those elements elements together and those elements together right and then i basically say together right and then i basically say this is the group that we have right this is the group that we have right maybe we can try with this combination maybe we can try with this combination and and and basically add our total value onto and basically add our total value onto like a result list or something right so like a result list or something right so in this case if we were to dfs down to in this case if we were to dfs down to this path uh what's going to happen is this path uh what's going to happen is you can see here we have fn right in you can see here we have fn right in this case we're going to call this this case we're going to call this function we want to continue you know function we want to continue you know try with all the combination for the try with all the combination for the left substring and we want to try all left substring and we want to try all the combination for the right substring the combination for the right substring so you can see here we're going down to so you can see here we're going down to two so f n2 is basically just two right two so f n2 is basically just two right and and for fn uh in this case the and and for fn uh in this case the function if we call the function for the function if we call the function for the for the right substring in this case for the right substring in this case with one minus one in this case we can with one minus one in this case we can continue breaking because you can see continue breaking because you can see there is operator right if there's an there is operator right if there's an operator we can continue to split into operator we can continue to split into half continuously and tap until we only half continuously and tap until we only have like just one number or in this have like just one number or in this case one uh single integer value and now case one uh single integer value and now we can basically just like return that we can basically just like return that integer uh list of integer value for integer uh list of integer value for this this sub for this string right back to the sub for this string right back to the original or the root function and then original or the root function and then in this case you can see one minus one in this case you can see one minus one is going to be zero and this is going to is going to be zero and this is going to be two two minus in this case the be two two minus in this case the operator is a minus sign so two minus operator is a minus sign so two minus zero is going to be two right so in this zero is going to be two right so in this case you can see if we go down to this case you can see if we go down to this branch the value will give us two okay branch the value will give us two okay if we go down to this branch if we go down to this branch okay so let's say if we were to go down okay so let's say if we were to go down this branch let's say if i group those this branch let's say if i group those two values together and this together two values together and this together right so based on this operator let's right so based on this operator let's split the string into the left half and split the string into the left half and the right half so it's kind of similar the right half so it's kind of similar to how we did it in our break problem to how we did it in our break problem uh you can see here we basically have uh you can see here we basically have two minus one right two minus one will two minus one right two minus one will give us one and then in this case for give us one and then in this case for one it's just one right so in this case one it's just one right so in this case two minus one is one one minus one is two minus one is one one minus one is zero so in this case this uh zero so in this case this uh this path will give us this path will give us a zero or in this case because one minus a zero or in this case because one minus one is zero right so you can see here we one is zero right so you can see here we have two combinations so let's say we have two combinations so let's say we have another example right so let's say have another example right so let's say we have two times three minus four times we have two times three minus four times five so in this case what we can do is five so in this case what we can do is that we can basically uh group the left that we can basically uh group the left substring right and the right substring substring right and the right substring um together and then basically try to um together and then basically try to come up with all the come up with all the you know all the all the possible you know all the all the possible combinations we can come up with combinations we can come up with for each and every single operator like for each and every single operator like we're trying to uh go down to all the we're trying to uh go down to all the combinations that we can come up with combinations that we can come up with right so you can see for each and every right so you can see for each and every single operator that we have right maybe single operator that we have right maybe we can just do like what we say what we we can just do like what we say what we exactly did on or break problem which we exactly did on or break problem which we break the string uh in half right so break the string uh in half right so based on this index right here in this based on this index right here in this case we know this is the operator we can case we know this is the operator we can split the string the left left substring split the string the left left substring and as well as the right substring and and as well as the right substring and then what we can do is that we can then what we can do is that we can basically try to try to calculate what basically try to try to calculate what are the total values of are the total values of you know of each and every single you know of each and every single parentheses that we add right or in this parentheses that we add right or in this case every every time we group a value case every every time we group a value together like what are some what are the together like what are some what are the total value right so in this case you total value right so in this case you can see where we have on the left we can see where we have on the left we have two right so this will this have two right so this will this function will return us two and then for function will return us two and then for our right we have three minus four times our right we have three minus four times five uh in this case you can see for five uh in this case you can see for each and we do the same thing for each each and we do the same thing for each and every single operator we continue to and every single operator we continue to split the string in half so we have split the string in half so we have three in this case you can see three three in this case you can see three this function will return us three and this function will return us three and then we group four five together and then we group four five together and three three individually together right so in this individually together right so in this case you can see four times five will case you can see four times five will give us 20. uh and in this case you can give us 20. uh and in this case you can see this will be three minus right see this will be three minus right because this this is a minus symbol uh because this this is a minus symbol uh 20 so 3 minus 20 will give us what will 20 so 3 minus 20 will give us what will give us give us uh in this case will give us 17 right uh in this case will give us 17 right and then we can also try with another and then we can also try with another combination which is three and four combination which is three and four together and then five individually so together and then five individually so we have a negative one here and a five we have a negative one here and a five right so this will give us what so this right so this will give us what so this will give us will give us um negative um negative five right because in this case it's a five right because in this case it's a multiplication symbol so in this case multiplication symbol so in this case you can see that for this function this you can see that for this function this will generate negative 17 and negative will generate negative 17 and negative five right and here it will give us two five right and here it will give us two so what we can do is that we can try so what we can do is that we can try with all the combination right so you with all the combination right so you can see here can see here we one way we can do is we can group two we one way we can do is we can group two together and then three four together together and then three four together and five or in this case you can see and five or in this case you can see uh we can also group two together and uh we can also group two together and then four five together and three then four five together and three together by by itself right so you can together by by itself right so you can see we have two combinations if we group see we have two combinations if we group those uh you know those elements those uh you know those elements together and this element together right together and this element together right so in this case you can see we're going so in this case you can see we're going to get 2 times to get 2 times negative 17 and 2 times negative 5 right negative 17 and 2 times negative 5 right so you can see we're trying with all the so you can see we're trying with all the same all each and every single same all each and every single combinations that we can come up with combinations that we can come up with right right so in this case uh once we try all the so in this case uh once we try all the combinations we're going to add it on to combinations we're going to add it on to the result list that we're going to the result list that we're going to return right to back to the root level return right to back to the root level so once we're back to the root level so once we're back to the root level what we're going to do is we're going to what we're going to do is we're going to try with another combination right maybe try with another combination right maybe this one and this one right here so 2 this one and this one right here so 2 times 3 which is 6 4 times 5 which is times 3 which is 6 4 times 5 which is 20. so in this case it's going to be a 20. so in this case it's going to be a list right so list of this and that so 6 list right so list of this and that so 6 times 20 which is basically uh in this times 20 which is basically uh in this case is a minus symbol so 6 minus 20 case is a minus symbol so 6 minus 20 will give us a will give us a negative 14 right so in this case what negative 14 right so in this case what we're going to do is we're going to uh we're going to do is we're going to uh return return you know a list of just only negative 14 you know a list of just only negative 14 in it and then we're going to return in it and then we're going to return back to the root level and we're going back to the root level and we're going to add that onto the um to add that onto the um right basically added on to the result right basically added on to the result list list so that's that and then we're gonna so that's that and then we're gonna backtrack and then we're going to try backtrack and then we're going to try with another combination maybe like for with another combination maybe like for example example uh let's say if i want to group those uh let's say if i want to group those elements together and this element right elements together and this element right here right so what's gonna happen then here right so what's gonna happen then is we're just going to see you can see is we're just going to see you can see we continue to break the string we continue to break the string down into smaller string right so you down into smaller string right so you can see we have two so we can basically can see we have two so we can basically group two together and three four right group two together and three four right or we can basically like two three or we can basically like two three together and four right and then you can together and four right and then you can see here we have two combinations uh in see here we have two combinations uh in this or in this yeah in this case we this or in this yeah in this case we have a list of size of two right because have a list of size of two right because in this case you can see we have two in this case you can see we have two times negative 1 which is going to be times negative 1 which is going to be negative 2 and we can also have like 6 negative 2 and we can also have like 6 minus 4 which is going to be 2 positive minus 4 which is going to be 2 positive 2. so we and here you can see it's just 2. so we and here you can see it's just going to be 5 right so it's going to be going to be 5 right so it's going to be negative 2 times 5 and negative 2 times 5 and 2 times 5 so this will give us a 2 times 5 so this will give us a negative negative negative 10 and positive 10 right so negative 10 and positive 10 right so we're just going to return that back to we're just going to return that back to here and we're going to add it on to the here and we're going to add it on to the result list right so basically you can result list right so basically you can see this is basically how we solve the see this is basically how we solve the problem using brute force and now let's problem using brute force and now let's take a look at the code so in this case take a look at the code so in this case you can see this is our brute force you can see this is our brute force solution in code right so in this case solution in code right so in this case we have different ways to compute so we have different ways to compute so this is our main function i basically this is our main function i basically add all of those symbols right all those add all of those symbols right all those characters onto the hash set characters onto the hash set um and then what we do is we also have um and then what we do is we also have expression array expression array in this case it's a character array and in this case it's a character array and then we basically convert the expression then we basically convert the expression into a character array right so a lot into a character array right so a lot easier to work with and we're basically easier to work with and we're basically passing down like an index right so in passing down like an index right so in this case we're starting like this case we're starting like like basically our our string is between like basically our our string is between zero to in this case the last character zero to in this case the last character index of the of our uh string right index of the of our uh string right expression right so what we do is we do expression right so what we do is we do our perform our dfs function it takes our perform our dfs function it takes the start and the end and then what we the start and the end and then what we do is we we have our result list that we do is we we have our result list that we want to return at the end and we iterate want to return at the end and we iterate from the start to the end from the start to the end and what we can do is that if the and what we can do is that if the current character is the operator current character is the operator right if it's operator then what we can right if it's operator then what we can do is that we can just did what we do is that we can just did what we exactly talked about right maybe this is exactly talked about right maybe this is the operator then what we're going to do the operator then what we're going to do is we're going to split the l we're is we're going to split the l we're going to you know calcula we're going to going to you know calcula we're going to dfs the left substring and then dfs the left substring and then calculate the right substring just like calculate the right substring just like how we did it in the merge sort uh how we did it in the merge sort uh video right we basically try to break video right we basically try to break the break the array down into smaller the break the array down into smaller pieces and then we compute it and then pieces and then we compute it and then we basically coming back up right so you we basically coming back up right so you can see this is sorry this is what we can see this is sorry this is what we did right we basically have operator set did right we basically have operator set we see that this character is an we see that this character is an operator then what we do is we're going operator then what we do is we're going to get the left list and the right list to get the left list and the right list right so it's going to be a list of right so it's going to be a list of integer and we try with all the integer and we try with all the combinations that we can do right in combinations that we can do right in this case maybe like for example just this case maybe like for example just like i mentioned before it could be like like i mentioned before it could be like in this case there is a in this case there is a two and there's a negative two right so two and there's a negative two right so maybe like two times five and negative maybe like two times five and negative two times five right there's many two times five right there's many combinations we want to try to get all combinations we want to try to get all the combinations in there right so and the combinations in there right so and then what we do is that let's say if then what we do is that let's say if there's a situation where it's just a there's a situation where it's just a number it's just a number for example if number it's just a number for example if it's just a two that we passing in then it's just a two that we passing in then it's just basically the the result it's just basically the the result the list of this the size of this list the list of this the size of this list is going to be zero right so what we can is going to be zero right so what we can do is we can basically just convert um do is we can basically just convert um the current value right in this case the current value right in this case it's just two if it's just two we can it's just two if it's just two we can just like convert it into just like convert it into a uh you know actual integer value and a uh you know actual integer value and add it on to the result and then we can add it on to the result and then we can just return result at the end right so just return result at the end right so that's basically what we can do uh let's that's basically what we can do uh let's say if there's a situation where we have say if there's a situation where we have a function a function right let's say let's let's just call right let's say let's let's just call dfs dfs so let's say dfs so let's say dfs and and let's say this thing is 23 or something let's say this thing is 23 or something right in this case what we know we this right in this case what we know we this this is not going to go here right this is not going to go here right because you in this case because you in this case uh the string that we're dealing with is uh the string that we're dealing with is 23 so let's say it's index 0 to 23 so let's say it's index 0 to 2 or something right or the last 2 or something right or the last character let's say is index 1. so in character let's say is index 1. so in this case we go here we know that in this case we go here we know that in this case this is not an operator right this case this is not an operator right so in this case 23 so in this case 23 so this is not operator and this is not so this is not operator and this is not operator then there is nothing we added operator then there is nothing we added onto the result list so the result list onto the result list so the result list is going to be empty so if it's empty is going to be empty so if it's empty we're just going to convert this this we're just going to convert this this string right here string right here into an integer value and add it onto into an integer value and add it onto the result right so it's pretty simple the result right so it's pretty simple and then here basically i call this and then here basically i call this calculate function this calculate calculate function this calculate function basically function basically uh calculates those two values right it uh calculates those two values right it will give us the total value of those will give us the total value of those uh it will give us a total a result uh it will give us a total a result value right so in this case value right so in this case based on the operator if it's a based on the operator if it's a multiplication addition multiplication addition subtraction we do what we have to do subtraction we do what we have to do right so if it's a multiplication we right so if it's a multiplication we times times addition we do plus subtraction we'll do addition we do plus subtraction we'll do minus in this case it will never go here minus in this case it will never go here because like the question states uh it because like the question states uh it will only have will only have multiplication addition and subtraction multiplication addition and subtraction right so this is right so this is the calculate function and then in this the calculate function and then in this case this is how we basically solve this case this is how we basically solve this problem using the uh the brute force problem using the uh the brute force approach right so this is how we solve approach right so this is how we solve the problem the problem and uh we know that the question says and uh we know that the question says it's going to be between 1 and 20. but it's going to be between 1 and 20. but let's say in this case the length of let's say in this case the length of expression.length is a lot bigger maybe expression.length is a lot bigger maybe like 100 or maybe like a lot more right like 100 or maybe like a lot more right that in this case how can we able to that in this case how can we able to improve the time complexity we know that improve the time complexity we know that it's going to be exponential but how can it's going to be exponential but how can people to improve further improve the people to improve further improve the time complexity time complexity um in this case let's say if the input um in this case let's say if the input scales right what we can do instead is scales right what we can do instead is maybe we can like try to cache this maybe we can like try to cache this right you can see here uh we basically right you can see here uh we basically compute four times five multiple times compute four times five multiple times right right or in this case four times right right or in this case four times five multiple times we know it's going five multiple times we know it's going to return us list with only 20 in it but to return us list with only 20 in it but let's say if the input is a lot bigger let's say if the input is a lot bigger maybe like maybe like like for example dot dot right in this like for example dot dot right in this case we have to have a lot more branches case we have to have a lot more branches that we're going to go down to so that we're going to go down to so in this case what we can do is we can in this case what we can do is we can cache this cache this um um so you can see here we have three minus so you can see here we have three minus four it's already computed three minus four it's already computed three minus four is already computed four is already computed uh uh we also have let's see here we also have we also have let's see here we also have like five already computed right five like five already computed right five already computed we also have like two already computed we also have like two times three also computed right so you times three also computed right so you can see we have a lot of things can see we have a lot of things duplicate computation right if the input duplicate computation right if the input is very large is very large let's say maybe like let's say maybe like you know what we can do is that we maybe you know what we can do is that we maybe we can be able to cache this right so we can be able to cache this right so what we can do instead is we can what we can do instead is we can basically create this function called basically create this function called get key and we have this cache which uh get key and we have this cache which uh the key is basically a the key is basically a type string and then the value is a list type string and then the value is a list of integers right because this is what of integers right because this is what the function is going to return right the function is going to return right integer integer list of integer values right that's what list of integer values right that's what we want to cache so in this case what we want to cache so in this case what we're going to do is that for our base we're going to do is that for our base case uh we first get our key right which case uh we first get our key right which is basically take this star and the and is basically take this star and the and the end right this is our start to start the end right this is our start to start end right we have put a comma in between end right we have put a comma in between uh and then what we do is we basically uh and then what we do is we basically say that uh we check to see if cache say that uh we check to see if cache contains this key right if it does we're contains this key right if it does we're gonna return that if it doesn't we're gonna return that if it doesn't we're gonna compute it gonna compute it and then we're going to save it onto our and then we're going to save it onto our cache and we're gonna return that cache and we're gonna return that computer value
2024-03-22 11:39:50
241
https://i.ytimg.com/vi/Z…axresdefault.jpg
[Java] Leetcode 241. Different Ways to Add Parentheses [Backtracking #13]
vHoNXYXVco8
hey everyone today i'll be going over lead code 1464 maximum product of two lead code 1464 maximum product of two elements in an array elements in an array so given an array of nums uh so given an array of nums uh you want to choose i and j of that array you want to choose i and j of that array uh return the maximum value of nums at i uh return the maximum value of nums at i minus 1 times nums of j minus 1. so very minus 1 times nums of j minus 1. so very confusing way to word it confusing way to word it i'll take a test case here i'll take a test case here it's very very simple to maximize the it's very very simple to maximize the product of a pair you just find the two product of a pair you just find the two biggest ones and multiply them biggest ones and multiply them for some weird reason it wants you to do for some weird reason it wants you to do minus one so this would be minus one so this would be you can see the two biggest are five and you can see the two biggest are five and four so five minus one four so five minus one times four minus one which is just you times four minus one which is just you know four times three which is 12. and know four times three which is 12. and that's the answer that's the answer um um so really all this problem is is find so really all this problem is is find the two biggest the two biggest uh subtract one from each of them and uh subtract one from each of them and then return the product then return the product so i'm going to do that so i'm going to do that and let's look at the constraints so and let's look at the constraints so there's going to be at least two there's going to be at least two uh uh each num each num is going to be a one or over is going to be a one or over so let's go uh first for first biggest so let's go uh first for first biggest and let's go second for second biggest and let's go second for second biggest and then all we're going to do and then all we're going to do is we're going to is we're going to iterate through numbs iterate through numbs and basically what we want to do and basically what we want to do is we want to check if this is the first is we want to check if this is the first biggest number so biggest number so if num is bigger than first if num is bigger than first uh let's just set both of these so we're uh let's just set both of these so we're gonna go uh first physique gonna go uh first physique and then the first biggest number now and then the first biggest number now becomes the second biggest number so becomes the second biggest number so second equals second equals first or actually uh rather we can go first or actually uh rather we can go first um we also want to check if it's greater than the second biggest uh if it is we can just go second equals number and then from here uh we just do exactly what it wants so first minus one times second one so just the first and second biggest uh multiplied and that'll be correct let's go ahead and that'll be correct let's go ahead and submit this and yeah it looks like it's pretty good so yeah like i said it's a very basic problem but yeah i just wanted to simplify it so i hope that helped thank
2024-03-21 02:54:03
1,464
https://i.ytimg.com/vi/v…axresdefault.jpg
Leetcode Solution - 1464 Maximum Product of Two Elements in an Array
OO_wrniY8Ts
Hello Everyone and Welcome Back to My Channel Algorithm Why Today I am Going to Algorithm Why Today I am Going to Write the Code and Also Explain to You the Write the Code and Also Explain to You the Algorithm to Solve This Zigzag Conversion Algorithm to Solve This Zigzag Conversion Problem Which is There in Lead Quote It is Problem Which is There in Lead Quote It is a Medium Level Problem and Has Been Asked a Medium Level Problem and Has Been Asked in in in Important for Interviews So let's start it by taking the name of Shri Krishna, in this question we will be given a string 'S' and an integer ' Namroz', okay whatever 'S' will be there, we will To make a zigzag pattern, To make a zigzag pattern, To make a zigzag pattern, like the letter which is on the zeroth index is like the letter which is on the zeroth index is placed on the zeroth row, then the letter which is on the first index is placed on the first row, then the one on the second is placed on the second row, then to make a zigzag pattern, the letter which is on the second row is placed on the second row. to make a zigzag pattern, the letter which is on the second row is placed on the second row. After the row which is before the second, that is the first After the row which is before the second, that is the first row, we will insert the next element in it, okay row, we will insert the next element in it, okay then for how long will we do this, we will keep going back then for how long will we do this, we will keep going back one by one and how long will we do this until one by one and how long will we do this until we get to the zeroth row, we get to the zeroth row, okay then like okay then like okay then like after that we will again start going down words. Okay, in row wise row, down words like from zero to one, one to one, one to two and when we make the opposite pattern of zigzag, that is, diagonal, then Row wise we will go up, okay like two to one, one to zero, Row wise we will go up, okay like two to one, one to zero, we will keep doing this, okay, this will be a very intuitive approach, one, we will take a variable with which we will add it to the string, and to create a row, we will take a string array, Let's run it and see Let's run it and see Let's run it and see how we will do it. Okay, so first of all we will how we will do it. Okay, so first of all we will create four days. Okay, four days. So let's create four days. Okay, four days. So let's assume that y is the string. Char assume that y is the string. Char is mt string. Let's assume for now. Okay, is mt string. Let's assume for now. Okay, what will we do now? We will take an i variable what will we do now? We will take an i variable from which from which from which Okay and what we will do in Nam Rose is first of all we will write a loop to go from top to bottom and then we will write a loop to go from bottom to top. So There will be a loop which will There will be a loop which will There will be a loop which will start from zero and will go start from zero and will go till Namroz, let's assume R, it is ok, R is not till Namroz, let's assume R, it is ok, R is not included, ok because it is 0 1 2 3 and included, ok because it is 0 1 2 3 and Namroz is four, ok so one from the bottom, sorry, Namroz is four, ok so one from the bottom, sorry, one from top to bottom, one loop. one from top to bottom, one loop. one from top to bottom, one loop. which will be from row to r and then we will write one for going from bottom to top. Now for going from bottom to top we will write that from where will it start, r is right from -2 like in this case It is It is It is starting from the second index. starting from the second index. We will have to add this letter in the second index row. If it We will have to add this letter in the second index row. If it is ok then how is the second index is ok then how is the second index coming? The number of rows is four. The coming? The number of rows is four. The index one before four will be our last index but index one before four will be our last index but we will have to add the last index. we will have to add the last index. we will have to add the last index. one before the last. Okay, so for the one before the last, we will again do one minus. If we had to take the last index, we would have done Namroz's minus. We have to take the one before that, so Namroz is doing minus. And where will it go from R Might to Row in And where will it go from R Might to Row in And where will it go from R Might to Row in which zero is again not included which zero is again not included because from zero a new pattern is because from zero a new pattern is starting, a new pattern starting, a new pattern is starting from zero, so we will again is starting from zero, so we will again enter values ​​in it through this loop, enter values ​​in it through this loop, right? right? right? First I was here, so I First I was here, so I put P here, okay, then I moved ahead, then put P here, okay, then I moved ahead, then Y, I put A on the bottom one, Y, I put A on the bottom one, okay, then I put W, then P again. okay, then I put W, then P again. okay, then I put W, then P again. instead of writing this again and again, we can understand it from what is already written. Okay, this four is okay, then we started with number minus two and then went backward in the row, so we have written number two. What was there after A? Then A was put. Okay, this loop ends at L. Now again the loop from zero to Namroz will continue, so from A to A, that loop will Okay, then if we make a zigzag one, we will put R and A. Okay, then only AG is played, so for NG, we will run it from zero to Namroz, but if I ends, then we will end that loop also. The string that will be formed will be The string that will be formed will be The string that will be formed will be like this, P will be written in the first row, like this, P will be written in the first row, OK, so here P I A is written OK, so here P I A is written in the answer, then in the second row, A L S I G will in the answer, then in the second row, A L S I G will be there, so here P is also written A L S I G, be there, so here P is also written A L S I G, then W A H R. then W A H R. then W A H R. AHR is written and then PE, then here also PE is written. Okay, so it will be completely like this. If we have to return this answer, then it is quite an intuitive approach, it If If If you divide it into four rows and we have to you divide it into four rows and we have to add letters, then let's code it. It add letters, then let's code it. It will be a simple code. Let's will be a simple code. Let's start by creating a string array. We will make start by creating a string array. We will make a string, er, answer, new string, and how many letters Then for int i is Then for int i is Then for int i is equal to equal to g. Now all the elements in this answer are null. Okay, so let's treat it with MT string. Then int a i 0 i is the variable with which Then int a i 0 i is the variable with which we are going to add. we are going to add. we are going to add. i will always be less than s dot length. Okay, now we write the loop int and int, take the index. Now i is already there, so the index should be less than number and the index will start from zero. Index Ps and index should be less than Namroz Ps and index should be less than Namroz Ps and index should be less than Namroz and there is another condition that the aa should and there is another condition that the aa should also be less than s dot length. Ok in this loop here the answer of index e is equal to addot here the answer of index e is equal to addot cut aa and aa ko i pe jo character. cut aa and aa ko i pe jo character. After adding it, After adding it, we have to increase aa. Next, we will we have to increase aa. Next, we will take another loop int index e equal to nam ro take another loop int index e equal to nam ro -2 now index should be greater than 0 -2 now index should be greater than 0 because new pattern will start from row which because new pattern will start from row which means repetition of the same pattern will start means repetition of the same pattern will start and and and in this then give again answer at index plus equal to a dat caret i p p ok last what will we do in this answer we will make all the strings in answer as a common string and return int sorry res plus equal to res plus equal to res plus equal to st r and then will return re. Let's st r and then will return re. Let's run it Sorry, here also a should be less than the dot length. sample test cases are being run. Submit and sample test cases are being run. Submit and see. and submit it successfully but and submit it successfully but before leaving please don't forget to like the before leaving please don't forget to like the video and subscribe to my channel also video and subscribe to my channel also tell me my improvement points in the tell me my improvement points in the comment section datchi
2024-03-18 11:36:02
6
https://i.ytimg.com/vi_w…xresdefault.webp
6. Zigzag Conversion | Leetcode | Medium | Java | String | Google
4g6lBUjRIfk
okay so lead code practice time easy question closes binary search tree easy question closes binary search tree value value um if you have um seen the previous um if you have um seen the previous video video two goals similar as previous videos two two goals similar as previous videos two goals the first one goals the first one is to find the solution for this is to find the solution for this specific problem specific problem and put some solid code there and the and put some solid code there and the other one other one is to see how to is to see how to solve the problem properly during solve the problem properly during interview interview so let's get started the first step so let's get started the first step is always to clarify the problem with is always to clarify the problem with your interview your interview with the interviewer if it is not clear with the interviewer if it is not clear to you to you and try to fully understand the problem and try to fully understand the problem at the same time think about some ash at the same time think about some ash cases cases which could be pretty special and then which could be pretty special and then after that it is about finding the after that it is about finding the solution solution so finding solution parts you will need so finding solution parts you will need to find the solution to find the solution yourself mostly by yourself and yourself mostly by yourself and communicate with your interviewer communicate with your interviewer run through some uh time space run through some uh time space complexity analysis complexity analysis etc and also etc and also um and also after the communication with um and also after the communication with your interviewer your interviewer um if you're both okay with that uh it um if you're both okay with that uh it is the next step which is doing some is the next step which is doing some solid code so you turn your id into the solid code so you turn your id into the solid code solid code and um during this time we care about and um during this time we care about the speed the speed the uh the the uh the the speed the the readability of the the speed the the readability of the code and also the correctness of the code as well and last part is about testing you explain your code using some sample test case do some sanity check and set up some test cases to have enough test coverage so let's take a look at this this example so exam questions so given a non-empty binary search tree it give me bst and the target value find the value in the bsd that is closest to the target so given target value is a floating point and you're guaranteed to have only one unique value in the bsd that's closest to the target which means so this one this one means that the the the bst is never going to be empty so at least one note okay so having said that the ash case i don't think there is too much of dash case to be fined to be found because um it is guaranteed the tree is not empty so that's only as case i could think about but it's not empty uh based on the notes and thus and then we try to find the solution of the problem so it says it's bst so usually it is binary search um so you start from the root if um the target is smaller than the root then you go to the left branch otherwise you go to the right branch and at the same time you keep track of the closest value using a variable so i would say the runtime is going to be linear to the height of the tree and let's do some solid code for this so for this one we don't need to check whether the root is empty whether it's a non-pointer because it says guaranteed to have a unique value so let's see for okay so um well uh okay so how to do that all right so how to start okay so well um root is not equal to none um the thing here is we are going to put the thing called the let's see closest uh glow this is equal to root dot value um if so we will say um if so we will say i would say closest is equal to i would say closest is equal to um closest so root dot value minus let's say mass. um this one if this one is closest minus closest minus target if target if the root value is closer then you assign the root value is closer then you assign the root value the root value as the closest otherwise we will keep as the closest otherwise we will keep the closest the closest as it is all right other as it is all right other so and then if so and then if the target is smaller than the target is smaller than root dot value then we are going to root dot value then we are going to the left branch is equal to root the left branch is equal to root the left otherwise uh we are going the left otherwise uh we are going into the right branch into the right branch root is equal to the roof top right root is equal to the roof top right and finally we just return closest and finally we just return closest so we're pretty much go complete with so we're pretty much go complete with this let's take a look this let's take a look um take a look at one example um take a look at one example to see how the code is going to work so to see how the code is going to work so let's say let's say we have the root we have the tree like we have the root we have the tree like this and this and we are trying to find target as 3.714 we are trying to find target as 3.714 and the first of all closes is equal to and the first of all closes is equal to four four and they say and then we step into this and they say and then we step into this um um while loop so first of all while loop so first of all we say so first of all we will see we say so first of all we will see so because it it is still the root so because it it is still the root so we can skip this checking actually so we can skip this checking actually uh we will see the target is smaller uh we will see the target is smaller than the root so it is going to than the root so it is going to snap into this branch so it has a two snap into this branch so it has a two uh which is the two the node is two uh which is the two the node is two and uh and then we do this and uh and then we do this uh comparison and we see uh comparison and we see four is closer than 2.7 four is closer than 2.7 uh okay so if this one is smaller then uh okay so if this one is smaller then you you have the roots so if have the roots so if if current one is closer then the if current one is closer then the current closes then you're going to have current closes then you're going to have okay so that that's right okay so that that's right and now we have 2 3.7 larger than 2 and now we have 2 3.7 larger than 2 then we go to this node with number s3 then we go to this node with number s3 and we see that 3 is still not and we see that 3 is still not closer than the current closes which is closer than the current closes which is four um four um then it closes still four so we return then it closes still four so we return four at this moment four at this moment so let's do a submission okay so it is so let's do a submission okay so it is good good and um and that's it for this coding and um and that's it for this coding question so regarding the task is set up question so regarding the task is set up uh i would say since the note says uh i would say since the note says and it's definitely not the empty tree i and it's definitely not the empty tree i would say would say some gender tree um it's general bst some gender tree um it's general bst um so i would say one example um so i would say one example like this um would be pretty much pretty like this um would be pretty much pretty enough enough it would be pretty enough regarding the it would be pretty enough regarding the tax coverage i think tax coverage i think because it touches the if and else because it touches the if and else branch as well branch as well um so that's it for this coding question um so that's it for this coding question if you like this video if you like this video please give me a thumb up and thanks for please give me a thumb up and thanks for watching
2024-03-22 12:29:16
270
https://i.ytimg.com/vi/4…axresdefault.jpg
Microsoft Coding Interview Question | Leetcode 270 | Closest Binary Search Tree Value
a4FqZG_-vFw
hey hey everybody this is larry this is me going over me going over q3 of the recent weekly contest 207 q3 of the recent weekly contest 207 uh hit the like button to subscribe and uh hit the like button to subscribe and join me on discord and let me know what join me on discord and let me know what you think about this farm you think about this farm uh maximum non-negative product in the uh maximum non-negative product in the matrix uh so matrix uh so for this problem uh for this problem uh i would recommend so there are a couple i would recommend so there are a couple of problems in last couple of contests of problems in last couple of contests where it's just you know you're given an where it's just you know you're given an array instead of a matrix array instead of a matrix uh and the key thing to notice is that uh and the key thing to notice is that you're going to move right or down so you're going to move right or down so basically you're constructing basically you're constructing different paths but different arrays so different paths but different arrays so you so if you haven't you so if you haven't if you're unable to solve this i if you're unable to solve this i recommend um going over the maximum recommend um going over the maximum non-negative product in an array and non-negative product in an array and then understanding that solution then understanding that solution and it will help you with the insight and it will help you with the insight for this solution that's how i kind of for this solution that's how i kind of figured it out um and the short answer figured it out um and the short answer for this problem is dynamic programming for this problem is dynamic programming i actually didn't implement this in a i actually didn't implement this in a good way good way i i so and i will go over the code in a i i so and i will go over the code in a second second so basically the idea is that in each so basically the idea is that in each each state is well each state would be x each state is well each state would be x y on the coordinates and also um y on the coordinates and also um and also whether you need a negative and also whether you need a negative number or not right number or not right and once you phrase that it becomes a and once you phrase that it becomes a lot easier to understand and write the lot easier to understand and write the recurrence that's how i always recurrence that's how i always try to think about it um but if you try to think about it um but if you watch me stop this live during the watch me stop this live during the contest contest i actually struggle because i i asked i actually struggle because i i asked the wrong question a little bit the wrong question a little bit um or not i wasn't it wasn't clear in my um or not i wasn't it wasn't clear in my head what the question was head what the question was and that's why you know for these kind and that's why you know for these kind of problems if you're trying to find of problems if you're trying to find figure out the transition you have to figure out the transition you have to ask the solutions very precisely ask the solutions very precisely otherwise you're going to get have to otherwise you're going to get have to mingle with r51s and mingle with r51s and weird edge cases and weird bass cases weird edge cases and weird bass cases and so forth so then and so forth so then so for this one uh and also if i look at so for this one uh and also if i look at it again i might have split into two it again i might have split into two functions functions but basically if negative uh this f but basically if negative uh this f or if i guess and also i should call or if i guess and also i should call this positive and sub-negative that may this positive and sub-negative that may have been a little bit have been a little bit better but but if the input is positive better but but if the input is positive that means that that means that we want the max max we want the max max positive answer uh positive answer uh from this help uh from this call right from this help uh from this call right uh if negative uh if negative or and it's actually technically not or and it's actually technically not negative you want to call that because negative you want to call that because you want to you want to get the max right if negative then we get the max right if negative then we want want men uh negative answer and min negative answer means the max and min negative answer means the max absolute answer uh so that's kind of why absolute answer uh so that's kind of why i i uh that way and i probably could have uh that way and i probably could have simplified swing a bit if i simplified swing a bit if i did it that way but um but yeah and then did it that way but um but yeah and then all it is is after that it's just going all it is is after that it's just going from left to right from left to right i think one additional thing to note is i think one additional thing to note is that uh because the that uh because the grid ij can only be up to four uh i mean grid ij can only be up to four uh i mean they don't tell you this they don't tell you this you know they asked you to mod uh and you know they asked you to mod uh and also on javascript it may be a little also on javascript it may be a little bit weird so this is not true for bit weird so this is not true for javascript so it's a little bit javascript so it's a little bit weird to be honest but for a lot of weird to be honest but for a lot of other languages other languages notice that it is up to four in my notice that it is up to four in my maximum value maximum value and that those columns you go to 15 and that those columns you go to 15 meaning the longest path meaning the longest path it's all only going to be about 29 or 30 it's all only going to be about 29 or 30 even even and 4 to the 30 is equal to 2 to the 60 and 4 to the 30 is equal to 2 to the 60 and 2 to the 60 of course fits in a and 2 to the 60 of course fits in a 64-bit int 64-bit int right so those are the constraints that right so those are the constraints that i would think about and that's why you i would think about and that's why you can mod it at the very end can mod it at the very end instead of like modding it progressively instead of like modding it progressively which leads to other which leads to other type of issues as well which in this type of issues as well which in this problem you don't have to think about it problem you don't have to think about it luckily luckily but yeah uh so basically once you have but yeah uh so basically once you have these questions these questions uh the transition becomes easier uh for uh the transition becomes easier uh for base cases right if you go out of bounds base cases right if you go out of bounds if you want a negative answer you want if you want a negative answer you want basically the opposite as a base case so basically the opposite as a base case so that you never return this answer that you never return this answer basically this is a standard value that basically this is a standard value that should never happen should never happen so so you should return the so so you should return the the infinite the positive infinity the infinite the positive infinity number which i have this but i should number which i have this but i should have really rewritten it have really rewritten it uh and i have the negative infinity uh and i have the negative infinity answer instead right answer instead right so let's actually maybe do a little bit so let's actually maybe do a little bit in refactor in refactor um so let's return infinite uh and this is this feels a little bit backward because you you basically don't want this to ever be to answer your return unless there's no other choice so that's why if you want a negative answer you return to you know the opposite of what you want uh and then the base case the other base case and this is for if you go a bounce right and the other base case is let's say you get to the corner uh if you want them and again this is where we can go back to the question right if we want the negative and the the number that the the number at the corner is negative then we could just return the number right or zero i suppose actually but uh and i actually double checked during the contest and if you want a positive answer and the grid number is positive then you just return that value uh otherwise again this is the same as this though it's went differently because i'm awkward um but yeah and where i confused a little bit was that i actually initially if you look at me during the contest i solved it like this but but now now that you have this recurrence this becomes a little bit easier to reason um which is that you know basically if the the good answer if the current grid value is negative then we want to swap the what we want right because uh and we actually we should have this doesn't even i don't know i guess i should have uh combined these two things no it's okay but yeah but basically if no it's okay but yeah but basically if if you want the negative if you want the negative answer as we said then we want the answer as we said then we want the minimum negative answer so minimum negative answer so we take the min of the current value we take the min of the current value times times uh this function which uh this function which um which yeah if this is negative then um which yeah if this is negative then you'll you'll you know basically you want the minimum you know basically you want the minimum negative answer from from this call negative answer from from this call right right and if it is positive you do the same and if it is positive you do the same except for max so that's why the max and except for max so that's why the max and the min are different the min are different and that's why the confusion here would and that's why the confusion here would not be great because this is not what not be great because this is not what you you that's not your input right so you're that's not your input right so you're returning a wrong input so yeah so returning a wrong input so yeah so that's pretty much the transition that's pretty much the transition uh and this transition of going uh uh and this transition of going uh bottom and to the right bottom and to the right there are a lot of legal problems uh there are a lot of legal problems uh that deals with uh that kind of that deals with uh that kind of transition so i definitely recommend you transition so i definitely recommend you go for it but basically the question you go for it but basically the question you you know uh recursion is and dynamic you know uh recursion is and dynamic programming and record uh memorization programming and record uh memorization is just rephrasing the question in a way is just rephrasing the question in a way that you can ask a different question that you can ask a different question by itself which means that okay if i go by itself which means that okay if i go down down and i want a negative value you know how and i want a negative value you know how do i go right do i go right or like what's the what's the smallest or like what's the what's the smallest negative value if i go down negative value if i go down and what's the smallest negative value and what's the smallest negative value when i go go to the right and so forth when i go go to the right and so forth so that's kind of the way that um yeah so that's the kind of the answers that um this would give us so yeah because if if uh the new because if this is negative we want our input to be the opposite of whatever so that we kind of keep on uh alternating um yeah uh so then and then at the very end if this is greater than uh well it's close to the infinity my previous infinity value then we return negative one uh for not possible um and then otherwise we just return the answer mod the mod value uh and we kick off in the corner with asking for non-pi or sorry not negative so positive value um so what is the so what is the complexity here right well if you look at this function uh everything we just do a constant amount of time so this is going to be o of one and then now we look at the so work per core is equal to o of one so how many possible inputs are there well there's rows times columns and negative it's two right so uh number of possible cause is equal to uh rows times columns times two for positive and negative so which is equal to over r times c uh or you know or 15 squared in this case so yeah so that means that total work is equal to of of r times yeah you can actually reduce the space a yeah you can actually reduce the space a little bit more by noticing this only little bit more by noticing this only goes goes left uh yeah this only goes right and left uh yeah this only goes right and down uh down uh so you could rewrite it bottoms up with so you could rewrite it bottoms up with dynamic programming dynamic programming to even reduce the space complexity more to even reduce the space complexity more uh and the space of course in this case uh and the space of course in this case it's just the number of possible cause it's just the number of possible cause because we store one cell for each one because we store one cell for each one so so yeah so this is time complexity so so yeah so this is time complexity and space complexity it is and space complexity it is you go to all of one per per core you go to all of one per per core and given that we have all of r times c and given that we have all of r times c core core uh this is equal to of our c uh this is equal to of our c uh space complexity and again uh space complexity and again you can upsell by converting this these two bottoms up uh and with that you can observe more by uh using the space of optimization technique uh so yeah so i'll link below on that dynamic programming progression uh tutorial that i have um but in terms of explaining this problem that's all i have uh let me know what you think of the like button hit the subscribe button and you can watch me solve the problem live during the contest next after i press the button thank you oh this is sounds like it's annoying oh sorry i keep my mind so let's do that only one non-negative so zero is okay maybe this so let's see let's see oh what uh yes that doesn't look very bad that doesn't look very bad well this is fine but i've gotten signs well that's not that way my base case [Music] okay that's good but just so makes sense why is that this should be huh yeah okay that's just oh this is it should be just 325. this is true it goes here this is true we're looking for a true negative other thing here other thing here this is still true so no this should be that's why okay it was negative okay it was negative one okay i need this to be bigger so hey uh yeah so that was the end of me solving this from during the contest uh thanks for watching hit the like button hit the subscribe button join me on discord ask me questions let me know how you you did how you feel uh and i will see you during the next problem
2024-03-21 14:50:21
1,594
https://i.ytimg.com/vi/a…axresdefault.jpg
1594. Maximum Non Negative Product in a Matrix (Leetcode Medium)
RyBM56RIWrM
hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today we're going to be solving a binary we're going to be solving a binary question question counting bits and this is one of the counting bits and this is one of the binary questions from the blind 75 list binary questions from the blind 75 list that we've been tracking in the that we've been tracking in the spreadsheet so we will finally be adding spreadsheet so we will finally be adding a a video solution to this binary problem video solution to this binary problem i'm pretty sure it used to be a medium i'm pretty sure it used to be a medium problem which is why it's highlighted problem which is why it's highlighted yellow but i think it got changed to an yellow but i think it got changed to an easy problem easy problem so the statement is pretty simple we're so the statement is pretty simple we're given an integer n and we want to return given an integer n and we want to return an answer array of length n plus one an answer array of length n plus one basically a value for every integer in basically a value for every integer in the range from zero the range from zero all the way up until n so if n happened all the way up until n so if n happened to be to be zero then we would just return a single zero then we would just return a single integer if integer if zero happened to be two then we would zero happened to be two then we would return three integers for return three integers for zero one and two and basically for every zero one and two and basically for every value value in this range zero to n so if n was two in this range zero to n so if n was two we would have three values in that range we would have three values in that range zero one two for each of these values we zero one two for each of these values we want to know what want to know what is the number of ones in the binary is the number of ones in the binary representation representation of this particular integer now what's of this particular integer now what's the binary representation of zero it's the binary representation of zero it's of course just of course just zero right you could add multiple zeros zero right you could add multiple zeros but it's but it's still going to be zero what's the binary still going to be zero what's the binary representation of one representation of one it's going to be just one right you it's going to be just one right you could have some leading zeros we could could have some leading zeros we could have as many as we want have as many as we want but at the end it's just going to end but at the end it's just going to end with a single one so there's only with a single one so there's only one occurrence of the integer one in the one occurrence of the integer one in the binary representation of 0. binary representation of 0. so so far our output is going to look so so far our output is going to look something like 0 something like 0 1 and then now we just need the number 1 and then now we just need the number of ones in the binary representation of of ones in the binary representation of 2. 2. the binary representation of 2 is going the binary representation of 2 is going to look like this 1 to look like this 1 0. you could have some leading zeros but 0. you could have some leading zeros but this is the main part that we're looking this is the main part that we're looking at so at so it just has a single one so then the it just has a single one so then the output is going to be output is going to be one for that so the array that we would one for that so the array that we would return is going to look something like return is going to look something like this this zero one one now the brute force way to zero one one now the brute force way to solve this problem solve this problem is going to be n log n and that solution is going to be n log n and that solution is going to look something like this is going to look something like this let's say we had an arbitrary let's say we had an arbitrary value such as 2 or maybe even 3 right we value such as 2 or maybe even 3 right we know the know the binary representation of 3 is going to binary representation of 3 is going to look like 1 look like 1 1 right so how are we going to count the 1 right so how are we going to count the number of ones number of ones in the binary representation of three in the binary representation of three well we first let's get the ones place well we first let's get the ones place right is this gonna right is this gonna is this gonna be a one or a zero how can is this gonna be a one or a zero how can we get that well we can take three we get that well we can take three mod it by two which is gonna give us one mod it by two which is gonna give us one so we have at least so we have at least one one here right so we already looked one one here right so we already looked at this position so what we do is at this position so what we do is basically cross it out and then we just basically cross it out and then we just want to look at the remaining want to look at the remaining portions now how can we actually do this portions now how can we actually do this uh like what kind of operation can we do uh like what kind of operation can we do basically if you take basically if you take three and divide it by 2 integer three and divide it by 2 integer division here division here and most programming languages will do and most programming languages will do this basically by integer division this basically by integer division what that's going to do to this integer what that's going to do to this integer is it's basically going to take that is it's basically going to take that ones place and remove it ones place and remove it take the remaining bits and then shift take the remaining bits and then shift it to the right so it basically does it to the right so it basically does exactly what you would want to do exactly what you would want to do and of course what do we get when we and of course what do we get when we take 3 and divide it by 2 take 3 and divide it by 2 integer division is going to give us a 1 integer division is going to give us a 1 so we're basically going to get this so we're basically going to get this and when you look at that yes this is and when you look at that yes this is the binary representation of 1 the binary representation of 1 right so now we're gonna take this and right so now we're gonna take this and mod it by two as well we're taking one mod it by two as well we're taking one modding it by two that's also gonna be a modding it by two that's also gonna be a one one so so far we've counted two different so so far we've counted two different ones for this integer ones for this integer and again we're gonna take this uh and again we're gonna take this uh this one's place now and chop it off and this one's place now and chop it off and now we're left with a single zero so if now we're left with a single zero so if you take one you take one divided by two yes you get zero once we divided by two yes you get zero once we get to zero that's how you know when get to zero that's how you know when we're stopping we're stopping right there's obviously in zero there's right there's obviously in zero there's no more ones no more ones in zero so basically we counted two in zero so basically we counted two different ones different ones so that's how we would do it for every so that's how we would do it for every particular integer the example i showed particular integer the example i showed right now is three right now is three and to get this the time complexity is and to get this the time complexity is log log n because for any integer n how many n because for any integer n how many times can you divide it by two well of times can you divide it by two well of course course that's just log base two n now we don't that's just log base two n now we don't really worry too much about the base really worry too much about the base usually but yes it's gonna be log n usually but yes it's gonna be log n log base two n that's how many times we log base two n that's how many times we could divide any particular integer could divide any particular integer n by two and of course we know we're n by two and of course we know we're doing this for a bunch of integers in doing this for a bunch of integers in the range the range all the way from 0 to n so we're doing all the way from 0 to n so we're doing this n times this n times doing a log n operation n times doing a log n operation n times is going to be time complexity and log n is going to be time complexity and log n now there's some repeated work now there's some repeated work that we can eliminate that you can that we can eliminate that you can easily recognize when you actually draw easily recognize when you actually draw out the bit mappings out the bit mappings the the binary representations of a the the binary representations of a bunch of integers and with that repeated bunch of integers and with that repeated work we can actually get a working o of work we can actually get a working o of n n solution let me show you that right now solution let me show you that right now now i just drew out the binary now i just drew out the binary representations from zero all the way up representations from zero all the way up to eight so we know that of course to eight so we know that of course zero has zero ones in the binary zero has zero ones in the binary representation representation when you get to one we have one when you get to one we have one occurrence of one in its binary occurrence of one in its binary representation for two we have representation for two we have one for three by looking at this we can one for three by looking at this we can see we have two different ones see we have two different ones and now when you get to four you really and now when you get to four you really start to notice how we are doing this start to notice how we are doing this repeated work repeated work notice how for four all the way to seven notice how for four all the way to seven we have a we have a one in this place right in the most one in this place right in the most significant place significant place we have a one and notice how the we have a one and notice how the remaining portion remaining portion of this and then this and then of this and then this and then this and this these four this and this these four are just repeats of the previous four are just repeats of the previous four that we calculated right because that we calculated right because we're you know we're counting zero zero we're you know we're counting zero zero adding a one adding a one right to four when you add a one you right to four when you add a one you just change it to this from four when we just change it to this from four when we add a two add a two we get this which is basically the we get this which is basically the binary representation of two itself binary representation of two itself right and then you get a one zero and right and then you get a one zero and then you get a one then you get a one one which is matching over here so now one which is matching over here so now looking at it this is the binary looking at it this is the binary representation of representation of four right there's just a single one in four right there's just a single one in this position this position so if we wanted to take zero and add so if we wanted to take zero and add four to it we would just four to it we would just to take this position and add a one here to take this position and add a one here right that will take us right that will take us four positions ahead and if you had a four positions ahead and if you had a one one and you and you changed this bit to a and you and you changed this bit to a one we're adding four to it so you can one we're adding four to it so you can take take a one and change it to a five by taking a one and change it to a five by taking that bit that bit so similarly when we get to four so similarly when we get to four we know that yes we're gonna have one we know that yes we're gonna have one extra one extra one in this position right because we just in this position right because we just got this one this one represents a four got this one this one represents a four this is the most significant bit so far this is the most significant bit so far but for the remaining ones all we have but for the remaining ones all we have to do to do is take this offset it by four is take this offset it by four and get here and count how many ones and get here and count how many ones were over here so when we're calculating were over here so when we're calculating how many ones how many ones for four we're just saying it's one plus for four we're just saying it's one plus the number of bits at position the number of bits at position zero how many bits how many ones were in zero how many bits how many ones were in position zero that's our dp so you can position zero that's our dp so you can see this is a dynamic programming see this is a dynamic programming problem because we're using the previous problem because we're using the previous results that we calculated results that we calculated to compute the new results in other to compute the new results in other words this is going to be 1 words this is going to be 1 plus dp of n minus plus dp of n minus 4 and actually when you look at this 5 4 and actually when you look at this 5 we're also offsetting it by 4 to get we're also offsetting it by 4 to get these two right because that's what's these two right because that's what's going to match up with going to match up with this which is going to tell us how many this which is going to tell us how many ones are going to go here right so and ones are going to go here right so and clearly clearly we see that that's a 1. so here we're we see that that's a 1. so here we're going to compute going to compute 1 plus again dp of n 1 plus again dp of n minus 4. and similarly for here we would minus 4. and similarly for here we would say say one which is coming from here plus the one which is coming from here plus the number of ones number of ones in this binary representation which we in this binary representation which we know we already computed know we already computed up over here and the answer to that was up over here and the answer to that was one so in this position one so in this position really there's going to be two ones in really there's going to be two ones in this binary representation now over here this binary representation now over here once again once again we know that there's at least one from we know that there's at least one from here plus how many were in this binary here plus how many were in this binary representation we computed that representation we computed that at position three which again is offset at position three which again is offset by four by four so this is going to be one plus two so this is going to be one plus two which is going to be 3. which is going to be 3. now you get over here so now we have an now you get over here so now we have an even more significant bit last time the even more significant bit last time the most significant most significant bit was in this position and we know bit was in this position and we know that represents the integer that represents the integer 4. now we got an even more significant 4. now we got an even more significant bit bit which represents the integer a so which represents the integer a so we know that this is going to have at we know that this is going to have at least one occurrence of one and then we least one occurrence of one and then we want to know how many want to know how many ones are in this binary representation ones are in this binary representation now now how are we going to get that in this how are we going to get that in this case you can tell case you can tell the the offset is no longer four because the the offset is no longer four because if we do an offset of four we get to the if we do an offset of four we get to the integer four that's not what we're integer four that's not what we're trying to do trying to do this binary representation represents this binary representation represents the integer zero so in reality the integer zero so in reality we want to take eight offset it by 8 we want to take eight offset it by 8 which is going to get us all the way which is going to get us all the way over here over here and once you do that that's when you and once you do that that's when you actually notice the pattern since this actually notice the pattern since this is going to be is going to be 1 plus dp of n minus 1 plus dp of n minus 8 you can tell that for each value 8 you can tell that for each value this is going to be the equation 1 plus this is going to be the equation 1 plus dp of n minus a particular integer dp of n minus a particular integer and that integer is going to be called and that integer is going to be called the offset the offset and the offset is going to be the most and the offset is going to be the most significant significant bit that we have reached so far and what bit that we have reached so far and what are the most significant bits well the are the most significant bits well the first one is going to be a one first one is going to be a one the next one is going to be a two the the next one is going to be a two the next is going to be a 4 8 next is going to be a 4 8 16. so basically they're doubling in 16. so basically they're doubling in size every time because we know a bit is size every time because we know a bit is just a just a power of two right that's what binary power of two right that's what binary represents so let's clean this up just a represents so let's clean this up just a tiny bit tiny bit so we know that this is kind of our base so we know that this is kind of our base case zero is going to have zero ones in case zero is going to have zero ones in it it now in the next position what's the most now in the next position what's the most significant bit we've reached so far significant bit we've reached so far it's in the ones place right so it's in the ones place right so therefore it's going to be a 1. so when therefore it's going to be a 1. so when we're computing we're computing this we're going to compute 1 plus dp this we're going to compute 1 plus dp of n n is always going to be the value of n n is always going to be the value we're computing right now so that's we're computing right now so that's going to be a 1 going to be a 1 minus 1 because 1 is the most minus 1 because 1 is the most significant bit we've reached so far significant bit we've reached so far down here we reached a new significant down here we reached a new significant bit of 2 bit of 2 right because we've gotten to the value right because we've gotten to the value 2 so far so 2 so far so for here we're going to say 1 plus dp of for here we're going to say 1 plus dp of n minus n minus two now in this next position again the two now in this next position again the most significant bit is most significant bit is two right we we know that two is a two right we we know that two is a significant bit significant bit the next significant bit is going to be the next significant bit is going to be four because that's another power of two four because that's another power of two so so three is not a it's still going to use three is not a it's still going to use the previous value the previous value so from here we're going to compute 1 so from here we're going to compute 1 plus again dp plus again dp of n minus 2. now once you get here of n minus 2. now once you get here we see that we've reached a new power of we see that we've reached a new power of 2. 2. so then we're gonna be modifying this to so then we're gonna be modifying this to one plus dp one plus dp of n minus four and then of course when of n minus four and then of course when we got to we got to eight we know we reached a new power of eight we know we reached a new power of two so we were gonna do one plus dp of n two so we were gonna do one plus dp of n minus eight minus eight how do you know if you reach a new power how do you know if you reach a new power of two well you can take the previous of two well you can take the previous power of two for example it was two power of two for example it was two right right let's say the current power of two is let's say the current power of two is two let's say we multiply it two let's say we multiply it by two does that equal the current uh by two does that equal the current uh value where if we got to three n equals value where if we got to three n equals three three we would check does two times two equal we would check does two times two equal three no it does not so we did not reach three no it does not so we did not reach a new power of two a new power of two if we if we got to four two times four if we if we got to four two times four that does equal that does equal four so now we reached a new power of four so now we reached a new power of two and then two and then from four we would do the same thing so from four we would do the same thing so four multiplied by two four multiplied by two does that equal to seven right let's say does that equal to seven right let's say we got to seven and we were trying to we got to seven and we were trying to see see is this a power of two no this does not is this a power of two no this does not equal seven but once we get to equal seven but once we get to eight then four times two yes that eight then four times two yes that equals eight right so we did reach a new equals eight right so we did reach a new power of 2 and we'd do the exact same power of 2 and we'd do the exact same thing thing so the next time we would reach a new so the next time we would reach a new power of 2 is would be 8 times 2 power of 2 is would be 8 times 2 equals 16. so next time we reach a 16 equals 16. so next time we reach a 16 that's going to be a new power of 2 that's going to be a new power of 2 and 16 times 2 is 32 etc etc so that's and 16 times 2 is 32 etc etc so that's how it's going to work how it's going to work and once you know this idea it's not and once you know this idea it's not super intuitive until you actually kind super intuitive until you actually kind of draw it out of draw it out but once you do the code is actually but once you do the code is actually pretty easy to write let me show you how pretty easy to write let me show you how so our dp array is going to be so our dp array is going to be initialized to all zeros and it's going initialized to all zeros and it's going to be length to be length n plus 1 because that's how many we're n plus 1 because that's how many we're trying to compute and we're also going trying to compute and we're also going to have an answer to have an answer array which is initially just going to array which is initially just going to have a single zero in it because we know have a single zero in it because we know n is going to be at least zero and then n is going to be at least zero and then we're going to go through for i we're going to go through for i in range all the way from one up until n in range all the way from one up until n so n plus one this is non-inclusive in so n plus one this is non-inclusive in python so we're actually going to be python so we're actually going to be stopping when we go from one all the way stopping when we go from one all the way up until n up until n and we're going to be keeping track of and we're going to be keeping track of one more variable the offset aka the one more variable the offset aka the highest power of two so far so initially highest power of two so far so initially that's gonna be that's gonna be one so before we actually compute the dp one so before we actually compute the dp or the number of bits in this or the number of bits in this integer i's binary representation first integer i's binary representation first we're going to check how we're going to check how can we double our offset we're going to can we double our offset we're going to check if check if offset multiplied by two is equal offset multiplied by two is equal to i the current end that we have just to i the current end that we have just reached if it is then we can set reached if it is then we can set offset equal to i otherwise offset is offset equal to i otherwise offset is going to stay the same going to stay the same and then we can actually compute the dp and then we can actually compute the dp so we're trying to compute dp of i so we're trying to compute dp of i which is basically the number of bits which is basically the number of bits the number of ones in i's binary the number of ones in i's binary representation we know that's going to representation we know that's going to be at least be at least 1 plus dp of i 1 plus dp of i minus the offset and actually one thing minus the offset and actually one thing i just realized i just realized is the dp and the answer array are is the dp and the answer array are actually the exact same i don't know why actually the exact same i don't know why i even created an answer array we can i even created an answer array we can get rid of that so this dp is basically get rid of that so this dp is basically our answer array it's going to give us our answer array it's going to give us the number of bits the number of one the number of bits the number of one bits in each integer's binary bits in each integer's binary representation so once representation so once once we're done with that we can go once we're done with that we can go ahead and just return this dp array ahead and just return this dp array so as you can see this is a pretty so as you can see this is a pretty efficient solution this is the linear efficient solution this is the linear time big o of n time big o of n time and space solution i hope this was time and space solution i hope this was helpful if it was please like and helpful if it was please like and subscribe it supports the channel a lot subscribe it supports the channel a lot and i'll hopefully see you pretty soon and i'll hopefully see you pretty soon thanks for watching
2024-03-24 10:52:18
338
https://i.ytimg.com/vi/R…axresdefault.jpg
Counting Bits - Dynamic Programming - Leetcode 338 - Python
GW7Km2V3kR8
hello guys welcome to God enzyme and in this video we are going to discuss this video we are going to discuss problem 149 of lead code and the problem problem 149 of lead code and the problem name is Max points in a line problem name is Max points in a line problem difficulty is hard let's read the difficulty is hard let's read the problem statement given an array of problem statement given an array of points where points I is equal to X1 points where points I is equal to X1 comma y1 represents a point in X Y plane comma y1 represents a point in X Y plane return the maximum points in a line on return the maximum points in a line on the same straight line okay so this is a the same straight line okay so this is a geometry problem let's see some examples geometry problem let's see some examples first so here is an example this is the first example so we have one comma 1 2 comma 2 and 3 comma 3 and we can see all the three points lie in around line and when we count the number of points in this line uh it is the maximum number of points so our output is three let's see example number two so here is example number two we have several number of points and we can see if we try to join every point to every Point uh so basically we will be brute forcing it so we will join every point to every point and we will count number of uh all the points that fall on every line and we will when we will see this is the maximum points we will get so these are the four points and these lie on the same line so our answer is 4 in this case now let's also see the constraints we have points DOT length is equal to 300 and the points sorry and points I represent consists of only two characters so the length is two and X1 comma y one ranges from minus 10 raised to power 4 to 10 s by 4 and all the pairs are unique so we don't have to take care of this uh last point but uh let's try to analyze what kind of complexity we will need and since points DOT length is approx is 300 so if we Cube it we will get an approximately uh six and two times per 6 which is almost less than 10 square 7. so we can say that uh maximum algorithm of Big O of n Cube will work in this case and in the and today I am going to discuss a solution of big of n Square so let's see the approach but before that we should know what kind of data structure to use but so we want to use our data structure where we will are going to store lines and for every line we are going to have some set of points right so we will need something like a hash map to where we are the where we will map every line to a set which will consist of unique points and a line on that line right so we are going to use hashmap for this case now the question comes what uh what describes the line so since we are going to sense our indexes of the hash map are going to be line but what exactly is a line and uh to answer this we need some knowledge of mathematics and let's see how we can actually represent the line and I am going to show you two forms and I'm going to show you two types of forms of line one is the uh to represent a one is the slope form and it is given by one is the slope form and it is given by Y is equal to MX plus C here m is the Y is equal to MX plus C here m is the slope and C is the intercept and another slope and C is the intercept and another is a point form so y minus y 1 upon x is a point form so y minus y 1 upon x minus x 1 this is also a slope which is minus x 1 this is also a slope which is equal to Y 2 minus y 1 upon x 2 minus x equal to Y 2 minus y 1 upon x 2 minus x 1 and here you can also use Y and X in 1 and here you can also use Y and X in this case also it follows give you the this case also it follows give you the same result but the important thing is same result but the important thing is this is equal to slope this is equal to slope so since slope is common one thing is so since slope is common one thing is for sure that we have to calculate the for sure that we have to calculate the slope of the line and in the second slope of the line and in the second point or second form we can use this point or second form we can use this point form to calculate the value of C point form to calculate the value of C and that's C and that's C is going to be equal to slope into x is going to be equal to slope into x minus X1 plus y1 right and if we put y x minus X1 plus y1 right and if we put y x is equal to 0 in this point form we will is equal to 0 in this point form we will get C is equal to slope into minus X1 get C is equal to slope into minus X1 plus y1 right so I will write that for plus y1 right so I will write that for you you so C is equal to slope into minus X1 so C is equal to slope into minus X1 plus y1 and in the hash map we can store plus y1 and in the hash map we can store pairs like uh first we are going to have pairs like uh first we are going to have a pair of slope and C slope and The a pair of slope and C slope and The Intercept which will map to a set of Intercept which will map to a set of points right but uh here comes a problem points right but uh here comes a problem what if this m the slope is equal to what if this m the slope is equal to Infinity what are we going to what will Infinity what are we going to what will be our Intercept in that case so for be our Intercept in that case so for that if the slope is infinite we can see that if the slope is infinite we can see that uh our lines will be vertical and that uh our lines will be vertical and if the two points remain on the same if the two points remain on the same line then we can see the X component of line then we can see the X component of that line will be same so in that case that line will be same so in that case we are going to store this x value in we are going to store this x value in the in place of this C okay if that's if the in place of this C okay if that's if the if our slope is infinity otherwise the if our slope is infinity otherwise we are going to use this formula only we are going to use this formula only so that is that was all the explanation so that is that was all the explanation and now let's see the code for this so and now let's see the code for this so this is the python code first I am this is the python code first I am checking the checking the first time first time handling the edge first time first time handling the edge cases so if our length of points is one cases so if our length of points is one I'm simply returning one and if it is I'm simply returning one and if it is two and it will simulated on into two and it will simulated on into and this is our map uh the dictionary and this is our map uh the dictionary and now I'm collect I'm saying that the and now I'm collect I'm saying that the okay for every Point uh this is an ol okay for every Point uh this is an ol Square Loop right because um Square Loop right because um for every Iron Ridge line point I'm also for every Iron Ridge line point I'm also traveling from to the other points and traveling from to the other points and later my first point will be X1 y1 okay later my first point will be X1 y1 okay and this X2 Y2 will be my second point and this X2 Y2 will be my second point if these two are equal if the X values if these two are equal if the X values is equal since we see so in this formula is equal since we see so in this formula we have to uh divide by X2 minus X1 we have to uh divide by X2 minus X1 since uh we so we have to handle it since uh we so we have to handle it explicitly otherwise it will give us a explicitly otherwise it will give us a divided by zero error divided by zero error so if X1 is equal to X2 my slope will be so if X1 is equal to X2 my slope will be infinite infinite and that means if we will reach this and that means if we will reach this case case and in Python we can specify slope is and in Python we can specify slope is equal to infinite using this equal to infinite using this float of INF float of INF so this will make my slope infinite and so this will make my slope infinite and otherwise I'm simply going to use this otherwise I'm simply going to use this formula now if my slope was infinite formula now if my slope was infinite what I am doing if my slope is infinite what I am doing if my slope is infinite I am storing my X values in place of The I am storing my X values in place of The Intercept so in my Intercept so in my so my intercept will be in X1 otherwise so my intercept will be in X1 otherwise I am storing the I am storing my I am storing the I am storing my intercept using this above formula intercept using this above formula slope is equal to C is equal to slope slope is equal to C is equal to slope into minus X1 Plus y1 into minus X1 Plus y1 and now uh in the dictionary I am and now uh in the dictionary I am putting these so if there's a tuple of putting these so if there's a tuple of slope comma intercept is already present slope comma intercept is already present in my dictionary then I am adding to the in my dictionary then I am adding to the set of points x 2 comma Y2 otherwise I set of points x 2 comma Y2 otherwise I am making a new set for that for this am making a new set for that for this Tuple and adding my these two points in Tuple and adding my these two points in that and At Last I can Traverse in the that and At Last I can Traverse in the dictionary and find the maximum amount dictionary and find the maximum amount of length of set of points in the of length of set of points in the dictionary and next I am going to return dictionary and next I am going to return answer so that completes the code so I answer so that completes the code so I hope you were able to understand this hope you were able to understand this so if you were able to understand this so if you were able to understand this currently subscribe to my channel like currently subscribe to my channel like this video this video I will see you guys next time happy I will see you guys next time happy learning thank you
2024-03-21 13:03:02
149
https://i.ytimg.com/vi/G…axresdefault.jpg
Leetcode: 149. Max Points on a Line | Daily Leetcode Problems
lNpoSEH388k
hello everyone welcome to the channel today's question is interlaced today's question is interlaced intersections if you are new to the intersections if you are new to the channel please consider subscribing we channel please consider subscribing we sold a lot of interview question on this sold a lot of interview question on this channel and that can definitely help you channel and that can definitely help you with your interview a questions is given with your interview a questions is given to lists of close intervals each list of to lists of close intervals each list of intervals his pay was destroyed and in a intervals his pay was destroyed and in a sorted order written the intersection of sorted order written the intersection of these two interval lists and we again these two interval lists and we again with the example and if we look at with the example and if we look at example we are given with a and P and we example we are given with a and P and we need Britain the intersection and we can need Britain the intersection and we can clearly see the intersection between a clearly see the intersection between a and B so these are the points of and B so these are the points of intersections so let's move to pen and intersections so let's move to pen and paper let's see how we can solve this paper let's see how we can solve this question after that we will see the code question after that we will see the code I have taken the example given in the I have taken the example given in the question and this question is similar to question and this question is similar to the question we have done before on this the question we have done before on this channel and you can find the link of the channel and you can find the link of the quotient in the description below and quotient in the description below and this question is asking that we need to this question is asking that we need to return the intersection of these two return the intersection of these two intervals and the intervals are a and B intervals and the intervals are a and B and if we look at bar chart two on the and if we look at bar chart two on the send how the intersection of interval is send how the intersection of interval is working then this represents a and this working then this represents a and this represents B and this represents our represents B and this represents our output and we can clearly see that output and we can clearly see that intersection of a and B for the first intersection of a and B for the first elements are this part and we can elements are this part and we can clearly see how we are getting there so clearly see how we are getting there so intersection of these two point will be intersection of these two point will be equal to 1 and 2 and how we are getting equal to 1 and 2 and how we are getting 1 into 1 is the maximum of starting 1 into 1 is the maximum of starting point you can see 1 we are starting with point you can see 1 we are starting with here and 1 we have starting point here here and 1 we have starting point here and and the starting point is maximum of the starting point is maximum of starting off a and B and if we took over starting off a and B and if we took over the ending point this is minimum of the ending point this is minimum of ending of a and B you can clearly see a ending of a and B you can clearly see a and say B and C so you can say the and say B and C so you can say the ending of R in the word is minimum of ending of R in the word is minimum of ending of a and B so now we go to our ending of a and B so now we go to our first interval and to get all the first interval and to get all the intervals I need to spam both of the intervals I need to spam both of the list a and B and for that I need to list a and B and for that I need to increase the point ring a and B but if increase the point ring a and B but if you see that a starting here before B you see that a starting here before B ends that means we also consider it as a ends that means we also consider it as a interval and which also means I just interval and which also means I just can't increase the pointer in both of can't increase the pointer in both of the array at the same time because what the array at the same time because what if I was first here at 0 and 0 after if I was first here at 0 and 0 after getting my first interval but if I am getting my first interval but if I am moved to 1 and one that I would have moved to 1 and one that I would have missed this part and my answer have been missed this part and my answer have been 8 and then and I missed this part which 8 and then and I missed this part which is 5 and 5 so how to check which one to is 5 and 5 so how to check which one to move whether I have to move in a or we move whether I have to move in a or we have to move in B so for that I will have to move in B so for that I will compare the ending part of each element compare the ending part of each element and if ending element of a is greater and if ending element of a is greater than ending element of P these are green than ending element of P these are green with with every single element and looking over in every single element and looking over in this case I will increase the point of P this case I will increase the point of P else if the ending part of a is less else if the ending part of a is less than ending part of P in that case I than ending part of P in that case I will increase pointer off and let's see will increase pointer off and let's see this thing in the second interval so if this thing in the second interval so if I come here I am done with my first I come here I am done with my first interval now I will compare ending interval now I will compare ending element of a and ending element of P and element of a and ending element of P and I found that ending element of B is I found that ending element of B is greater than ending element of a that greater than ending element of a that means I will going to increase the means I will going to increase the pointer in a and I will come here but I pointer in a and I will come here but I will not going to increase the pointer will not going to increase the pointer in P so I will still remain here now in P so I will still remain here now again I will implement this part that again I will implement this part that the starting point of the interval will the starting point of the interval will be the maximum of starting point of a be the maximum of starting point of a and B so our is this which is maximum of and B so our is this which is maximum of five and one so Maxima is five okay so five and one so Maxima is five okay so we got five and the ending point of the we got five and the ending point of the interval will be minimum of ending point interval will be minimum of ending point of a and ending point of B and the of a and ending point of B and the minimum of ending point of a and ending minimum of ending point of a and ending point of B is five and so in this way we point of B is five and so in this way we will get our second interval which is will get our second interval which is five and five which represent this part five and five which represent this part okay now again we have the quotient in okay now again we have the quotient in which part we have to increase the point which part we have to increase the point of again we will compare the ending of again we will compare the ending point of a and B so we have a here and point of a and B so we have a here and we have be here so I will compare the we have be here so I will compare the ending part of a which is 10 and the ending part of a which is 10 and the ending part of B which is 5 and if ending part of B which is 5 and if ending part of a is greater than ending ending part of a is greater than ending part of B I will increase the pointing B part of B I will increase the pointing B so now I will come here and I will so now I will come here and I will remain here in a so now again remain here in a so now again I will use this part to get my interval I will use this part to get my interval so the starting point of the interval so the starting point of the interval will be maximum of a and B maximum of a will be maximum of a and B maximum of a and B is 8 and the ending point of the and B is 8 and the ending point of the interval will be minimum of a and B interval will be minimum of a and B which is 10 and this is our third which is 10 and this is our third interval now again to increase the interval now again to increase the pointer I will compare the ending point pointer I will compare the ending point of a and B and ending point of a is 10 of a and B and ending point of a is 10 and ending point of base 12 and ending and ending point of base 12 and ending point of a is not greater than ending point of a is not greater than ending point of B that means I will increase point of B that means I will increase the pointer of a so now my a will come the pointer of a so now my a will come here now again to get the interval oil here now again to get the interval oil implement this thing so the starting implement this thing so the starting point of the interval will be the point of the interval will be the maximum of starting point of a and P maximum of starting point of a and P maximum of a and B is 13 and the ending maximum of a and B is 13 and the ending point will be the minimum of ending of a point will be the minimum of ending of a and B and the minimum is 12 and now we and B and the minimum is 12 and now we are facing a weird thing that how can are facing a weird thing that how can our starting point can be greater than our starting point can be greater than the ending point if this is the case the ending point if this is the case this is not an interval so if starting this is not an interval so if starting point is not less than equal to the point is not less than equal to the ending point I will not going to append ending point I will not going to append it my interval so let me write it down it my interval so let me write it down here if starting is less than equal to here if starting is less than equal to ending then only we are going to append ending then only we are going to append it in intervals so so we will not going it in intervals so so we will not going to append it in the endeavor but again to append it in the endeavor but again to increase the pointer we will use to increase the pointer we will use ending point of a and ending point of B ending point of a and ending point of B ending point of H 23 and ending point of ending point of H 23 and ending point of peace peace ending point of a is good with an ending ending point of a is good with an ending point of B so I will increase the point point of B so I will increase the point O in B so again the starting point the O in B so again the starting point the interval will be the maximum of a and B interval will be the maximum of a and B which is 15 and the ending point of which is 15 and the ending point of interval will be minimum of a and P interval will be minimum of a and P which is 23 now again I will append it which is 23 now again I will append it to my intervals 1523 which is here so now again to check which pointer to increase I will compare the ending point of a and ending point of B and if the ending point of a is less than ending point of P that means I will going to increase the pointer in a and ending point of age 23 and ending point of is 24 so I will increase the pointer in a so now again the starting part of interval will be the maximum of starting of a and B the maximum of starting of a and B is 24 and the ending will be the minimum of ending of a and B now the minimum is also 24 so again we go to our fifth interval which is 24 and 24 which is our this part so again to check the pointer I will compare the ending point of a and B and now ending point of a is geared to the ending point of P that means we will increase the pointer in B so my pointer will come here now again to get the interval so now the starting point of the interval will be the maximum of starting point of a and B and the maxim between 24 and 25 is 25 so the starting point of my interval will be 25 and ending will be minimum of ending of a and B and ending of in base 25 and 26 and minimum of them is 25 so I will take 25 and this will serve as the last interval which represent this part so what are the key things we have to pick from here first to get the interval I will use this part that the starting point will be the maximum starting bit of a and B and the ending part will be minimum of ending of a and B and we will only willing to append in the interval if the starting point is less than the ending point and to check the pointer I will use this part that if the ending point of a is greater than ending point of P in that case I will increase the pointing B else I will going to increase the pointer in a or you can say if the ending point of a is less than the ending point of P in that case I will going to increase the pointer in a else I will going to increase the pointer in me or you can say whosoever have the smaller ending point I will increase the pointer in that so let's move to the coding part and let's see what is the code for this problem so let's see the code at line number 3 and at line number 4 I have pointer a and B which is equal to 0 and I have taken interval which is empty list in which I will store my intervals and I am taking a while loop while I is less than length of a and B is less than the length of given list B and I am defining my interval of starting and interval of ending and the starting part will be equal to maximum of starting of a and B and the ending of interval will be equal to minimum of ending of a and B and we will going to append the starting and ending point in the interval only if if the standing point of the interval is less than equal to ending point of in the world and to increase the pointer we will check the ending point of a and P and if the ending point of a is less than the ending point of P in that case I will increase the pointer in a else I will going to increase the pointer in P and at the end I will simply written the interval so this is the code let's see whether it works or not so here I sum in my code and it got septic so this was the solution for this problem if this video was helpful to you please give it a thumbs up thank you so much guys for watching the video please don't forget
2024-03-25 14:29:59
986
https://i.ytimg.com/vi/l…axresdefault.jpg
interval list intersections leetcode | interval list intersection python | leetcode 986 | $$
5NwYuETUlwo
hello everyone we are solving problem number 225 to implement stack using number 225 to implement stack using queues so in this problem we need to queues so in this problem we need to implement functionalities of Stack which implement functionalities of Stack which are push pop top and empty using only Q are push pop top and empty using only Q data structure so data structure so we will first take what is the we will first take what is the difference between these two structures difference between these two structures so for Q it implements first in first so for Q it implements first in first out methodology out methodology while while stack implements lasting for start stack implements lasting for start methodology methodology so so this is the major difference between uh this is the major difference between uh these two on this structures while other these two on this structures while other functionalities like top pop empty are functionalities like top pop empty are nearly similar so I will just first nearly similar so I will just first Implement one queue or declare one queue let's call it q and we will initialize we are going to implement using it using we are going to implement using it using linked list linked list so so we will first complete this uh simple we will first complete this uh simple questions or the simpler functions so in questions or the simpler functions so in this case we will just say Q dot Pole this case we will just say Q dot Pole then in this case then in this case we will just say Q dot P these are the we will just say Q dot P these are the similar functionalities similar functionalities so we don't need to think for this so we don't need to think for this U dot is empty okay but for push so when we push any item in a queue so the item which which is pushed earlier gets removed from the first while use in queue sequence but while in the stack uh when you push an item and you if you perform pop operation so the element which is most recently uh pushed get popped so so this is the uh one uh tricky implementation so for that what we can do is let's take one example let's say we have one two three four in the queue and we need to add 5 but as Stacks logic if we need to perform power operation our file should get popped but uh by Q's implementation if we perform pop operation then our one will get pop as one is added earlier than others so here what we can do is we will add this Phi and we will re-add these elements again from the back so what we will do is we will just simply do this process so we will uh so by this process we will uh maintain the track of which element is getting pushed most recently and which is getting pushed with the uh which is pushed earlier than other elements so we will just do this what we're going to do is we will just that's it that's it add and then what we will do is we will run while I is less than while I is less than Q Q dot size dot size but you will perform till but you will perform till -1 only -1 only as we don't need to pop this element as as we don't need to pop this element as we need to keep it and then we need to we need to keep it and then we need to react the elements which are in front of react the elements which are in front of on that element from the back so we we on that element from the back so we we will just remove first uh length minus will just remove first uh length minus one elements and you will we will react one elements and you will we will react them so I plus plus them so I plus plus and what we will do is we will just say and what we will do is we will just say Cube that Q dot add Cube that Q dot add Q dot pull so by this process by this Q dot pull so by this process by this function we are removing element from function we are removing element from the beginning the beginning and then adding it in the end so and then adding it in the end so I think everything is okay let's try to I think everything is okay let's try to run this code [Music] [Music] yeah 100 faster so I will just explain yeah 100 faster so I will just explain uh this tip once again uh this tip once again so what we are doing is let's say we so what we are doing is let's say we have one two three in this stack and we have one two three in this stack and we are uh pushing let's say a new element X are uh pushing let's say a new element X so by this tax logic if we pop in a pop so by this tax logic if we pop in a pop uh if you go from pop operation then X uh if you go from pop operation then X should get popped but by the queues should get popped but by the queues implementation as uh it has original implementation as uh it has original functionality the one will get pop as it functionality the one will get pop as it is pushed earlier than x so what we will is pushed earlier than x so what we will do is we will push X in this queue and do is we will push X in this queue and then we will push the elements which are then we will push the elements which are main front of X sorry uh again from the main front of X sorry uh again from the back so back so I will do stepwise okay I will do stepwise okay so what we will do is we will pop this so what we will do is we will pop this one one and we will add it again from the end and we will add it again from the end okay so then again we will pop this two okay so then again we will pop this two and then we will add it from the end and then we will add it from the end then we will pop this three then we will pop this three and then we will add it from the end and then we will add it from the end okay so by this way okay so by this way our most recent elements will get will our most recent elements will get will get placed uh in the front of queue and get placed uh in the front of queue and if we perform then uh then if we perform if we perform then uh then if we perform uh pop operation for this implementation uh pop operation for this implementation of Stack then we will get the most of Stack then we will get the most recent element so for that we have done recent element so for that we have done this Loop till size minus 1 and we have this Loop till size minus 1 and we have added the element which are which we are added the element which are which we are poking popping from the front okay poking popping from the front okay so thank you
2024-03-22 11:00:21
225
https://i.ytimg.com/vi_w…xresdefault.webp
Implement Stack using Queues - Leetcode #225
r_uJ9Vlqaqs
hey hello there so today I want to talk about this question 689 marks in the sum about this question 689 marks in the sum of three non-overlapping sub-arrays we of three non-overlapping sub-arrays we have an input array of positive integers have an input array of positive integers and we want to find the three and we want to find the three non-overlapping sub arrays within this non-overlapping sub arrays within this input array and if you add all the input array and if you add all the numbers from those three sub arrays they numbers from those three sub arrays they should be the maximum possible and there should be the maximum possible and there is one thing that this resub er is in is one thing that this resub er is in common they they all have size k common they they all have size k consecutive K elements in this sub consecutive K elements in this sub arrays the the K is also input to the arrays the the K is also input to the problem we want to return the list of problem we want to return the list of indices for their starting positions if indices for their starting positions if there are multiple answers we should there are multiple answers we should return the lexicographically smallest return the lexicographically smallest one so the we want them to be as left as one so the we want them to be as left as possible if we have tied total total possible if we have tied total total total sum for the elements we wanted the total sum for the elements we wanted the one that towards the left and as much as one that towards the left and as much as possible so example we have 1 2 1 2 6 7 possible so example we have 1 2 1 2 6 7 5 1 the sub array are of size 2 so if we 5 1 the sub array are of size 2 so if we look at the starting index at zero that look at the starting index at zero that window that sub array is long and 2 so window that sub array is long and 2 so the total suite if you look at the index the total suite if you look at the index 3 the sub array are 6 & 2 the total is 8 3 the sub array are 6 & 2 the total is 8 if we look at the index 5 the sub array if we look at the index 5 the sub array contains 7 & 5 the total is 12 so 12 contains 7 & 5 the total is 12 so 12 plus 8 plus 3 we get at 20 23 so that's plus 8 plus 3 we get at 20 23 so that's the maximum and they are multiple there the maximum and they are multiple there there are another possibility is just 1 there are another possibility is just 1 3 & 5 3 & 5 basically just shifting the first two basically just shifting the first two separate was right 1 2 2 1 they sum to separate was right 1 2 2 1 they sum to be the same thing but for this one the be the same thing but for this one the lexicographically order it is larger lexicographically order it is larger because one is it's larger than zero so because one is it's larger than zero so visually it will be the if we have visually it will be the if we have physical arrays there physical arrays there visually will be more visually will be more that's right so that's that's why we that's right so that's that's why we wanted a nursery fire here so some wanted a nursery fire here so some current tea here current tea here the lens is gonna be within this range the lens is gonna be within this range the the numbers here are I think it's the the numbers here are I think it's eight I don't remember eight I don't remember eight bits integer and in here the K eight bits integer and in here the K will be between one and four noms lens will be between one and four noms lens divided by three that's just saying that divided by three that's just saying that we have to have at least one possibility we have to have at least one possibility for four K sub arrays in this in this for four K sub arrays in this in this array if K is larger than this number array if K is larger than this number then there is no way we can put K then there is no way we can put K consecutive non-overlapping arrays in consecutive non-overlapping arrays in the array so that's some guarantee so we the array so that's some guarantee so we will read through this question there is will read through this question there is really nothing special about this really nothing special about this reading here there's nothing about three reading here there's nothing about three that that really changes how you just that that really changes how you just think about this question and actually think about this question and actually you can you can you should expect that you can you can you should expect that this three will be may be upgraded for this three will be may be upgraded for to four to be a more complex question or to four to be a more complex question or downgraded to be one or two to begin downgraded to be one or two to begin with but the end goal is is to have a with but the end goal is is to have a more generic a solution that supports an more generic a solution that supports an arbitrary number of non-overlapping sub arbitrary number of non-overlapping sub arrays so if you have a solution that's arrays so if you have a solution that's really doing a lot of special handling really doing a lot of special handling of three cases then you will be a lot of three cases then you will be a lot difficult for you to solve the difficult for you to solve the follow-ups if the generic one is coming follow-ups if the generic one is coming afterwards so so you staff directly afterwards so so you staff directly thinking about three non-overlapping sub thinking about three non-overlapping sub arrays we just got to be thinking about arrays we just got to be thinking about this as m and the simplest case for this this as m and the simplest case for this question will be one none of the lapping question will be one none of the lapping sub arrays so how do we solve that so we basically run the window well the window is basically the sub-arrays of size two from the left most locations starting position and just run it slide it towards right we're gonna shift it by want what's right each time the initial one that it has the sum of three and the initial location index to be zero in the next iteration will move it towards right by one the new total is still three so because it's not it's the tie so we just keep track of the first appearance because that we results to be lexically lexicographically smaller another iteration doesn't change anything one more iteration the sub-array now sum up to eight eight is larger than 3 so we update this maximum and also update an index that's that becomes three another iteration we get 13 we change eight to 13 and update the index to for another iteration will get twelve since that 12 is not smaller than the previous maximum we don't do any updates one last iteration so we reach the end of the input array we tried all the possible size two sub arrays of course it's non overlapping with zero sub arrays and we by doing running through the window we get the maximum four for the one none of loving sub arrays of size to the the some would be searching and its index will be four so we run one window we can solve the one none of Allah great question so can we just run two windows together to solve the two non-overlapping separate question yes yes that's that's what we're gonna do so initially we're gonna have because they are none of lopping the best case we can do in the in the very beginning we could just gonna have them side by side we're index of one index of two which maximum index of one index of two which maximum of one a maximum of two this second lie of one a maximum of two this second lie here is gonna be the maximum of two none here is gonna be the maximum of two none of the laughing sub arrays it's not the of the laughing sub arrays it's not the maximum of the second but that posed maximum of the second but that posed together so initially this is in the together so initially this is in the initial case it's 3 and 0 this will be 3 initial case it's 3 and 0 this will be 3 plus 3 and the index will be at a pole plus 3 and the index will be at a pole of 0 & 2 so that's the initial State and of 0 & 2 so that's the initial State and in the next year very same we're just in the next year very same we're just going to move this towards right stimuli going to move this towards right stimuli endlessly by by one position the first endlessly by by one position the first window will become 3 this first a sub window will become 3 this first a sub array will become sorry so then we only array will become sorry so then we only like then we'll look after the maximum like then we'll look after the maximum of 1 all we can do is compare this owed of 1 all we can do is compare this owed 3 with this new sub array so it would be 3 with this new sub array so it would be similar to the one window case we similar to the one window case we couldn't update that in this case for couldn't update that in this case for the second sub array you've become the second sub array you've become interesting the total now the total for interesting the total now the total for our sub array is now 8 and what would our sub array is now 8 and what would compare that with is the 8 plus the compare that with is the 8 plus the current a maximum of 1 because the current a maximum of 1 because the there's this non-overlapping guarantee there's this non-overlapping guarantee we can we can always just add 8 tor for we can we can always just add 8 tor for for the maximum of 1 there in in the for the maximum of 1 there in in the same iteration which could be recently same iteration which could be recently updated updated can be updated to four if we have two can be updated to four if we have two here and eight plus three will be 11 and here and eight plus three will be 11 and because 11 is larger than the previous because 11 is larger than the previous maximum six we can we can update the maximum six we can we can update the maximum of two to be maximum of two long maximum of two to be maximum of two long overlapping sub arrays this given time overlapping sub arrays this given time to be 11 and the location will be to be 11 and the location will be updated to zero and Suite 3 is the updated to zero and Suite 3 is the starting location for this sub array sum starting location for this sub array sum up to eight the second sub array the sum up to eight the second sub array the sum up to 8 3 so that's the picture here in up to 8 3 so that's the picture here in the next iteration we could have shifted the next iteration we could have shifted the two window towards right by one two the two window towards right by one two sub arrays I use window and summarised sub arrays I use window and summarised interchangeably because they are pretty interchangeably because they are pretty much the same in this context the first much the same in this context the first sub array is still sorry we don't week sub array is still sorry we don't week still can't update the first slide but still can't update the first slide but the second line the this submarine comes the second line the this submarine comes 13 + 13 + 3 is larger than searching 13 + 13 + 3 is larger than searching plus 3 is larger than the previous box plus 3 is larger than the previous box and 11 and so that we can actually do and 11 and so that we can actually do the update change the in starting index the update change the in starting index for the second window a second subarray for the second window a second subarray 204 so the 0 and for those 2 sub arrays 204 so the 0 and for those 2 sub arrays the total would become the new total the total would become the new total would be become 16 I'm just going to run would be become 16 I'm just going to run this through one more time one last time this through one more time one last time actually the first sub array becomes 8 actually the first sub array becomes 8 total there so we update there's to be 8 total there so we update there's to be 8 and the index will be 3 and the second and the index will be 3 and the second sub array here the sulphur that running sub array here the sulphur that running sub array here would be second the sub array here would be second the running sub array will be 12 and when we running sub array will be 12 and when we consider how we whether we should update consider how we whether we should update in this box in this box love to we are 12 where's this 8 with no love to we are 12 where's this 8 with no new maxim of want because then no new maxim of want because then no non-overlapping guarantee this we can non-overlapping guarantee this we can always if we process this box of one box always if we process this box of one box of 2 in the sequence we can always use of 2 in the sequence we can always use this 12 to add the you know max this we this 12 to add the you know max this we don't care about what's actually in here don't care about what's actually in here all we care is the maximum of 1 and all we care is the maximum of 1 and because none of a lapping we can always because none of a lapping we can always use that to try to construct our bigger use that to try to construct our bigger song so 12 plus 8 plus 8 which is 20 song so 12 plus 8 plus 8 which is 20 that's the new maximum it's greater than that's the new maximum it's greater than 16 and to update the indices it's just 16 and to update the indices it's just now 3 & 5 yes that's pretty much it so now 3 & 5 yes that's pretty much it so the tool and overlapping sub-array the tool and overlapping sub-array solution is basically just maintaining solution is basically just maintaining two lines here and you can imagine if we two lines here and you can imagine if we are actually working on this three are actually working on this three non-overlapping case we just have three non-overlapping case we just have three windows here will be three eight and windows here will be three eight and twelve the starting indices for them is twelve the starting indices for them is one for the current sub array running one for the current sub array running sliding running sub array it's 1 3 & 5 sliding running sub array it's 1 3 & 5 their distance there their gap is the their distance there their gap is the size 2 here the maximum for the first size 2 here the maximum for the first would be 3 the index would be 0 but would be 3 the index would be 0 but that's this one here the maximum of 2 that's this one here the maximum of 2 will be 11 which is 3 3 plus 8 and the will be 11 which is 3 3 plus 8 and the index is 3 is 0 & 3 for the 8 a maximum index is 3 is 0 & 3 for the 8 a maximum 3 and the location in indices of the 3 and the location in indices of the story would be story would be 11 plus 12 2003 and 5 and that is 11 plus 12 2003 and 5 and that is exactly this simple example sample exactly this simple example sample sample example 0 certify so just by sample example 0 certify so just by looking at this if we have M windows looking at this if we have M windows we're just going to have M line here we're just going to have M line here each line is memorizing the maximum sum each line is memorizing the maximum sum of the first and windows and there are of the first and windows and there are indices for the end windows so we're indices for the end windows so we're just going to update that the update just going to update that the update rule is basically is going to be the rule is basically is going to be the maximum between the previous maximum of maximum between the previous maximum of 5 and the maximum of I minus 1 we use a 5 and the maximum of I minus 1 we use a bracket to indicate this as indices plus bracket to indicate this as indices plus the current window current parent of the current window current parent of submarine current to sub array I so submarine current to sub array I so that's the update rule and for the that's the update rule and for the indices we just grabbed the indices indices we just grabbed the indices associated with the max and the max of I associated with the max and the max of I minus 1 and just append the starting minus 1 and just append the starting location for the current a sub array I location for the current a sub array I and we can update the indices so that's and we can update the indices so that's pretty much as a strategy it's gonna be pretty much as a strategy it's gonna be sliding and different windows altogether sliding and different windows altogether and they are side by side the update is and they are side by side the update is happening by updating the sum of the happening by updating the sum of the first our first one some of the first first our first one some of the first two some of the first two sweet max in two some of the first two sweet max in the sum of the first three and so on and the sum of the first three and so on and so forth so we can do this updating a so forth so we can do this updating a for loop instead of different for loop instead of different our different logic hand-coded our different logic hand-coded hard-coded logics we can just use a hard-coded logics we can just use a looping construct to do that so that's looping construct to do that so that's pretty much the analysis then is the pretty much the analysis then is the actual coding now sorry my voice sounds actual coding now sorry my voice sounds bad because I'm copying a little bit bad because I'm copying a little bit today early on and but I guess you don't today early on and but I guess you don't care so we're gonna populate something care so we're gonna populate something like the window song which before that like the window song which before that the first thing to do is to make the the first thing to do is to make the question to be the full opera version M question to be the full opera version M which is the number of windows that we which is the number of windows that we want number for the overlapping windows want number for the overlapping windows so what do we do is first we you start so what do we do is first we you start up a cockade calculating this sum of k up a cockade calculating this sum of k elements and all the time you know elements and all the time you know whenever we shift the one we we need to whenever we shift the one we we need to calculate a new some of the sub arrays calculate a new some of the sub arrays we basically do one pass and generate we basically do one pass and generate all this in in one go and later on we all this in in one go and later on we can just grab those instead of doing can just grab those instead of doing doing some extra calculation redundant doing some extra calculation redundant calculation we're going to call this calculation we're going to call this windows sounds and the I we just grab windows sounds and the I we just grab the sum by the first position for the the sum by the first position for the for the sub array as the as the index so for the sub array as the as the index so in the beginning it's some of the in the beginning it's some of the numbers of apollon T of the first decade and then I'm just going to do one loop this is make sure that we have one last this is make sure that we have one last window that of size K so it's a instead window that of size K so it's a instead of you know the last index for that of you know the last index for that would be lens of nuns plus 1 exclusive would be lens of nuns plus 1 exclusive decrement by one so that's why we need a decrement by one so that's why we need a plus one and we decrement by K we minus plus one and we decrement by K we minus K because the window size is okay so K because the window size is okay so that's the the range here we will pen is that's the the range here we will pen is to grab the previous window a previous to grab the previous window a previous solarium and just disregard the discard solarium and just disregard the discard the previous leftmost element and add in the previous leftmost element and add in the new element so that the nones the new element so that the nones I minus one plus I plus K minus one so I minus one plus I plus K minus one so that's the that's the updates throughout that's the that's the updates throughout the leftmost the previous leftmost and the leftmost the previous leftmost and are the new rightmost and so that we can are the new rightmost and so that we can just whenever we wanted this three eight just whenever we wanted this three eight twelve thing we can just call the twelve thing we can just call the windows song with the index number so we windows song with the index number so we don't have to recalculate every time don't have to recalculate every time yeah we initializing data structure to yeah we initializing data structure to store this al-anbar lying thing it's store this al-anbar lying thing it's gonna be a we can we can access that by gonna be a we can we can access that by the number of sub arrays we're the number of sub arrays we're considering so it's a hashmap with keys considering so it's a hashmap with keys being the index being the number of sub being the index being the number of sub arrays we're considering the value is arrays we're considering the value is going to be two things a typo or going to be two things a typo or an array of two things which is the an array of two things which is the maximum sum of the candidate list of maximum sum of the candidate list of indices so we're gonna have that way indices so we're gonna have that way what are we gonna call it max max sums it's gonna be defaulted the default value for those is going to be zero and empty list after that which is going to slide the M windows in simultaneously so we got out the iterator which is going to be the starting location for the very first window so I'm just gonna call it s meaning the starting location for the first suburb of sliding sub array so the range is gonna be from 0 which is the first allocation here towards it would be similar here it's just that the K would be multiplied by M m windows just gonna copy and multiply this by n the number of windows my conserving then we just got to loop through this thing one [Music] we will grab the Sudbury song you know what I'm already calling this window so you just gonna call this window windows on the go you say index so the first index is going to be as the first windows a starting location will be ass that's that's why we call this ass but for the eyes window it will be for the second window it will be this S Plus the window size K so since that we're working with arbitrary number the we can just use a variable to to do that to keep track of that so it's a s plus I minus 1 multiplied by the window size K so that's the that's the starting position for the eyes eyes sub-array running sub-array and we grab the sum instead of actually calculating on-the-fly actually calculate on the fryers also fly as also okay but I think this use a little bit extra space to speed up the things but potentially speed up things this pattern danya's just using this formula to do the grab the so this windows son here will grab the so this windows son here will be the correspondent to the current a be the correspondent to the current a sub-array I this same here and we want sub-array I this same here and we want to grab the maximum of I minus one so to grab the maximum of I minus one so it's I minus 1 and the the max is the it's I minus 1 and the the max is the first item in that so it's 0 if it's first item in that so it's 0 if it's greater than the the max of I which is greater than the the max of I which is using this key now the first element using this key now the first element then we just override this maximum with then we just override this maximum with the new maximum and we update the the new maximum and we update the candidate in the say list which which candidate in the say list which which will be the indices of n minus 1 the will be the indices of n minus 1 the maximum of the maximum for a candidate maximum of the maximum for a candidate for the N minus 1 I minus 1 I'm sorry for the N minus 1 I minus 1 I'm sorry concatenating the this L location that's concatenating the this L location that's the updates for the windows so in the the updates for the windows so in the end which is going to return the the end which is going to return the the very last ally and return the candidate very last ally and return the candidate candidate in the silliest so this n + 1 candidate in the silliest so this n + 1 so yeah so this is the code let me try so yeah so this is the code let me try runs for some examples missing one runs for some examples missing one required position argument and okay let required position argument and okay let me set a default here which is 3 what me set a default here which is 3 what the question originally is and say the question originally is and say submit so yeah it's working submit so yeah it's working so let's look at the code and do a so let's look at the code and do a little bit analysis about the time and little bit analysis about the time and space space so this Sudbury Sam's is pre calculated so this Sudbury Sam's is pre calculated the the size is a it's obvious the lens the the size is a it's obvious the lens minus k plus 1 so it's a and if we have minus k plus 1 so it's a and if we have n numbers so that's space and 404 for n numbers so that's space and 404 for generating this portion then looking at generating this portion then looking at this this data structure here the hash this this data structure here the hash map the keys are the M number M windows map the keys are the M number M windows the space requirement here is it's the space requirement here is it's dominated by the appended list so the dominated by the appended list so the first the first window yo has you will first the first window yo has you will have for the first two sub array they have for the first two sub array they were it would just have one index number were it would just have one index number but for the very last one the M it will but for the very last one the M it will be M element here and index are there so be M element here and index are there so it's one plus two plus and go all the it's one plus two plus and go all the way up to M windows am summaries I'm way up to M windows am summaries I'm sorry they're interchangeable yes you sorry they're interchangeable yes you you you should be okay understanding so you you should be okay understanding so it's a M squared that's the space for it's a M squared that's the space for for this data structure for this hash for this data structure for this hash mark it's predominated by the number of mark it's predominated by the number of index that we want to keep track of so index that we want to keep track of so that's what hash map here for this that's what hash map here for this looping condition here it's a outer loop looping condition here it's a outer loop and you know we're looking through all and you know we're looking through all the delenn's - some cost of smaller the delenn's - some cost of smaller things if they K and M are relatively things if they K and M are relatively small the array has this big this is small the array has this big this is pretty much just out of hand pretty much just out of hand the second loop in the inner loop is all the second loop in the inner loop is all of em so that the time for this is a of em so that the time for this is a multi-part the end is the resize m is multi-part the end is the resize m is the number of windows number of the number of windows number of race for space there's nothing here so race for space there's nothing here so so this space is the M squared plus egg so this space is the M squared plus egg and if we want to optimize for space a and if we want to optimize for space a little bit we can we can choose to not little bit we can we can choose to not do this but instead we can put one do this but instead we can put one element in the hashmap element in the hashmap to be the window zone to be the running to be the window zone to be the running running sub-array zone and instead of running sub-array zone and instead of doing this calculation just in a one-off doing this calculation just in a one-off fashion here for each of those windows fashion here for each of those windows we can instead of grabbing that from the we can instead of grabbing that from the pre calculate result we can just do do pre calculate result we can just do do the subtract and addition here with this the subtract and addition here with this index to be some kind of multiple of K index to be some kind of multiple of K and offset it by the S so that that can and offset it by the S so that that can remove the requirement for populating remove the requirement for populating this so dropping the time on our end and this so dropping the time on our end and the space order so the space will be the space order so the space will be strictly M Squared but I I think that strictly M Squared but I I think that will be little bit more tricky to will be little bit more tricky to writing interview time and you have to writing interview time and you have to deal with this s and you know this would deal with this s and you know this would be complicated the number of multiple of be complicated the number of multiple of another loop another thing here the da another loop another thing here the da here another Sam if you decide to do here another Sam if you decide to do that here it will be S Plus I don't even that here it will be S Plus I don't even want to I don't want to talk about that want to I don't want to talk about that formula but it's easy to get it formula but it's easy to get it anyway anyway this is the question it's anyway anyway this is the question it's a generic version solution so we a generic version solution so we supports arbitrary M and if I look at supports arbitrary M and if I look at the analysis is really not about the analysis is really not about anything different from one or two yeah anything different from one or two yeah all the things the area's just did this all the things the area's just did this relationship and that's pretty much it relationship and that's pretty much it alright so that's the question for today alright so that's the question for today bye for now
2024-03-20 17:09:13
689
https://i.ytimg.com/vi/r…axresdefault.jpg
Leetcode 689 Maximum Sum of 3 Non-Overlapping Subarrays
C5u_hvbq1qQ
That IPL 2000 Problems In Life In North And Look For Simple Right But Just In The North And Look For Simple Right But Just In The Mid Day To Copy No Optimal Solution 2019 Mid Day To Copy No Optimal Solution 2019 Tricks For Big Problems Tricks For Big Problems Sometimes In Talking About Very Similar Problem Only Give Sometimes In Talking About Very Similar Problem Only Give Hello Friends Welcome To My Subscribe Subscribe Limitations Subscribe To Let You A Letter To Make Short Were Doing A Letter To Make Short Were Doing Problems Worth Treating Not Problems Worth Treating Not Just These Tears And Cheers Elements You Need To Find Just These Tears And Cheers Elements You Need To Find Out How Many Elements Of Out How Many Elements Of Modern Modern Modern case number one Vihar second right and benefit amazing to deposit for each element unit of length is long then element number 8 how many elements of moral and even smaller to this model tourism and entry small do not give total Of Elements Right to Unit Two Right Down for Engineers and Robbers next9news Hello Cooking Hate You Hello Cooking Hate You Too Too Year-2013 Year-2013 Toll Free Number Toll Free Number to Do Subscribe Button and a Remedy Latest Writer Locator Take Care Number Two You Have the Element 65.88 The Element Six How Many Elements Confined to a Small Detail 514 Correct Elements of Elements of Elements of Modern 540 on the right side a similar diff is number three this for all a similar diff is number three this for all elements of 7 light to turn off elements elements of 7 light to turn off elements of smaller in this case Cancer of smaller in this case Cancer 20000 20000 not find any solution in front of you This Day This Staff Element Twist Comparing Between Element One Spinner Yes Tourism And Yes To Small Royce This Marvelous Gift Total Of Elements Like You Ca n't Stop Writing In This One Moving Forward Element Number One And Welcome Page 89 Tomato Two Is Not Does not feel left Does not feel left Does not feel left down 0 ki ko ine tube start element number 218 is note maurya vansh smaller two is equal dhund not maurya ko mute only five one element right the twilight wave similar you will get one can you will get over with oo 10 minutes work correctly and will give 10 minutes work correctly and will give 10 minutes work correctly and will give correct answer every time but problem with correct answer every time but problem with a a very large for example of no 15909 post office second element and again 15909 post office second element and again compete with a pinch of elements to what compete with a pinch of elements to what is happening taking a lot of time to is happening taking a lot of time to complete all complete all complete all Write To Improve The This Lipstick You Sample Are Once Again And Whenever Your Thinking About And Optimize Solution Just Ruler Of Things With Your Intuition How Can You Approach Problem Account Deficit In The Middle Of The Elements For all elements in early you can create a new account of switch of the element in there is not sorted in addition to attract the current account of this element Vivo phone that Tamilnadu Effigy start editing Number 8 Right For Number 8 Right For Number 8 Right For Themselves Will Increase Discount By One To Have Themselves Will Increase Discount By One To Have Next Such Element Number One Quarter Me To Family Increment Discount Again By One To That They Will Increase Discount By One To Index Number 2 And Intimate Discount Spoon Way Increment Vikram One Neck August 116 Go To Index August 116 Go To Index August 116 Go To Index Number 2 And Instruments Account Number 2 And Instruments Account Increment Discount Welcome To Similarly Increment Discount Welcome To Similarly Phone Number Three Level Increment The Account Phone Number Three Level Increment The Account Index Number 3 A Moving Ahead Like This With Salary Will Welcome Something A Right And What Is Not Telling If You Have A Right And What Is Not Telling If You Have 2103 2103 Dos Dos 3251 3251 chhath festival one you have three to love you one you have three to love you have one two three love you have two five say have one two three love you have two five say this one fix and you have this one fix and you have 182 right now go one step ahead just look at 182 right now go one step ahead just look at element number two e look to laptop element number two e look to laptop How many element to elements right and How many element to elements right and right the elements right the elements three 500 600 to Tubelight it's all elements and elements in this question you need to find the number kal su qualified dhul dhul tips hum off kal su qualified dhul dhul tips hum off switch off button to notification steadims page will switch off button to notification steadims page will give me give me Two will give two three will give oo the five plus one will give fix plus one will give fix 60 will give 60 will give 6162 e will give 6162 e will give 8080 will give oo that 8080 will give oo that 90 90 tune in airtel tune in airtel a suite 20 number three and what are the a suite 20 number three and what are the telling you mercy simply shading dat this telling you mercy simply shading dat this rebellion elements data rebellion elements data rebellion elements data Elements And Smaller Than Two And Than One Right Next You Have Five Elements Latest Model Country Where Two Too Two One Right You Have Fixed Animators Manvendra Hair Oil Officer Ban Sake This Fixed Element 2015 Light Move Ahead With No Limits For Elements Elements Elements That Pranav One Week Come Up With The Answer What The That Pranav One Week Come Up With The Answer What The Tools You Can Start Looking At All Of Tools You Can Start Looking At All Of The Independence And A Value On The Independence And A Value On Thursday Turn On The Question Thursday Turn On The Question Number Of Elements Of Of Elements In Of Elements In To-Do List To-Do List Play B's answer is B's answer is B's answer is a new latest figures how they can a new latest figures how they can write you do this ok hair vihar left side of the screen you can go to intimidation and write sample water does in the beginning create water does in the beginning create worked for counting point dry display create but there worked for counting point dry display create but there and Mrs too and Mrs too and Mrs too of Chief Minister for to that Pranav second is telling media have that Pranav second is telling media have best I have to app best I have to app 13018 right to connect with they are now what do you know subscribe this Video subscribe this Video give 123 day plus one day i will give you for ur day plus one day i will give you for ur day plus one day i will give you for ur reply flag can forgive and forget and reply flag can forgive and forget and ultimately which power grid now the is tele me ultimately which power grid now the is tele me data it for events at this month of data it for events at this month of three elements to smaller than three elements to smaller than one element smaller than 2 and have elements one element smaller than 2 and have elements involved in this involved in this involved in this out that there are moon on that similarly phone number to have a look at index stud and will get the volume 181 hair 10101 hair and ultimately or Please Please Please time Complexity of provident fund 1020 not mean that fits well into space so I hope life is the problem and solution for new item final moments thank you took advantage of accounting for them and tried to important question For Help You Avoid Subscribe Problem Problem Work Has Not Only Of Elements From Nehru Problem Very Much You Can Apply For For Bigger Problem Water Measure Pay And For Bigger Problem Water Measure Pay And Water Tank Withdrawal What Prompted To This Every Thing Water Tank Withdrawal What Prompted To This Every Thing This Comment Section 2D Attack this subscribe friends this friends this video problem
2024-03-21 00:40:13
1,365
https://i.ytimg.com/vi/C…axresdefault.jpg
Numbers Smaller than current Number (LeetCode 1365) | Full solution with examples | Study Algorithms
4IYQYJhi1LA
Hello friends welcome back and watch this video. Simply Want Justice For This Element Simply Want Justice For This Element 's Daughter Suri Cruise Patient Element From One 's Daughter Suri Cruise Patient Element From One Point In This Universe In This Year Now Point In This Universe In This Year Now Electric Reached To Of This Day Will Appear Electric Reached To Of This Day Will Appear In The List Of Elements Of Elements In The List Of Elements Of Elements For Example 123 Subscribe Will Start From For Example 123 Subscribe Will Start From Subscribe To Subscribe To With Mayor We With Mayor We With Mayor We Receive New Receive New Updates Time Play List Play Updates Time Play List Play One Phone The Last Second Position Verified So What Is One Phone The Last Second Position Verified So What Is Simply Dresses For Class Simply Dresses For Class Second Position Started Search This Second Position Started Search This Note To The Police Please My Note To The Police Please My Note To The Police Please My Bigg Boss Reading and Writing Video Subscribe One Place A Speech At Everything In This Way Can't Have Equal To Zero Track Hussain Saver Of The Number Please Please Please Please Please Subscribe My Apps Elements President of Ayyappan and Two Elements Means How Plus Debit So Now Simply Set Up Absolutely Free May Next Okay Bad Skin Element Which Is This Band's Play List Number One Position But Last But Not Least to lucknow wire i want to which is not good luck looking for land last element please please subscribe subscribe and subscribe how to fix deposit 1059 liquid course pretty pretty how to fix deposit 1059 liquid course pretty pretty simple is the only thing which simple is the only thing which assures a peon circle rate assures a peon circle rate assures a peon circle rate School Class Select Class Class Element In Placing Limits And Placid It's A Platform Elements Not Equal To The Last Second Element Severe Good Places Sequence Placid At Its Principles In Good Elements Which Can Simply Chari Net Acid Classification Share I Will Have The tap on the simply don't see the like oo
2024-03-20 12:08:52
80
https://i.ytimg.com/vi/4…LA/sddefault.jpg
Remove Duplicates from Sorted Array II - Leetcode
iHXfR-jdnLI
hey everyone today we'll be doing another lead code problem to uh seven to another lead code problem to uh seven to four point pivot Index this is an easy four point pivot Index this is an easy one given an array of nums calculate the one given an array of nums calculate the pivot index of this array the pivot pivot index of this array the pivot index of this array is where the sum of index of this array is where the sum of all the numbers tricky left of the index all the numbers tricky left of the index equal to the sum of the all the numbers equal to the sum of the all the numbers at the very right at the very right and if the index is on the left edge of and if the index is on the left edge of the array the array then the sum is going to be 0 to the then the sum is going to be 0 to the left the sum left sum is going to be 0 left the sum left sum is going to be 0 because there are no elements on the because there are no elements on the left this also applies to the right left this also applies to the right return the leftmost pivot index if no return the leftmost pivot index if no such then returns minus return minus 1 such then returns minus return minus 1 so we have an array like this in which so we have an array like this in which we are going to return the pivot index we are going to return the pivot index of pivot index at this point this point of pivot index at this point this point is going to be this 6 because the sum at is going to be this 6 because the sum at the very left of the index is the very left of the index is this is going to be returning 11 and this is going to be returning 11 and this is going to be returning 11 not this is going to be returning 11 not including the pivot itself including the pivot itself so what we can do is just make a left uh so what we can do is just make a left uh some variable and a write some variable some variable and a write some variable so the left sum obviously starting from so the left sum obviously starting from the very first they said like it is 0 the very first they said like it is 0 and we are not going to include the and we are not going to include the pivot in our index uh pivot the index pivot in our index uh pivot the index itself which we are considering a pivot itself which we are considering a pivot and not in our sum and not in our sum so one will not be added in neither of so one will not be added in neither of the right or left so right will be just the right or left so right will be just the sum of the whole array but minus 1 the sum of the whole array but minus 1 because we are at uh because we are at uh zero index and one is at the zero index zero index and one is at the zero index 28 is going to be the sum of this whole 28 is going to be the sum of this whole list and if you minus 1 we are getting list and if you minus 1 we are getting 27. then we will we are this is our 27. then we will we are this is our pivot and now we will just pivot and now we will just move our pivot move our pivot and add before moving our period we are and add before moving our period we are going to add that add the first index to going to add that add the first index to the left one you can say and the left one you can say and now when we go in the next iteration we now when we go in the next iteration we will remove it from the right one so we will remove it from the right one so we will check left and right are not equal will check left and right are not equal to 0 we will move our pointer to or our to 0 we will move our pointer to or our pivot to the next and then 7 is going to pivot to the next and then 7 is going to be added here so it will be like 8. be added here so it will be like 8. and now 3 will be decremented from here and now 3 will be decremented from here and the private will move to 6 and 3 and the private will move to 6 and 3 will be uh it was decremented from here will be uh it was decremented from here and it will be incremented here and it will be incremented here so it will become like 11 and now 6 is so it will become like 11 and now 6 is going to be decremented from here going to be decremented from here because we are at six we are not going because we are at six we are not going to include 6 and we are at 11 and 11 so to include 6 and we are at 11 and 11 so at this point at this 6 we are going to at this point at this 6 we are going to have 11 11 left sum is equal to the have 11 11 left sum is equal to the right one so we are going to return 3 in right one so we are going to return 3 in that case because the index of 6 was 3. um Okay so left is equal to 0 and the right is equal to the sum of sum of nums okay so for index index and element in in numerate in nums okay so first of all we have to decrement our right with the element element okay now if the right is equal to left we are going to return the index in text okay and after that we can just decrement or not decrement just increment our left by the element and that's it if you are going to find it then we are going to return the index otherwise we are going to return minus 1 that's it if you have any kind of that's it if you have any kind of questions you can ask them in the questions you can ask them in the comments
2024-03-21 10:58:42
724
https://i.ytimg.com/vi/i…LI/sddefault.jpg
724. Find Pivot Index | Leetcode | Python
WYeo6ApWK2U
well it's another death first search problem you know you want it you know problem you know you want it you know you came for it you came for it you can't live without it here we have you can't live without it here we have number 200 number of islands number 200 number of islands so this says so this says given an m by n 2d grid map given an m by n 2d grid map of one's land and zero's water of one's land and zero's water return the number of islands an island return the number of islands an island is surrounded by water is surrounded by water and is formed by connected connecting and is formed by connected connecting adjacent lens adjacent lens horizontally and vertically you may horizontally and vertically you may assume assume all four edges of the grid are all four edges of the grid are surrounded by water surrounded by water okay um well this is as if you just okay um well this is as if you just stepped in the mediterranean stepped in the mediterranean and they say hey uh identify uh and they say hey uh identify uh naxos samos kefalonia naxos samos kefalonia rhodes lesbos yes rhodes lesbos yes that's where lesbian comes from let's go that's where lesbian comes from let's go there and of course there and of course the biggest greek island crete the biggest greek island crete okay so you have these ones and okay so you have these ones and zeros and whenever you see a bunch of zeros and whenever you see a bunch of ones connected ones connected horizontally and vertically that's kind horizontally and vertically that's kind of one island so this is kind of of one island so this is kind of one big island here which is what they one big island here which is what they give one give one island whereas here you have kind of island whereas here you have kind of these these four ones in a bunch then this one and four ones in a bunch then this one and then these two so then there's then these two so then there's that's three islands so they're asking that's three islands so they're asking you to count the islands so this is a you to count the islands so this is a depth first search depth first search in which we're going to what we're going in which we're going to what we're going to do to do is kind of iterate through the 2d grid is kind of iterate through the 2d grid and every time we see a 1 we're going to and every time we see a 1 we're going to go down as far as we can with the ones go down as far as we can with the ones either vertically or horizontally and either vertically or horizontally and we're going to flip those ones that we're going to flip those ones that we're going to turn them into we're going to turn them into an s character and incidentally i think yeah they should have made this a character symbol instead they made it a string symbol over here kind of the double quotes whatever in any case um every time we see the ones we're going to convert them to s's so that we don't look at them again and but before we start our dfs we're going to increment our count by one and that's it at the end we're just going to return our count so first a little sanity check if grid as per usual if grid is empty okay then we're going to come up with um okay then we're going to come up with um an int my count which is zero and this is the new c plus i think they call it universal initialization and at the end we're gonna return my count so let's iterate down this grid so four into i equal zero i smaller than grid dot size i plus plus and now we're going to have our int j equals zero j smaller than grid zero dot size so these are the these are the rows j plus plus okay so as we go in so okay so our check what we're going to do is eventually have some kind of magic dfs function which is going to convert them into s's so we don't want to see s's as well so if we see a 1 we're in if we see a 0 or an s we don't go down the dfs so in fact let's just call it dfs so um if grid uh equals one equals one yeah as a matter of fact that's how we yeah as a matter of fact that's how we could do the check then could do the check then we start the then oh first we need to we start the then oh first we need to increment my count and then increment my count and then we could go down the dfs so let's send we could go down the dfs so let's send it it let's send it the grid let's let's send it the grid let's and let's send it our i and let's send it our i and j coordinates and actually i think and j coordinates and actually i think that's it that's it isn't it i think that's it we won't have isn't it i think that's it we won't have to do anything else after that to do anything else after that okay let's uh let's get down to this so we have this is our dfs function in which we're going to throw in our grid because the count we don't need to pass it in we as soon as we see an island we iterate all the way down and we can increment the count beforehand before getting in the dfs so we're throwing our grid by reference since we're going to modify it and then we're going to throw in i and cons and j okay now in this function here um okay now if we're going too far so all we want to do is just go in and as soon as we see more ones we just flip them to s's so that we don't see them again as we're iterating down the grid so let's see now so if i smaller than zero or let's use this c plus plus or which we can right now or j smaller than zero or i bigger or equal to what is this grid dot size or j bigger or equal to grid zero dot size or so okay so if we got that far that or so okay so if we got that far that means we could check means we could check grid i j not equal to uh what is this not equal to one uh yeah one if it's not equal to one then we just return we we came to a bad square so if we're yeah if we hit an s or a zero then we just get out of there otherwise we just set grid we just set the grid i j equals s for scene so if it's not equal to 1 then we don't care about it and then we just uh kind of move along in the dfs so dfs we're going to send it the grid and then we're going to send it i and j okay so there's four different okay so there's four different combinations we're doing i combinations we're doing i plus one i minus one plus one i minus one and we're doing j plus one and we're and we're doing j plus one and we're doing doing j minus one so going up and down j minus one so going up and down left and right and let's see if this left and right and let's see if this miraculously works miraculously works run code wrong answer run code wrong answer expected one when it saw a one here expected one when it saw a one here so what's this problem we got into so what's this problem we got into if it saw one it should at least if it saw one it should at least it should at least increment my count it should at least increment my count oh wait okay so this is a one oh wait okay so this is a one character that's so idiotic character that's so idiotic that's a one character and let's make that's a one character and let's make sure that we saw that let's run that sure that we saw that let's run that again again okay now it worked let's submit that okay now it worked let's submit that and we have a winner thanks a lot and we have a winner thanks a lot everyone everyone have yourselves a very good day or night have yourselves a very good day or night whatever time it is over there
2024-03-21 14:40:52
200
https://i.ytimg.com/vi_w…U/sddefault.webp
LeetCode 200: Number of Islands C++ In Plain English (Microsoft Interview Question)
KfVj2MtiWFk
welcome to october's leeco challenge today's problem is an insert into a today's problem is an insert into a binary search binary search tree you are given the root node of a tree you are given the root node of a binary search tree binary search tree and a value to insert into the tree and a value to insert into the tree return the root note of the binary return the root note of the binary search tree after the insertion search tree after the insertion it is guaranteed that the new value does it is guaranteed that the new value does not exist in the original not exist in the original binary search tree now notice there may binary search tree now notice there may be multiple valid ways for the insertion be multiple valid ways for the insertion for example if we were to insert five for example if we were to insert five into this binary search tree into this binary search tree we could insert it to the left node of we could insert it to the left node of seven or we could seven or we could restructure the tree added to the root restructure the tree added to the root and make four go into the bottom here and make four go into the bottom here on the right side of the three node i on the right side of the three node i would say ignore this would say ignore this this just makes it more confusing just this just makes it more confusing just look at this look at this binary search tree insertion and think binary search tree insertion and think about how we would about how we would write our algorithm now one of the write our algorithm now one of the things i realized is i've worked with things i realized is i've worked with binary search trees quite a bit but binary search trees quite a bit but i actually don't know how to do this i actually don't know how to do this which surprised me which surprised me but if you simplify this idea as simple but if you simplify this idea as simple as possible as possible like let's just say we have the number like let's just say we have the number five we know how to traverse the tree five we know how to traverse the tree right we could say right we could say if five is greater than fourth and go to if five is greater than fourth and go to the right if seven is the right if seven is uh or five is less than seven go to the uh or five is less than seven go to the left left and so on and so forth that's only when and so on and so forth that's only when we find that there's no more nodes we find that there's no more nodes that we should do the insertion we that we should do the insertion we should insert five here should insert five here but say that we have the number 2.5 for but say that we have the number 2.5 for example i know example i know these are all integers but just for these are all integers but just for example say we have the number 2.5 example say we have the number 2.5 we go left and then we would see that we go left and then we would see that 2.5 is between 2 and 3 right 2.5 is between 2 and 3 right so one of the first thoughts you might so one of the first thoughts you might have is oh then we should you know have is oh then we should you know restructure this to have 2.5 here and restructure this to have 2.5 here and then 3 to the right then 3 to the right but we don't need to do that actually but we don't need to do that actually because of the way the binary search because of the way the binary search trees are trees are structured there always will be one structured there always will be one level at the end where we can insert level at the end where we can insert our our value especially because we know our our value especially because we know that it's unique that it's unique there should be some child at the very there should be some child at the very end some sort of leaf end some sort of leaf that we should be able to insert it at that we should be able to insert it at the very end whether it's to its left or the very end whether it's to its left or right and still keep the structure of right and still keep the structure of the binary search tree the binary search tree so because of that this really is not so because of that this really is not that complicated that complicated what we're going to do is write a what we're going to do is write a function and we'll just call it function and we'll just call it insert and we'll pass in the root or insert and we'll pass in the root or we'll call it node we'll call it node as well as the value now as well as the value now usually with these sort of binary search usually with these sort of binary search tree problems we have like a base tree problems we have like a base condition condition but you'll notice that we'll actually but you'll notice that we'll actually don't need that here um and i'll show don't need that here um and i'll show you why you why so if the value so if the value is greater than the node's value then is greater than the node's value then what do we want to do we want to go to what do we want to do we want to go to the right side the right side right so we'll just do the insert and go right so we'll just do the insert and go to the right otherwise we know that it's less so we're going to go to the left side all right so where do we do the insertion well here's the problem we actually need to insert it when we're at the node right we can't insert when we're at a at a null value so it's not this base condition that we want to put we just want to check here if node.right is null so if not node.right this is where we just insert it into the node so we say node.right is just going to equal tree node of this value and then we just end right there so we can just make this an else and continue on forward like this same thing here if not node dot left and make the no dot left equal to tree value otherwise we keep traversing and do the insert here so this is recursive but notice that the base condition comes so that i thought was interesting but so that i thought was interesting but that makes total sense right that makes total sense right so all we need to do then is so all we need to do then is run our code insert the root and value run our code insert the root and value and then just return the root after and then just return the root after we're finished now one edge case we're finished now one edge case if the root is blank we still need to if the root is blank we still need to create create a node for the tree so if not root we're a node for the tree so if not root we're just going to return just going to return the tree node of this value the tree node of this value because that is now going to be the root because that is now going to be the root all right so let's see if this works and it looks like it's doing what we want uh this is the example we've been given and you can see five has been put to the uh left side of seven here i think well um i guess we can just take a look and yeah so five is at the left side of and yeah so five is at the left side of seven this correct let's go and submit seven this correct let's go and submit that and there we go accepted so when i first saw this problem it kind of worried me because i wasn't sure i've never seen this before it might be complicated but as soon as i realized you know we can always insert this value into some sort of leaf at the very bottom it becomes very very simple so great thanks for watching my channel and
2024-03-21 10:09:55
701
https://i.ytimg.com/vi_w…k/sddefault.webp
Leetcode - Insert into a Binary Search Tree (Python)
EVxTO5I0d7w
everyone welcome back and let's write some more neat code today's today let's some more neat code today's today let's solve the problem minimum cost to cut a solve the problem minimum cost to cut a stick and to be honest somebody at leak stick and to be honest somebody at leak code really needs to put down the crack code really needs to put down the crack pipe because we are given a wooden stick pipe because we are given a wooden stick of length n so far so good the stick is of length n so far so good the stick is labeled from zero up until n so just labeled from zero up until n so just like you know a meter stick or something like you know a meter stick or something like that and we're also given an array like that and we're also given an array of cuts which tell us where we are going of cuts which tell us where we are going to perform the cut so for example we to perform the cut so for example we could cut here we could cut there we could cut here we could cut there we could cut here but then they tell us we could cut here but then they tell us we should perform the cuts in order and should perform the cuts in order and also you can change the order of the also you can change the order of the cuts as you wish and at that point I cuts as you wish and at that point I just stop reading the description just stop reading the description because it's probably not going to help because it's probably not going to help you understand the problem so let's you understand the problem so let's actually look at the example so let's actually look at the example so let's say we're given n equals seven and these say we're given n equals seven and these are the cuts now they tell us here that are the cuts now they tell us here that if we try to just perform the cuts in if we try to just perform the cuts in the order that they're given we do not the order that they're given we do not end up with the optimal result and by end up with the optimal result and by the way every time we perform a cut so the way every time we perform a cut so for example one we're going to be for example one we're going to be cutting right here every time we perform cutting right here every time we perform a cut we take the length of the stick a cut we take the length of the stick that we just cut which in this case is that we just cut which in this case is seven zero up until seven and we add it seven zero up until seven and we add it to like the cost we're trying to to like the cost we're trying to calculate the cost of cutting the stick calculate the cost of cutting the stick with all these cuts and where not only with all these cuts and where not only that we're trying to minimize that cost that we're trying to minimize that cost so in this case no matter which one of so in this case no matter which one of these Cuts we do first I mean the length these Cuts we do first I mean the length is of length seven so we're always going is of length seven so we're always going to have to have a plus seven here next to have to have a plus seven here next let's try to perform the three cut so let's try to perform the three cut so these are our two sticks remaining these are our two sticks remaining suppose we do the cut here what's the suppose we do the cut here what's the length of this portion of the stick it's length of this portion of the stick it's length six so then we add a plus six to length six so then we add a plus six to our total cost next try to do the four our total cost next try to do the four we cut here the length of this portion we cut here the length of this portion looks to me like it's also four so then looks to me like it's also four so then we say plus four and lastly we do the we say plus four and lastly we do the five on this portion which is of length five on this portion which is of length three and then we end up with these three and then we end up with these sticks we don't care about the sticks we sticks we don't care about the sticks we care about the cost so we add the plus care about the cost so we add the plus three here total we get 20 was the cost three here total we get 20 was the cost now there's different orderings that we now there's different orderings that we could have done the cuts in and this could have done the cuts in and this happens to be the optimal ordering first happens to be the optimal ordering first cutting three which again would give us cutting three which again would give us a cost of seven then cut five rather a cost of seven then cut five rather than cutting four because it kind of than cutting four because it kind of divides the stick into evenly sized divides the stick into evenly sized portions rather than cutting it here portions rather than cutting it here which would leave us with a one but then which would leave us with a one but then also leave us with a three over here so also leave us with a three over here so cutting here first gives us a cost of cutting here first gives us a cost of four not bad then do one over here the four not bad then do one over here the length of this portion is three so we length of this portion is three so we get a plus three and then lastly we do get a plus three and then lastly we do the four cut the length of this portion the four cut the length of this portion is two so we ended up I think with a is two so we ended up I think with a cost of 16. so clearly doing it in this cost of 16. so clearly doing it in this order is minimal but if we try to Brute order is minimal but if we try to Brute Force this we'll have to pretty much try Force this we'll have to pretty much try every permutation of cuts I think that's every permutation of cuts I think that's roughly n factorial and that's not going roughly n factorial and that's not going to be super efficient so let's see how to be super efficient so let's see how we can try to optimize this problem and we can try to optimize this problem and first let's just kind of understand how first let's just kind of understand how we can even think about this problem at we can even think about this problem at all like how could we even Solve IT all like how could we even Solve IT recursively even with a Brute Force recursively even with a Brute Force approach well let's consider the choices approach well let's consider the choices that we have we know we have a choice that we have we know we have a choice for every single cut we could cut three for every single cut we could cut three first we could cut at five first we first we could cut at five first we could cut at one first or we could cut could cut at one first or we could cut at four first I redo it just to make it at four first I redo it just to make it a bit more clearer that these are like a bit more clearer that these are like the cuts that are happening but what the cuts that are happening but what kind of value are we going to be kind of value are we going to be maintaining let's suppose we did the cut maintaining let's suppose we did the cut on three we knew originally the length on three we knew originally the length of our stick was seven now that we cut of our stick was seven now that we cut three obviously we're gonna have two three obviously we're gonna have two different sticks at this point it looks different sticks at this point it looks like we're gonna have a stick of length like we're gonna have a stick of length three and we're gonna have a stick of three and we're gonna have a stick of length four and we need to then length four and we need to then recursively go in both directions so recursively go in both directions so basically every time we perform a cut basically every time we perform a cut we're actually not creating one branch we're actually not creating one branch for that we're we're creating two for that we're we're creating two branches branches um maybe I'm not drawing it super um maybe I'm not drawing it super clearly but that's because it's kind of clearly but that's because it's kind of hard to visualize but notice how like hard to visualize but notice how like saying okay now the length of the stick saying okay now the length of the stick here is three the length of the stick on here is three the length of the stick on this side is four that's not really this side is four that's not really enough information because now if we try enough information because now if we try additional Cuts like we try to perform a additional Cuts like we try to perform a five cut here a one cut a four cut we five cut here a one cut a four cut we don't know does that cut actually apply don't know does that cut actually apply because if we're cutting at the five because if we're cutting at the five Mark we can't cut like this stick at the Mark we can't cut like this stick at the five Mark and this stick of length four five Mark and this stick of length four we can't just cut it at some arbitrary we can't just cut it at some arbitrary spot we have to cut it at this spot we have to cut it at this particular spot we have to know that particular spot we have to know that that's where we're cutting it and it's that's where we're cutting it and it's going to be split into two sticks of going to be split into two sticks of length two so rather than keeping track length two so rather than keeping track of the length of our portion let's keep of the length of our portion let's keep track of the range of it so initially track of the range of it so initially we're at a range from left equals zero we're at a range from left equals zero to right equals seven so that gives us a to right equals seven so that gives us a more clear definition of the sub problem more clear definition of the sub problem that we are currently at now the other that we are currently at now the other thing is let's suppose we did cut at thing is let's suppose we did cut at three it's pretty easy for us to know three it's pretty easy for us to know what the cost of that cut at 3 three was what the cost of that cut at 3 three was because we just take the length of our because we just take the length of our range we could take right minus left range we could take right minus left that gives us the length so that's easy that gives us the length so that's easy enough but now that we already used the enough but now that we already used the three now from here we're probably going three now from here we're probably going to make some more choices right probably to make some more choices right probably these choices we still have to do the these choices we still have to do the five cut we still have to do the one cut five cut we still have to do the one cut and we still have to do the four cut so and we still have to do the four cut so should we be keeping track of that cuts should we be keeping track of that cuts array and like dynamically removing from array and like dynamically removing from it as we already perform a cut you could it as we already perform a cut you could try it that way it'd be kind of try it that way it'd be kind of complicated to do it but notice that complicated to do it but notice that it's actually not really necessary in it's actually not really necessary in the context of this problem if we the context of this problem if we perform a three cut and now here we try perform a three cut and now here we try to perform four more Cuts again to perform four more Cuts again including the three cut if I try to do including the three cut if I try to do the three the five the one and the four the three the five the one and the four the three cut is not really gonna do the three cut is not really gonna do anything anymore because we know after anything anymore because we know after we did the cut here we actually ended up we did the cut here we actually ended up with two sticks from zero to three and with two sticks from zero to three and then another stick from three to seven then another stick from three to seven so you can try cutting this stick at the so you can try cutting this stick at the three Mark like this stick over here you three Mark like this stick over here you can try cutting it here it's not really can try cutting it here it's not really doing anything you can try cutting this doing anything you can try cutting this stick at the three Mark it's not really stick at the three Mark it's not really doing anything so basically there's an doing anything so basically there's an easier way for us to know that this cut easier way for us to know that this cut is unnecessary and that's basically is unnecessary and that's basically every time we try a cut let's at least every time we try a cut let's at least make sure that that cut in this case make sure that that cut in this case three let's at least make sure that cut three let's at least make sure that cut is greater than the left boundary and is greater than the left boundary and less than the right boundary in this less than the right boundary in this case three is not greater than the three case three is not greater than the three and less than the seven this does not and less than the seven this does not apply therefore this cut does not apply apply therefore this cut does not apply to this segment and also the one cut to this segment and also the one cut over here also wouldn't apply to this over here also wouldn't apply to this segment of the stick so therefore segment of the stick so therefore there's an easier way for us to know there's an easier way for us to know that this branch is not going to do that this branch is not going to do anything for us and also the one branch anything for us and also the one branch is not gonna on this portion of the is not gonna on this portion of the stick and the five we're would not do stick and the five we're would not do anything on this portion and the four anything on this portion and the four would not do anything on this portion of would not do anything on this portion of the stick so that is an easy way to the stick so that is an easy way to simplify this problem and believe it or simplify this problem and believe it or not those are really the two points that not those are really the two points that you need to keep track of to solve this you need to keep track of to solve this problem even though this is a hard problem even though this is a hard problem it's actually surprisingly not problem it's actually surprisingly not super insane I guess the hard part was super insane I guess the hard part was trying to understand what the hell trying to understand what the hell they're asking for again the two points they're asking for again the two points are that we're keeping track of the are that we're keeping track of the range of our stick and that we're just range of our stick and that we're just going to be looping through all the going to be looping through all the possible Cuts determining if a cut possible Cuts determining if a cut actually is valid for that portion of actually is valid for that portion of the stick or not and that will be enough the stick or not and that will be enough to solve this problem especially when we to solve this problem especially when we apply caching to it because you notice apply caching to it because you notice that the sub problem itself is very that the sub problem itself is very simple we don't even need to keep track simple we don't even need to keep track of this as part of the sub problem we of this as part of the sub problem we simplified that part we only need to simplified that part we only need to keep track of the range and there's keep track of the range and there's going to be two values left and right going to be two values left and right the possible combinations of these two the possible combinations of these two values are going to be n possibilities values are going to be n possibilities for left because it could be any of for left because it could be any of these values same thing for right so the these values same thing for right so the number possibilities is going to be N number possibilities is going to be N squared now we are going to be looping squared now we are going to be looping through the cuts array each time so I through the cuts array each time so I believe the overall time complexity is believe the overall time complexity is going to be the length of the cuts array going to be the length of the cuts array let's call that M multiplied by N let's call that M multiplied by N squared where n is given to us as a squared where n is given to us as a parameter so now let's code this up so parameter so now let's code this up so remember we're going to have a recursive remember we're going to have a recursive function I'm going to call it DFS the function I'm going to call it DFS the range of our sub problem is going to be range of our sub problem is going to be defined from left to right and defined from left to right and immediately let me show you how I'm immediately let me show you how I'm going to call this I'm going to call DFS going to call this I'm going to call DFS starting from 0 going up until n which starting from 0 going up until n which is the parameter given to us and I guess is the parameter given to us and I guess this is one thing I didn't talk about this is one thing I didn't talk about what's going to be the base case for what's going to be the base case for this problem possibly where the length this problem possibly where the length of the stick is equal to zero possibly of the stick is equal to zero possibly where left is equal to right well is where left is equal to right well is that technically possible is it possible that technically possible is it possible for us to cut this stick in such a way for us to cut this stick in such a way that we get a length segment that's of that we get a length segment that's of equal to zero not really so we're equal to zero not really so we're probably never going to call DFS where probably never going to call DFS where the two left and right boundaries are the two left and right boundaries are equal it wouldn't really make sense the equal it wouldn't really make sense the base case would basically be if none of base case would basically be if none of the cuts apply to this segment and we the cuts apply to this segment and we don't necessarily know that until we don't necessarily know that until we iterate through the list of cuts but iterate through the list of cuts but there is one case where we do there is one case where we do immediately know that and that's when immediately know that and that's when the length of our segment is equal to the length of our segment is equal to one so basically R minus left is equal one so basically R minus left is equal to one and in that case we would just go to one and in that case we would just go ahead and return zero let me add the If ahead and return zero let me add the If part to that here so that's the main part to that here so that's the main base case we're going to have another base case we're going to have another base case for the caching case but for base case for the caching case but for now I'm just gonna code this up the now I'm just gonna code this up the Brute Force way so remember we're trying Brute Force way so remember we're trying to minimize the cost so let's initialize to minimize the cost so let's initialize the cost to be a really big value like the cost to be a really big value like infinity and then let's start going infinity and then let's start going through every possible cut in the cuts through every possible cut in the cuts or right now how do we know if this cut or right now how do we know if this cut applies remember if the cut is greater applies remember if the cut is greater than left and less than right and in than left and less than right and in Python you can do that with like a Python you can do that with like a single equality like this but maybe in single equality like this but maybe in other languages you can't now how do we other languages you can't now how do we calculate the cost well the cost to cut calculate the cost well the cost to cut this stick was right minus left plus now this stick was right minus left plus now let's run DFS on the left portion of the let's run DFS on the left portion of the stick which we can get by taking the stick which we can get by taking the left pointer and the cut position left pointer and the cut position because that kind of tells us now where because that kind of tells us now where the end of that stick is going to be and the end of that stick is going to be and let's also call DFS on the right portion let's also call DFS on the right portion which is going to be from the cut mark which is going to be from the cut mark up until the right pointer and remember up until the right pointer and remember we're trying to minimize the result so we're trying to minimize the result so let's set result equal to minimum of let's set result equal to minimum of itself and this portion which is the itself and this portion which is the recursive case of course so after this recursive case of course so after this our result will be minimized now our result will be minimized now technically there is an edge case what technically there is an edge case what if none of the cuts actually apply like if none of the cuts actually apply like we never even executed the recursive we never even executed the recursive case result would still be infinity and case result would still be infinity and that's probably not what we want to that's probably not what we want to return so maybe we can set result equal return so maybe we can set result equal to zero if it's still equal to Infinity to zero if it's still equal to Infinity that basically tells us that we could that basically tells us that we could not cut the stick just like in this case not cut the stick just like in this case otherwise we leave it as the result and otherwise we leave it as the result and then here we return the result so that's then here we return the result so that's pretty much the entire code and believe pretty much the entire code and believe it or not it actually does pass on leak it or not it actually does pass on leak code and you can see the time complexity code and you can see the time complexity is not going to be super efficient is not going to be super efficient actually this won't pass on lead code I actually this won't pass on lead code I forgot to do the caching so let's make forgot to do the caching so let's make sure we do that which is usually pretty sure we do that which is usually pretty easy just a few lines I'm going to easy just a few lines I'm going to create our DP cache in this case I'm create our DP cache in this case I'm going to use a hash map but you could going to use a hash map but you could probably use a two-dimensional array I'm probably use a two-dimensional array I'm going to check has this key already been going to check has this key already been computed and if it has go ahead and computed and if it has go ahead and return it like this if it hasn't let's return it like this if it hasn't let's go ahead and compute it which basically go ahead and compute it which basically means we're Computing the result so means we're Computing the result so before we return the result let's also before we return the result let's also make sure we add that same value into make sure we add that same value into the cache which I'm just doing in a the cache which I'm just doing in a single line sorry if this is confusing single line sorry if this is confusing because there's multiple assignments because there's multiple assignments being made this is being assigned to being made this is being assigned to result and result is being assigned to result and result is being assigned to that and then we're returning the same that and then we're returning the same value so now let's run this to make sure value so now let's run this to make sure that it works and as you can see yes it that it works and as you can see yes it does and it's somewhat efficient I think does and it's somewhat efficient I think there's a slight optimization that leak there's a slight optimization that leak code made in the editorial but I think code made in the editorial but I think the overall time complexity actually the overall time complexity actually can't really be improved no matter what can't really be improved no matter what you are going to need a loop inside of you are going to need a loop inside of the recursive function if you found this the recursive function if you found this helpful please like And subscribe if helpful please like And subscribe if you're preparing for coding interviews you're preparing for coding interviews check out neatcode.io it has a ton of check out neatcode.io it has a ton of free resources to help you prepare free resources to help you prepare thanks for watching and I'll see you thanks for watching and I'll see you soon
2024-03-21 11:45:45
1,547
https://i.ytimg.com/vi/E…axresdefault.jpg
Minimum Cost to Cut a Stick - Leetcode 1547 - Python
TCDrL3LVc5s
hello today we are going to take a look at question 539 minimum time difference at question 539 minimum time difference in this problem we are given a list of in this problem we are given a list of 24-hour clock time points in our minutes 24-hour clock time points in our minutes format and we need to find the minimum format and we need to find the minimum minutes difference between any two time minutes difference between any two time points in the list let's take a look at points in the list let's take a look at example one so the time 23 hours 59 example one so the time 23 hours 59 minutes and 0 hours 0 minutes is one set minutes and 0 hours 0 minutes is one set one minute note the number of time one minute note the number of time points in the given list is at least 2 points in the given list is at least 2 and I won't exit to 20,000 the input and I won't exit to 20,000 the input time is legal and the range is from 0 time is legal and the range is from 0 hours 0 minutes to 23 over 59 minutes ok hours 0 minutes to 23 over 59 minutes ok so how are we going to solve this so how are we going to solve this problem first let's take a look to solve problem first let's take a look to solve this problem there is no algorithm to this problem there is no algorithm to apply just just the procedures so first apply just just the procedures so first we will need to so we're given a list we will need to so we're given a list right so we will need to put all convert right so we will need to put all convert all the time in two minutes all the time in two minutes so and put it in to our new list then we so and put it in to our new list then we sort them so first sort them so first minutes time lists minutes time lists minutes time lists so second we sort of a list sort of a minutes time list so third we get a Jensen adjacent difference in our sorted list and then we find the minimum difference so this is how we are going to get our answer okay so it's step by step then let's take a look at how to do each steps so first step to create our minimum time to create our minute time list minute time list okay to do that first we have to know how many minutes in a day so this formula tells us it's 1440 minutes in a day okay so we first create a magic number called ten minutes one go further okay why we need to do this because sometimes we need to use this value to get the difference because the get the difference because the difference is not just simply miners difference is not just simply miners sometimes okay so the second step is sometimes okay so the second step is after we get this there is there is after we get this there is there is there are two exceptions we have to there are two exceptions we have to consider so let's say the first consider so let's say the first exception is that the list we are given exception is that the list we are given as all the numbers all the time points as all the numbers all the time points we in a day so if that is the case and we in a day so if that is the case and there must be two to duplicated time there must be two to duplicated time points in that list therefore we will points in that list therefore we will just return 0 Thanks just return 0 Thanks there are two time points they are there are two time points they are exactly the same so there is no exactly the same so there is no difference difference so the minimum difference is zero and so the minimum difference is zero and there's another problem is that if the there's another problem is that if the time the length of the time point is 1 time the length of the time point is 1 so that what will happen is that so so that what will happen is that so there's only one time points therefore there's only one time points therefore we return 10 minutes since there is no we return 10 minutes since there is no other time points after after that one other time points after after that one so there is no that is not a good case so there is no that is not a good case but now I look at this sentence it says but now I look at this sentence it says the number of time points in the given the number of time points in the given list is at least the two therefore I list is at least the two therefore I don't think we need this exception okay don't think we need this exception okay that's moving on that's moving on so now we are going to create our list so now we are going to create our list new list with time and we need to create new list with time and we need to create a variable which is our answer a variable which is our answer eventually it's the minimum difference eventually it's the minimum difference so the minimum difference we first the so the minimum difference we first the curator the biggest number as possible curator the biggest number as possible so we give it this now it's time to put so we give it this now it's time to put our time points convert them and put it our time points convert them and put it in all times so we iterate through the in all times so we iterate through the time points so first we have to deal time points so first we have to deal with one exception which is the time is with one exception which is the time is equals to zero zero at that time we equals to zero zero at that time we should not give zero to append zero to should not give zero to append zero to our new list instead we have to depend our new list instead we have to depend the ten minutes the reason why is the ten minutes the reason why is because we needed so we need the minimum because we needed so we need the minimum difference therefore when it's when it difference therefore when it's when it comes to zero we use that we can if we comes to zero we use that we can if we use their own which sorry the result we use their own which sorry the result we get will not be the minimum therefore we get will not be the minimum therefore we need to choose the so another expression need to choose the so another expression of this time which is the ten minutes so of this time which is the ten minutes so cycle it's like how to say it like 12 cycle it's like how to say it like 12 p.m. is exactly the same as zero a.m. so after this we just continue things or process so this time has been processed so so if the time is not this we need to do we need to and extract the over and the minutes out from over time which we split it by step of this so we get our hour and minute number then how are we going to convert it to minute so we are now 1 over consisted of 16 minutes and at the minute so we get we converted that we get the converted form now we add this into our new list ok our new list have the converted time okay now it is time for us to sort it after we sorted it we have to iterate it one more time things because so we have already finished step 1 and step 2 and now we need to do step 3 which is we so the way we get it is we just iterate so the way we get it is we just iterate through it and keep getting the through it and keep getting the pageant's and difference and and then we pageant's and difference and and then we compare this adjacent difference with compare this adjacent difference with the minimum difference if it's smaller the minimum difference if it's smaller than the minimum difference the minimum than the minimum difference the minimum difference will be replaced by this difference will be replaced by this different stuff in that case so the different stuff in that case so the minimum difference will get lower minimum difference will get lower smaller and smaller then eventually smaller and smaller then eventually we'll get the smallest difference okay we'll get the smallest difference okay now after this can we just the return now after this can we just the return minimum difference the reason is so the minimum difference the reason is so the the answer is we can't why because the the answer is we can't why because the minimum difference we get so we sorted minimum difference we get so we sorted the new list but there's one more saying the new list but there's one more saying we have to check which could be the we have to check which could be the minimum so the smallest time for them minimum so the smallest time for them boots let's say one the biggest let's boots let's say one the biggest let's see let's see 10 so we had 2 3 4 5 6 9 see let's see 10 so we had 2 3 4 5 6 9 so there will be a case the number the so there will be a case the number the difference between this is not difference between this is not soft so it's the smallest I don't know I soft so it's the smallest I don't know I don't know how to give you an example don't know how to give you an example but sometimes that will be the case when but sometimes that will be the case when you convert those time into time minutes you convert those time into time minutes lists so sometimes this will be the case lists so sometimes this will be the case therefore that's one thing we need to do therefore that's one thing we need to do is we need to get the difference between is we need to get the difference between the first number and the last number of the first number and the last number of our new list and of course sometimes the our new list and of course sometimes the time is sometimes the the number is not time is sometimes the the number is not so if we get the number simply sometimes so if we get the number simply sometimes it is not the case therefore we need to it is not the case therefore we need to add the 10 minutes since it's already I add the 10 minutes since it's already I don't know because we need to get the don't know because we need to get the minimum minutes difference therefore we minimum minutes difference therefore we need to check this so after this then we can start return if this T is bigger than zero usually it will bigger than zero bit well but usually it won't smaller than minimum difference else we will just return yes so the tricky thing is a lot of yes so the tricky thing is a lot of people they forget to check this depth people they forget to check this depth so I'll think of an example of why you so I'll think of an example of why you have to check this example so it's we have to check this example so it's we have already sorted the minimum list and have already sorted the minimum list and it's from the smallest to the biggest but if we - it and its last ten minutes yes yes because sometimes for damp Oh hmm so ten minutes is one four four zero so for example the first number is one and the last number is one four four zero so we know so one four three no just one four four zero so we know this is very small so their difference is very small so don't make I'll make it clear for them po the first the smallest number in our list is one the biggest is one four four zero so we know the difference between this two is one right but if we just attract the adjacent but if we just attract the adjacent difference we will miss it the further difference we will miss it the further orders this the second number we carried orders this the second number we carried back three four or five you name it then back three four or five you name it then we will get the we will get the minimum numbers too but the the truth is minimum numbers too but the the truth is this the difference between the smallest this the difference between the smallest number and the biggest number is our number and the biggest number is our minimum difference therefore we have to minimum difference therefore we have to consider this
2024-03-20 10:31:31
539
https://i.ytimg.com/vi_w…xresdefault.webp
leetcode 539. Minimum Time Difference
Tt3poT5qOqI
we will have pointer J to go through each index and check for non-zero each index and check for non-zero numbers and we will have pointer I to numbers and we will have pointer I to replace all the zeros with nonzero replace all the zeros with nonzero numbers identified by pointer J and to numbers identified by pointer J and to set Zer at the end of set Zer at the end of array here value at J pointer is zero array here value at J pointer is zero therefore we will move therefore we will move on now J pointer is at a non zero value on now J pointer is at a non zero value therefore we will assign this value to therefore we will assign this value to the I pointer and then increment the I the I pointer and then increment the I pointer again J pointer is at a zero value so we will move on now 3 is non zero therefore we will assign it to the ey pointer and increment ey pointer 12 is also non zero therefore we will assign it to the I pointer and pointer now we can assign all the pointer now we can assign all the elements being visited by I pointer to Z this is the final result now let's code the solution we will set pointer I and J to zero initially we will use J pointer to iterate through all the elements in the array whenever we find a nonzero value we will assign it to I pointer and increment I pointer after that we we will assign zero let's run the solution it's working see you in the video
2024-03-22 14:08:18
283
https://i.ytimg.com/vi/T…axresdefault.jpg
283. Move Zeroes | LeetCode 75 #10 | Two Pointers
QklIrzxiqcM
welcome to august liko challenge today's problem is some of left leaves today's problem is some of left leaves find the sum of all left leaves in a find the sum of all left leaves in a given binary tree given binary tree you can see we have a binary tree here you can see we have a binary tree here and a left leaf and a left leaf is while a leaf on the left side is while a leaf on the left side so it's got no children and it's coming so it's got no children and it's coming from the left from the left we want to sum them all up so here 9 and we want to sum them all up so here 9 and 15 are the only ones 15 are the only ones and we'll turn 24. so to solve this and we'll turn 24. so to solve this problem problem i'm going to use a deferred search and i'm going to use a deferred search and what i'm going to do is what i'm going to do is traverse the entire tree and only start traverse the entire tree and only start checking to see if we are on a left checking to see if we are on a left leave at the very end so leave at the very end so just a normal dfs what we'll do is pass just a normal dfs what we'll do is pass in the node in the node and we'll say if not node return and otherwise we will call the node.left and the node dot right now here we need to have some sort of checker to see if that this is a leaf or not so we could just say if not no dot left and not no dot right we will increase our total by the no doubt value so we're only going to add up to children here we'll have some sort of self variable on top and we'll start with zero but one thing to note we need to know if we're on the left side or the right side and we're not gonna be able to tell that from the note itself we're gonna have to keep track of where we've been passed from so to do that i can just pass another variable and when we're coming from the left i and when we're coming from the left i will make that equal to true and will make that equal to true and if we're not we'll make that equal to if we're not we'll make that equal to false and that is going to be an extra check here and left that's going to make sure that we only add up the left leaves finally we just need to call this the root and we will pass in false because we're not coming in from the left technically so we're just coming from the root so that's going to be a false finally at the very end we just return the and that's it it's a and that's it it's a pretty straightforward problem let's go pretty straightforward problem let's go and submit that and accept it so main trick here is to realize that since at the node we're at we're not going to be able to know if we're coming from the left or the right we have to pass that along and once we realize that everything else is pretty straightforward so that's it thanks for watching my channel and remember do not trust me
2024-03-15 18:26:41
404
https://i.ytimg.com/vi/Q…cM/sddefault.jpg
Leetcode - Sum of Left Leaves (Python)
7Ki94tmHTXY
hey guys how's everything going let's continue our journey to lead code yay continue our journey to lead code yay I'm Jay sir who is not good at algorithm I'm Jay sir who is not good at algorithm today we will look at 102 7 longest today we will look at 102 7 longest arithmetic sequence sequence given an arithmetic sequence sequence given an array a of integers return the length of array a of integers return the length of the longest arithmetic subsequence in a the longest arithmetic subsequence in a ok so 4 3 6 9 12 out of them are ok so 4 3 6 9 12 out of them are arithmetic sequence right so the longest arithmetic sequence right so the longest will be in the whole array four nine will be in the whole array four nine four seven to 10 a long case would be 4 four seven to 10 a long case would be 4 7 10 yeah an example 3 like this will be 7 10 yeah an example 3 like this will be longest will be 20 15 10 5 well let's longest will be 20 15 10 5 well let's analyze some basic examples if the analyze some basic examples if the elements the input will be longer than 2 elements the input will be longer than 2 so if there is only 2 elements like 3 6 so if there is only 2 elements like 3 6 of course the longest will be the whole of course the longest will be the whole array and if there is 3 6 9 array and if there is 3 6 9 of course 3 6 9 let's define what is of course 3 6 9 let's define what is this arithmetic sequence this arithmetic sequence well the sequence will have a have a well the sequence will have a have a characteristic that the increment is the characteristic that the increment is the same right so 3 plus 3 is 6 plus 3 is 9 same right so 3 plus 3 is 6 plus 3 is 9 plus 3 is 12 so actually the element is plus 3 is 12 so actually the element is start start annamund plus the increment start start annamund plus the increment but actually define the whole Earthman but actually define the whole Earthman arithmetic set sequence right and the arithmetic set sequence right and the increment is defined by the top two increment is defined by the top two element right if we have the top two element right if we have the top two elements like this and we can just edit elements like this and we can just edit check if check if nine is in the fall in the rest elements nine is in the fall in the rest elements and we find a line we can check if 12 is and we find a line we can check if 12 is the nment thus for each two top two the nment thus for each two top two elements we can use extra linear time to elements we can use extra linear time to detect the longest arithmetic sequence detect the longest arithmetic sequence and how many top top numbers are there and how many top top numbers are there well into the end to the square square n well into the end to the square square n right so totally we can achieve we can right so totally we can achieve we can tackle this problem by and to the cube tackle this problem by and to the cube of time complexity right we just start of time complexity right we just start with any top two elements and just to do with any top two elements and just to do the iteration to check the next possible the iteration to check the next possible animate well sure let's just try to animate well sure let's just try to start so the the idea is start with all start so the the idea is start with all possible top two elements and they use a possible top two elements and they use a linear time to check the longest linear time to check the longest sequence Wow let for the yeah for the sequence Wow let for the yeah for the start if the input is only two elements start if the input is only two elements we can just return to right or we can we can just return to right or we can just mmm I think we can just ignore just mmm I think we can just ignore ignore it ignore it mmm no because yeah yeah yeah I think mmm no because yeah yeah yeah I think we're just a filter out the special case we're just a filter out the special case if a tenth is two we turn to right so so if a tenth is two we turn to right so so now at least there will be three now at least there will be three elements okay now for the now we next elements okay now for the now we next loop through the array with a two round loop through the array with a two round to determine the top two elements top two elements so the first first a loop ends at the sediment right so smarter than one now now we can get to the top elements with AI with hij so the increment will be AJ minus AI so now we can look through the rest numbers J plus 1j smaller than 8 up then k plus plus K and how will we check we will find the next impossible and next target right we have the enemy increment we have the second element and we can calculate the right yeah after we get it we can update right yeah after we get it we can update to the next target and continue our to the next target and continue our search with one patch just to be just in search with one patch just to be just in this for loop so I'll say the next this for loop so I'll say the next target would be AJ plus increment for target would be AJ plus increment for this K if a K is next target add weaned this K if a K is next target add weaned and do we need to set the net current current longest then our with I'll just use these nests because we already have to write so current is 2 and if we find a target what we do plus a current and update it oh we forgot to define that the max okay and we need to update to the next target increment and finally we return the max so actually this is this should work cool let's submit yes we are accepted and the faster than 60% of the input let's analyze the time and space complexity a time we use of two for loop here and another for loop to check the possibilities so obviously it's in to the cube space we haven't used any extra space so it's constant so this is our solution but could we improve it we have done this a lot of times if we want to improve it we need to analyze our input analyze our naive solutions like this one is and to the cube right like we have assists to analyze this this example - first we are we get to start with two six and then we run into nine and update the max and then run into twelve right and then we got to nine there's nothing matted and then two and a six nine okay here's a problem first three six nine twelve we've already Travis two six nine right and now we have because it's actually part of the longest arithmetic sequence we now will with Travis six nine twelve again well this is a necessary check right so what if we have when we travels first first time when we go to Twitter three and six and we can we can cache the result of the check from six nine six six nine twelve which means in next time when we go to Six know of what if we get when we start three and a six we all reach however the six in an up in a traversal for it and cache the results say we have a longest string have a longest I have a longest arithmetic sequence I'll finance three with the increment of three if we have that information when we are when we are checking them this number three we will just because the stiff the difference between three and six is three so we can get the result immediately without extra this for check so so thinking backward is a little little little confusing let's just try to understand our previous solution in without rather than calculating the start point it's basically a symmetric so we can think of the problem as ending right so if we treat think this this for loop as we choose the two ending ending ending what ending positions for the the longest arithmetic sequence like the first we will get to six wow it's too sick itself and then two nine three nine well is 3/9 off and the six nine okay we're gain is six nine because we've already traverse three three six it's two with three and three plus six plus three is nine self so we can get the results right away so now we can have we have the we have the chance to catch the intermediate result right so the problem becomes what is the longest automatic sequence ending at each position the longest one absolutely will be will be be deducted with this math max so that's a side effect we don't need to care so we don't we need to we need to catch the result for each point so so the data will be like cut the data we want to cache is actually a combination of one the increment and that is to the longest currently a current longest length right cool now let's do that so the idea is cache the result for off of this this increment and the current longest then ending which ends at index right let's say if that is F so the increment my increment might might there were been a lot of these kind of combinations right this will be a map if I will be a map this will be a map if I will be a map map of what type of increment longest map of what type of increment longest death right so fi plus one will be what death right so fi plus one will be what now let's say we have all the this fi now let's say we have all the this fi for a through two three six nine now we for a through two three six nine now we have a new one fi plus one what do you have a new one fi plus one what do you what what what what it is it will be what what what what it is it will be suppose the supposed 9 is in the array suppose the supposed 9 is in the array right right so suppose line is together with this 12 so suppose line is together with this 12 there are two possibilities one there is there are two possibilities one there is nothing there is nothing ending at no nothing there is nothing ending at no prayer no previous longest arithmetic prayer no previous longest arithmetic sequence ending at nine if that's the sequence ending at nine if that's the case we can just say there is a new case we can just say there is a new possibility at the start at nine right possibility at the start at nine right so it would be it would be living so it would be it would be living criminals - and no you increment B a criminals - and no you increment B a minus a plus one - we just say new map a previous previous sequence of AI plus 1 previous previous sequence of AI plus 1 - increment - increment with a I I mean so the increment with with a I I mean so the increment with these two numbers are fixed to three so these two numbers are fixed to three so we just need to check if nine has we just need to check if nine has previous arithmetic sequence with the previous arithmetic sequence with the increment of three right so if there is increment of three right so if there is we just said we just there we just add we just said we just there we just add twelve in it if there isn't we just add twelve in it if there isn't we just add I'll add it add a to a right so if there I'll add it add a to a right so if there is it would be a I minus a I and is it would be a I minus a I and previous one so this will be for AJ F J previous one so this will be for AJ F J get AI minus plus one minus a I I mean get AI minus plus one minus a I I mean this is the increment mmm okay I'll say this is the increment mmm okay I'll say this is in cream looks rebels but you this is in cream looks rebels but you know what I mean know what I mean get this I plus one right well this is get this I plus one right well this is not as simple as it is it should be four not as simple as it is it should be four this is not I a I am sorry it should be this is not I a I am sorry it should be j j okay j j okay because each of the previous element because each of the previous element would be possible so for J and 0 would be possible so for J and 0 - I also the cut so the relation is - I also the cut so the relation is unclear let's start writing our code okay let's first though that the cache will be of course array of maps so I'll currents on the gate longest sequence map at okay use this cache and now we're gonna loop through each element you start would be four for the first one there's nothing there so we first we push the first push the first element the first element first cache will start with a six so one equals so there's only one possibility right so new map the increment would be a 1 minus a 0 then this would be too cool so the though so so the loop will start with I from to write the 1 is already set it here so I'll remove this one so according to our methodology here we will do what we will for let we will start with J from 0 and J will be J was more than that I and J plus plus and free which means for each this right and then we will check the increment right the first one okay for I forgot sorry the first one okay for I forgot sorry the first one would be the first one the first one would be the first one will be empty ray yeah new map so we will be empty ray yeah new map so we just to check check if there is previous just to check check if there is previous record record so it means cast previous equals previous ight previous map @j okay I use this first map equals this with J now if this has increment which means just a pen has add the new new element as one possibility right if you already have the increment so okay I'll create a new set for current so car and map car map is here god sure so current map I'll say set increment with previous map increment of course it's get house one right okay for all the art cases if if if there's nothing there maybe we could just add a new one right and a new top two elements for for sequence so it would be two and don't forget to update the max let max equals two here max equals math max max this oh I'll say I'll cash it let's run the code hmm oh it's not working let's debug for three six nine twelve okay we increment the first one is empty oh sure the second one is this too right we start with nine I'll here is mistake we should end at I'll here is mistake we should end at the last one right this is different the last one right this is different from previous for loop so I made a from previous for loop so I made a mistake sorry mistake sorry mmm-hmm Irish my house undefined undefined ah quote I submit well I think we are quote I submit well I think we are little we have improved improved a little we have improved improved a little yeah and cool now let's analyze little yeah and cool now let's analyze the time and space complexity as you can the time and space complexity as you can see we use a for-loop eat24 loop and the see we use a for-loop eat24 loop and the process here is actually a bunch of set process here is actually a bunch of set of map direct access right a skier said of map direct access right a skier said said so the time complexity would be said so the time complexity would be improved to and to the square space it's improved to and to the square space it's basically too complicated basically too complicated first we have n and affordab no n first we have n and affordab no n elements so the the map array will at elements so the the map array will at length n and for each one what's the length n and for each one what's the worst case I think for the worst case worst case I think for the worst case would be that we every time we add a new would be that we every time we add a new news a new wait a minute when you a new news a new wait a minute when you a new entry right so so the rest case is all entry right so so the rest case is all the elements are different and so for I the elements are different and so for I for index I their worst case is and I for index I their worst case is and I minus one entry to map I so the space minus one entry to map I so the space would be actually and space would be a would be actually and space would be a sigma some okay so actually 0 plus 1 sigma some okay so actually 0 plus 1 plus 2 plus the data so it's au and plus 2 plus the data so it's au and square so we've square so we've actually trait have a trade-off here we actually trait have a trade-off here we use extra end Squarespace for for the use extra end Squarespace for for the improvement from and cube to the N improvement from and cube to the N square so that's a that is our solution square so that's a that is our solution to solutions hope it helps to solutions hope it helps see you next time bye bye
2024-03-25 15:14:49
1,027
https://i.ytimg.com/vi/7…axresdefault.jpg
LeetCode 1027. Longest Arithmetic Sequence(DP) | JSer - JavaScript & Algorithm
4S5x4SF4fsM
welcome to march's leeco challenge today's problem is coin change you are today's problem is coin change you are given coins of different denominations given coins of different denominations and the total amount and the total amount write a function to compute the fewest write a function to compute the fewest number of coins that you need to make up number of coins that you need to make up that amount that amount if that amount cannot be made up return if that amount cannot be made up return negative one you may assume you have an negative one you may assume you have an infinite number of each kind of coin so infinite number of each kind of coin so if we had if we had coins one two five we would coins one two five we would return three because two five coins and return three because two five coins and one one coin one one coin would be the least amount of coins to would be the least amount of coins to get eleven get eleven now on the surface this looks like a now on the surface this looks like a very simple problem very simple problem um in the beginning we might think like um in the beginning we might think like we could just we could just sort our coin denominations and then do sort our coin denominations and then do a while loop a while loop subtracting the largest denomination subtracting the largest denomination first first and then trying to see if we can get the and then trying to see if we can get the amount here so here we'd get amount here so here we'd get one five coin two five coins so now we one five coin two five coins so now we have one left and we move here we move have one left and we move here we move here and we have one coin so that'd be here and we have one coin so that'd be three coins right three coins right but that wouldn't work because of but that wouldn't work because of certain situations like this where we certain situations like this where we have have let's say one four five if we had eight let's say one four five if we had eight coins if that algorithm coins if that algorithm would be the same we would take five would be the same we would take five here and then we take three one coins here and then we take three one coins which would equal four which would equal four but we know that we can do four twos and but we know that we can do four twos and that would be that would be two coins that should be the minimum so two coins that should be the minimum so we need to keep track we need to keep track of um the number of of um the number of coins that we can make at each point so coins that we can make at each point so really really that solution won't work we'd have to go that solution won't work we'd have to go with something with something um either recursive or dp and i'm going um either recursive or dp and i'm going to go with a dp solution to go with a dp solution what we'll do is create this into sub what we'll do is create this into sub problems and problems and have some sort of dp array that contains have some sort of dp array that contains the numbers all the way up to 8. the numbers all the way up to 8. what we'll do is just have some infinite what we'll do is just have some infinite max number here max number here i'm just going to call that let's i'm just going to call that let's let's say let's say negative one but let's say let's say negative one but assume that this is assume that this is infinite and what we'll do is um see we keep track of the index points so this is uh zero amount one two three four five six seven eight something like that and basically we'll check for each coin denomination how many coins would it take to fulfill how many coins would it take to fulfill that amount that amount so here we'll start with uh one coin so here we'll start with uh one coin or i'm sorry we'll start with the amount or i'm sorry we'll start with the amount zero we know that there there's no zero we know that there there's no amount of coins that we can make to make amount of coins that we can make to make you know you know um zero amount so this would just be um zero amount so this would just be zero immediately now we have the amount zero immediately now we have the amount one right one right so out of these three coins we run a for so out of these three coins we run a for loop if we use one loop if we use one then we could create it with one coin then we could create it with one coin right what about four right what about four we can't we can't deal with five either we can't we can't deal with five either so this would all be the same up to like so this would all be the same up to like two two three four something like this but once three four something like this but once we reach we reach four uh we know that we could have four four uh we know that we could have four ones but we ones but we should also check one four and we know should also check one four and we know that that's gonna be the minimums that that's gonna be the minimums so that can be changed to like one four so that can be changed to like one four coin five wouldn't be work coin five wouldn't be work now what about at five here now what about at five here we'll check we'll check to first see five ones that don't work to first see five ones that don't work okay so five ones we'll update that okay so five ones we'll update that now what about four well we obviously now what about four well we obviously can't make five with four can't make five with four but we could make um but we could make um we know that we could add one four here we know that we could add one four here and then go back and then go back four spaces to one see how many coins four spaces to one see how many coins that it took to make one that's going to that it took to make one that's going to be the minimum here and add that be the minimum here and add that so we know at five we can have one four so we know at five we can have one four coin and use one one coin here coin and use one one coin here and that would equal two right so that and that would equal two right so that gets updated to two gets updated to two and that's uh the algorithm how that and that's uh the algorithm how that algorithm works we like look backwards algorithm works we like look backwards to see the minimum amount to see the minimum amount that we can make minus that coin amount that we can make minus that coin amount and see if that's minimum and see if that's minimum if we if it is we're going to update it if we if it is we're going to update it so hopefully that sort of made sense so hopefully that sort of made sense what we'll do is create a dp array here what we'll do is create a dp array here i'm going to start with making these all i'm going to start with making these all infinite values infinite values because we want to get the max value because we want to get the max value and we'll say 4i or whatever four blank and we'll say 4i or whatever four blank in range of in range of length of amount we'll also need to add length of amount we'll also need to add one here one here okay so we have a steep array we need to okay so we have a steep array we need to make the very first make the very first value zero so we'll do that here value zero so we'll do that here now for let's see for i in range of length of dp we are going to run through all our coins so for c in coins if this i minus c is greater or equal to zero that means we're in bounds so we could subtract the coin amount from our value here we're going to update our i to be the minimum between ppi or dp i minus c and then add one which is the coin value right now that we're at so if this is less then we're going to update it otherwise uh we'll keep the old one so at the very end we should have our dp amount for this number that we're trying to get the amount which would be the very last index in our dp already now one thing to note we want to return negative one if it's an infinite right because that means that we weren't able to form that amount uh if i made this negative one here it wouldn't work with this algorithm so what i have to do is say [Applause] if dp i minus 1 is equal to float infinite then we'll return negative one else we'll just return the amount right there objects has no length here objects has no length here oh okay i don't need length here i just oh okay i don't need length here i just get the range of amounts get the range of amounts plus one i think all right so that looks like it's and accept it so time complexity wise and accept it so time complexity wise it's going to be of n it's going to be of n which is um the number amount here which is um the number amount here times the number of coins so let's say times the number of coins so let's say that's c c times n that's c c times n now i did see that there were some now i did see that there were some recursive solutions that did the exact recursive solutions that did the exact same thing but were way faster when we same thing but were way faster when we run an elite code run an elite code i'm not entirely sure why that is i'm not entirely sure why that is because time complexity wise because time complexity wise should be the same it could be that should be the same it could be that forming this array here takes a while forming this array here takes a while especially if the amount is large especially if the amount is large i'm not entirely sure so feel free to i'm not entirely sure so feel free to put that in the comments if you know why put that in the comments if you know why but otherwise this is the um sort of but otherwise this is the um sort of accepted solution for this problem it's accepted solution for this problem it's a very classic one a very classic one all right thanks for watching my channel all right thanks for watching my channel and remember do not trust me i know and remember do not trust me i know nothing
2024-03-24 10:27:47
322
https://i.ytimg.com/vi/4…sM/sddefault.jpg
Leetcode - Coin Change (Python)
rj7qcxzdpA4
hello hi guys good morning welcome back to the new video and for sure if you to the new video and for sure if you have salt or if you have watched our have salt or if you have watched our live contest stream which we do every live contest stream which we do every week if you have watched it for the past week if you have watched it for the past one month then for sure try this one month then for sure try this question but I also because you should question but I also because you should be able to do it because I have told you be able to do it because I have told you this exact same question like kind of this exact same question like kind of same question in the live stream for same question in the live stream for sure do it try it by yourself but now sure do it try it by yourself but now unless I will pronounce it with her unless I will pronounce it with her asteroid Collision it's a very very asteroid Collision it's a very very standard problems like Collision kind of standard problems like Collision kind of problems are kind of standard they just problems are kind of standard they just have three four variants two variants we have three four variants two variants we have already told in our live streams it have already told in our live streams it is same one such one of the one of those is same one such one of the one of those two variants which you are seeing right two variants which you are seeing right now cool now cool um we are having an array of asteroids um we are having an array of asteroids of integers representing of integers representing representing uh asteroids in a row uh representing uh asteroids in a row uh for each asteroids the absolute value for each asteroids the absolute value represents its size and the sign so represents its size and the sign so basically we have an array of asteroids basically we have an array of asteroids right so every asteroid has some value right so every asteroid has some value let's say minus 40 or 40 let's say minus 40 or 40 um or let's say 15. so 15 will represent um or let's say 15. so 15 will represent the size 40 will represent the size and the size 40 will represent the size and minus will represent the direction minus minus will represent the direction minus will say left and plus we'll say right will say left and plus we'll say right cool cool now uh find out the stays of the assets now uh find out the stays of the assets which means asteroids are just moving it which means asteroids are just moving it is just the moving States now we have to is just the moving States now we have to tell tell after all the after all the collisions after all the after all the collisions are done and see the position will are done and see the position will happen between two asteroids so two F2 happen between two asteroids so two F2 asteroids meet and for sure when these asteroids meet and for sure when these two will meet then only the Collision two will meet then only the Collision will happen so when the two asteroids will happen so when the two asteroids will meet force or the smaller one will will meet force or the smaller one will be explode and if both of are of same be explode and if both of are of same size then both will explode cool now size then both will explode cool now just that okay we have to know the state just that okay we have to know the state after all the collisions which means after all the collisions which means after my all after my all asteroids meet with each other so for asteroids meet with each other so for short I I know is ultimately if the short I I know is ultimately if the asteroids will collide then for sure asteroids will collide then for sure they have to meet if they have to meet they have to meet if they have to meet then for sure some condition will be then for sure some condition will be there so I'll just see okay what all there so I'll just see okay what all asteroids will not meet and whatever asteroids will not meet and whatever asteroids will meet cool uh so if two asteroids will meet cool uh so if two asteroids meet what I will do is I will asteroids meet what I will do is I will make all the cases of when the two make all the cases of when the two asteroids can meet for sure the examples asteroids can meet for sure the examples can help you but yeah we quickly jump can help you but yeah we quickly jump onto the logic because we know we have onto the logic because we know we have to just make the two asteroids meet and to just make the two asteroids meet and ultimately if if some asteroids it ultimately if if some asteroids it remains ultimately after even after remains ultimately after even after meeting then for sure it will be in my meeting then for sure it will be in my final answer after collisions and if it final answer after collisions and if it just gets finished then for sure it just gets finished then for sure it won't be in our answer after Collision won't be in our answer after Collision now what I can do is I can start off now what I can do is I can start off very easily so in the starting itself I very easily so in the starting itself I have let's say any asteroids moving have let's say any asteroids moving right or moving left if some asteroid is right or moving left if some asteroid is moving left then for sure it will keep moving left then for sure it will keep on moving left and no way it will gonna on moving left and no way it will gonna be Collide and ever with anyone because be Collide and ever with anyone because for sure it's it's moving left left left for sure it's it's moving left left left right so in the starting in the starting right so in the starting in the starting of and for sure now you will see okay of and for sure now you will see okay Arena starting when I know that I have Arena starting when I know that I have to take this so in what data structure to take this so in what data structure shall I take I know I have to return a shall I take I know I have to return a vector but should I take a vector or for vector but should I take a vector or for doing the operations so one thing you doing the operations so one thing you know for sure that as you are pushing an know for sure that as you are pushing an element every time you encounter an element so basically you will be pushing this element in a data structure for the for example this element when you will get the you know okay it's never gonna have a collusion so for sure you will push this element in some data structure what that title structure can be we have to see and also when we know when someone who is coming left and for sure in between let's say someone was coming right so we know one thing also for sure that we need to pop one of these because it is right it is left so one will pop out so for sure we know that a few elements we will push in a few elements will pop out so maybe at the run time itself I should be able to push and pop the elements who are remaining let's say for example right if this is if this if this was bigger and this was small so for sure it it will collide and for sure it will remain so for sure uh one needs to pop so by this itself I can know maybe I can use a stack or something like that okay from the end I can remove an element I can push an element from the end it can be the stack either it can be a DQ it can be a vector or any data structure you want let's take it as a stack itself and for sure if it was the first time of you solving it that season I told you about the intuition of stock but going forward please have at the back of your mind saying that the Collision problems can either be straightforward or via stock start is 90 of the times used in cooling out of problems cool now coming back to the first case if it is at the very starting and if it is moving left it will keep on moving left so for sure we don't need to do anything if it is empty and if it is negative then just push that in the move start and push that element and when this is it is the asteroid of I push that in your stack but if it is positive and for sure if it is moving in the starting now you will say again if it is positive then for sure it can have a collision yeah it can have but provided if later point of time someone is coming left right now it can't have collision by just a straightforward scene it can't have Collision so for sure I will assume that whosoever is moving right will not have Collision but whosoever will move left later on will actually can impact Collision so for these moving right I'll just say okay uh it won't cause Collision so for sure if it is empty so now we saw if it is empty either if it is a positive or negative just push that in your stack okay one case done now other case for us was to know okay if it was moving just right now for sure if it is moving right we know it won't cause Collision because it is moving right so for sure if it is positive then please itself it wasn't starting when it is empty so we know we can push both of them either possible negative but yeah we also saw okay if it is positive even and we know the positive ones won't cause cause Collision because we ultimately thought the negative ones on positive will cause solution so we just assumed okay because one will cause a question on the other so here we assume the positive ones will not Constitution and the negative ones coming forward will cause Collision you can also do vice versa and make your cases a bit more efficient by that but they are simple now ultimately what will happen is maybe the negative one come now you know one thing we took one case starting case we took okay it is positive we do okay now it is negative if it is a negative it can cause correlation but but let's say if it is negative which was coming in Left Right it has some value if the values which is the the one which is coming in left is Big the one which was actually in the left so the one which is coming left it is this element it is Big the one which we have already in the left it is small then for sure big one will collide with a smaller one and the smaller one will get removed and you know everything which means everything which is in the left is actually in the stack itself already so for sure as the big one is coming in it he knows that he will collide with the smaller one and smaller is going to finish so what will happen is I will just say okay if my stack the top which means anything which is in the stack itself if it is positive which means it is moving right and also if it is less which is smaller in size then for sure it's gonna be removed so I just simply remove it but this process will keep on going until I have smaller elements and also the elements moving right in the stack itself so I will just simply apply a while loop on this okay smaller elements moving right keep on removing it until you have the condition that okay they are smaller in size with the one which is coming in left for you it is coming in left and for sure you know one thing the values of this particular is actually negative so please make sure that you take the absolute value off here so you will write absolute of asteroid of I because ultimately I am concerned I know okay it is a negative one which is coming in by the direction but now I'm concerned about the sizes so please take the absolute value now coming okay and now we saw okay if both of them had if the one coming in left had the bigger size and the one which was uh in the start which means it was coming in the right has a smaller size but what if they both have same size now if they both have same size based on the question both will get collided so the while loop will not come in picture if they both have same size because if both have same size for sure both will get collided so no one will be there to actually make Collision for the remaining part of the start right so if both have the same size if both and again here it will be absolute if both are the same size please simply pop it and simply stop it so it will not be a while loop it will just simply be if if if Loop now what if this coming left has a smaller size if you're a smaller size and if it is bigger size and if you already know that it is already in the stack if it is a bigger size it's a smaller size then simply simply you just remove this which means it was incoming in it was the asteroid of I you just removed it and it is already it was already in the stack it will still remain in the stack cool no worries so nothing you have to do as such or you can simply pop it and push it again but still no worries no effect as such on this particular element of the stack but lastly let's say if it was going in going and going in in the first case as you going in and what if it completely exhausted all the elements of Stack which means ultimately what if the stack becomes empty again it came back to the first case that okay if the stack becomes empty and if the element is coming in as left simply push that element so for sure if it is coming in s as if and the stack is empty simply push that element but what if the next element although we saw here the element which was the next to him which means it if asteroid was I was the incoming element and the element in the top of the stack was actually a element moving right so we just did the Collision but if the element at the top of the stack was actually element moving left itself so for sure it will keep on going left so ultimately no Collision so please again push this asteroid of I if the elements in top of the stack are actually moving left so if the stack top is actually negative which means stack top is actually moving left so please simply push this element because it's also a negative element which is it's also a element moving left simply push that element and by this you can simply make out the cases of when the Collision will happen and when it it will not and how the Collision will affect the existing stack top and that's only simply the case you have to solve in general in this kind of problems quickly see the code uh firstly we'll simply go on to entire Vector from left to right right uh simply as we go on we will simply say as we saw if it is empty even if it is moving left or right simply push it or if it is moving right then simply push it so if it is empty or if it is simply moving left or right oh sorry if it is empty or if it is actually positive element simply push that in the stack now comes the part where actually this element is coming in as F which means the asteroid of I is actually a negative element for sure we know I will keep on removing from the stack provided the element at the top of Stack is actually moving right and also its value is smaller than actually the incoming element it's moving left so if it is the case I will simply remove Elements by while loop but but if they both have same size so if they both have same size then I'll simply do a if conditions and remove the stack like I simply remove the element of the of the above the stack which means standard pop but if I still have the element which is negative coming in and stack is empty simply I'll just simply push it or if the stack top is already a negative which means moving left then also simply push it because I can't simply pop anything out so in this case I simply pushed it down now we have all the elements at the top of the stack right because here we are moving from left to right left to right we are moving and we have portion the top of the stack now as we will pop it out which means as you will get the final elements after Collision remaining so what we will get is in the vector as from right to left right because it is the first last and first out so I'll just simply push in the elements like this but simply I again want in the same order from left to right so I'll simply have to reverse it down or maybe what I can do is I can simply push these elements which means the stack top I can push it at the last and then it is the second lesson so on and so forth anyways you can do so here we just have all these stack elements posted in this kind of order last element at the last location this element at the last location this element at the last location by this moving at the from the last index onwards and by this simply getting the elements which are actually meaning after collision and simply return that in the better and the form of result you can simply use the vector also a DQ also and stack for sure but stack is more intuitive to actually solve it pop a top uh push that kind of concept right time and space both o of n because for sure you are using a stack stack space stack time simple linear stuff going on that see that's that's actually very standard see that's that's actually very standard so please remember that this that kind so please remember that this that kind of thing is used and we have gone of thing is used and we have gone through Wireless stuff you actually through Wireless stuff you actually started doing things
2024-03-21 11:51:31
735
https://i.ytimg.com/vi_w…xresdefault.webp
Asteroid Collision II Collision Problems II Stacks II Vector II Leetcode 735
hQU1gYzY-Ug
hey guys welcome back to the channel so this channel everyday data science is this channel everyday data science is all about trying to learn the various all about trying to learn the various concepts involving data science by concepts involving data science by practicing a lot of questions in this practicing a lot of questions in this video i am going to solve this question video i am going to solve this question on lead code regarding employees with on lead code regarding employees with missing information and try to walk you missing information and try to walk you through how we can develop solutions to through how we can develop solutions to such problems okay so let's jump right such problems okay so let's jump right in we are given a table called employees in we are given a table called employees with two different columns employee id with two different columns employee id and the name and these are their data and the name and these are their data types types employee id is the primary key so no employee id is the primary key so no null unique values each row of this null unique values each row of this table indicates the name of the employee table indicates the name of the employee whose id is employee id so basically whose id is employee id so basically employee id and the name of the employee employee id and the name of the employee we are also given another table called we are also given another table called salaries with again two columns employee salaries with again two columns employee id and their salary and here also id and their salary and here also employee id is the primary key for this employee id is the primary key for this table so non-null unique values table so non-null unique values and this table in basically represents and this table in basically represents the employee id and their salary we are the employee id and their salary we are asked to write a sql query to report the asked to write a sql query to report the ids of all the employees with missing ids of all the employees with missing information and how do how do they are information and how do how do they are defining the missing information defining the missing information either the name is missing or the salary either the name is missing or the salary is missing and the final result should is missing and the final result should be ordered by employee id in ascending be ordered by employee id in ascending order okay so let's go through this order okay so let's go through this example right so here we are given the example right so here we are given the employees table and salaries table with employees table and salaries table with three different data points three different data points in each of these tables so employee id in each of these tables so employee id two four five these are the names of the two four five these are the names of the employees and these are their salaries employees and these are their salaries and obviously we are to output the ids and obviously we are to output the ids of such employees where either the name of such employees where either the name is missing or the salary is missing is missing or the salary is missing right so uh here if we see for employee right so uh here if we see for employee id 2 uh the name is present id 2 uh the name is present uh but there is no salary right so uh but there is no salary right so uh salary is missing so employee id 2 uh salary is missing so employee id 2 should be there should be there for employee id 4 the name is there the for employee id 4 the name is there the salary is also there so 4 won't be salary is also there so 4 won't be included for employee id 5 name salary included for employee id 5 name salary both are present both are present and the the fourth should be since 4 and and the the fourth should be since 4 and 5 are here 2 is 5 are here 2 is not in this table so we also need to not in this table so we also need to look at look at which employee id does not have a name which employee id does not have a name but is in the salaries table so if you but is in the salaries table so if you see employee id one is in the salaries see employee id one is in the salaries table so it has salary but there is no table so it has salary but there is no name right so basically one and two name right so basically one and two should be the output right and this is should be the output right and this is what we get what we get okay so one thing that okay so one thing that right away can come to your mind and if right away can come to your mind and if you don't read the question carefully it you don't read the question carefully it will lead to the problem right so one will lead to the problem right so one thing uh a person can think of here is thing uh a person can think of here is oh so if we do a join here right so if oh so if we do a join here right so if we do a join of employees on salaries we do a join of employees on salaries uh and see whether whether the salary uh and see whether whether the salary column is null column is null uh then we can you know arrived at the uh then we can you know arrived at the destination right but see if you do a destination right but see if you do a left join of employees table left join of employees table on salaries or you do a left join of on salaries or you do a left join of salaries on employees table in both the salaries on employees table in both the cases you won't be able to get the cases you won't be able to get the entire list of employee ids where either entire list of employee ids where either the name is missing or the salary is the name is missing or the salary is missing let me just show you right so if missing let me just show you right so if you just let's do a left join of you just let's do a left join of employees on salaries so how the join employees on salaries so how the join works so firstly uh we will uh and we works so firstly uh we will uh and we are joining on employee id column right are joining on employee id column right so here the cursor will start with the so here the cursor will start with the first row right so employee id 2 it will first row right so employee id 2 it will see here oh there is nothing so in the see here oh there is nothing so in the salary column it would be null salary column it would be null for 4 for 4 the the salary will be populated sixty the the salary will be populated sixty three thousand five thirty nine for five three thousand five thirty nine for five um um name and salary is going to be seventy name and salary is going to be seventy six thousand zero seven one right since six thousand zero seven one right since a left join keeps all the rows on the a left join keeps all the rows on the left side of the keyword left so only left side of the keyword left so only three rows will be present where three rows will be present where for the first row the salary would be for the first row the salary would be null because there is no employee id 2 null because there is no employee id 2 in the salaries table and rest 2 will in the salaries table and rest 2 will have salaries column so if you return have salaries column so if you return the employee id in that case you are the employee id in that case you are only going to get two but ideally your only going to get two but ideally your answer should be one and two similarly answer should be one and two similarly if you do the opposite if you do the opposite that if you left join salaries on that if you left join salaries on employees again for five it will find a employees again for five it will find a match so the name will be question here match so the name will be question here for one it won't find anything so name for one it won't find anything so name would be null for would be null for for employee id for it will find a match for employee id for it will find a match and the name will be haven so here also and the name will be haven so here also if you return the employee id uh where if you return the employee id uh where the name was null it would be only one right but if you think about it what i just described as two separate things so basically doing a left join of employees on salaries and vice versa if we combine both and union the result then we can get the answer right so because if you when we did a left join of employees on salaries what we re what we got to when we returned where salary was null right and when we did a left join of salaries on employees and did where name is null we got employee id one so the answer is basically one and two right so we can get the answer okay so let's do this so let's first do a left join of employees so basically from the table employees aliased as e do a left join on salaries table aliased as s on which column e dot employee id is equal to s dot employee id and after doing this we are only going to keep which rows because when we do a left join so these this entire these two columns with the data is going to be present right when we are doing a left join two new columns will be added employee id from the salaries table and the salary from the salaries table right so when we are doing a left join what do we need to do here since we only need to keep where the information is missing so in this case we are only going to keep such rows where the salary is null so salary is null basically means salary information is missing so s dot because salary column is in the s dot because salary column is in the salaries table right so s dot salary salaries table right so s dot salary is is null null and what do we do and what do we do we return the we return the employee id and we are going to return employee id and we are going to return the employee id column from the the employee id column from the employees table so e dot employees table so e dot employee employee id id right right so here from this what we are going to so here from this what we are going to get get 2 2 because for 4 and 5 there is going to be because for 4 and 5 there is going to be a match and the salary is not going to a match and the salary is not going to be nil right be nil right and we do the same thing but in a and we do the same thing but in a reverse manner reverse manner so what we can do is select or basically so what we can do is select or basically from from the salaries table aliased as s the salaries table aliased as s left to join left to join employees table aliased as e employees table aliased as e again on again on s dot employee s dot employee id id is equal to e is equal to e dot dot employee employee id id and here we are only keeping such rows and here we are only keeping such rows where since we are where since we are left joining salaries table on employees left joining salaries table on employees table so this entire thing is going to table so this entire thing is going to remain as it is but two new columns will remain as it is but two new columns will be added employee id and name from the be added employee id and name from the employees table and when we don't find a employees table and when we don't find a match then the null values will be in match then the null values will be in the employee id and name columns from the employee id and name columns from the employees table so where the employees table so where e e dot name dot name is null is null right right and what do we return and what do we return we return the employee id column from we return the employee id column from the salaries table so returns s dot the salaries table so returns s dot employee employee id id so from this we got 2 so from this we got 2 from this from this we got 1 we got 1 and at the end what do we do we just do and at the end what do we do we just do a union a union so so union union let's go ahead and run this let's go ahead and run this uh okay before going ahead and running uh okay before going ahead and running this this see one last thing we need to do is see one last thing we need to do is the order of the result should be in the order of the result should be in employee id in ascending order right employee id in ascending order right okay so we okay so we order order by by employee employee id id okay so let's go ahead and run this and okay so let's go ahead and run this and see what happens so yeah this is see what happens so yeah this is accepted our output is same as expected accepted our output is same as expected output let me go ahead and submit it and output let me go ahead and submit it and see if this passes all the test cases so see if this passes all the test cases so yeah this passes all the test cases and yeah this passes all the test cases and this is how we solve this problem this is how we solve this problem there is another way to do it there is another way to do it it was so what you can do is you can use it was so what you can do is you can use common table expressions or basically common table expressions or basically temporary tables to do this in another temporary tables to do this in another way right so what you can do is from way right so what you can do is from these two tables you can these two tables you can get all the employee ids basically from get all the employee ids basically from these tables store it in a temporary these tables store it in a temporary position or store it in a temporary position or store it in a temporary table common table expression does not table common table expression does not matter matter and then and then once we have that then we can perform a once we have that then we can perform a double left join so basically what i'm double left join so basically what i'm saying saying is so let's say for this right so we i is so let's say for this right so we i create a common table expression which create a common table expression which returns me all the employee ids from returns me all the employee ids from both these tables so basically two four both these tables so basically two four five and one right so five and one right so two two four four five and one right so now what i can do five and one right so now what i can do is so this is a common table expression is so this is a common table expression or a temporary table and now i can or a temporary table and now i can perform a double left joint so what i do perform a double left joint so what i do is i is i do a left join of this on employees do a left join of this on employees table table so whatever what it will do so whatever what it will do so two so two it will find it will uh it will find it will uh make a you know populate the name column make a you know populate the name column as crew 4 5 it will populate but for one as crew 4 5 it will populate but for one it will be null right so what will it will be null right so what will happen so here it will be crew happen so here it will be crew here it would be heaven here it would be heaven here it would be christian here it would be christian in the name column and here it would be in the name column and here it would be null right and then what i do is v i null right and then what i do is v i do another left join of this thing on do another left join of this thing on the salaries table right so what will the salaries table right so what will happen happen is is for uh employee id 2 right so for since for uh employee id 2 right so for since 2 is not in the salaries table so 2 is not in the salaries table so here the salaries column would be null here the salaries column would be null for four for four salary would be sixty three five three salary would be sixty three five three nine nine five three nine for five three nine for employee id five the salary would be employee id five the salary would be seventy six zero seventy six zero seven one seven one seventy 6 0 7 1 and for seventy 6 0 7 1 and for employee id 1 it is going to be 20 22 employee id 1 it is going to be 20 22 517 right so 22 5 1 7 and now when i do 517 right so 22 5 1 7 and now when i do only keep those records where either the only keep those records where either the name was null or name was null or the the salary was null right so it will remove salary was null right so it will remove both of these rows because here we have both of these rows because here we have both the name and the salary so no both the name and the salary so no information is missing so from this now information is missing so from this now i can return the employee ids i can return the employee ids and order in the ascending way right so and order in the ascending way right so this is again another way to do it right this is again another way to do it right so if you don't want to uh so if you don't want to uh go by this basically doing a thing and a go by this basically doing a thing and a vice versa you can vice versa you can you know employ this method but again it you know employ this method but again it is in both the cases we are using joins is in both the cases we are using joins so more or less uh the runtime would be so more or less uh the runtime would be similar similar uh and whatever suits you or whatever uh and whatever suits you or whatever seems more logical to you you can adopt seems more logical to you you can adopt that right and let me know also here i that right and let me know also here i just demonstrated the logic let me know just demonstrated the logic let me know what the actual code will look like for what the actual code will look like for this second method right in the comment this second method right in the comment section section okay okay uh uh hopefully this video made sense and hopefully this video made sense and hopefully it was helpful to you hopefully it was helpful to you uh let me know in the comment section if uh let me know in the comment section if it was and until then i will see you it was and until then i will see you guys in the next video
2024-03-25 13:25:55
1,965
https://i.ytimg.com/vi/h…axresdefault.jpg
LeetCode 1965 Interview SQL Question with Detailed Explanation | Practice SQL
RHDLFs11tCk
what's up guys this is my two first video video we gonna solve the famous problem the we gonna solve the famous problem the first missing positive first missing positive it's usually asked by the top tech it's usually asked by the top tech company like amazon company like amazon okay so let's move to the description okay so let's move to the description okay so given an inserted integer array okay so given an inserted integer array nums nums uh find the smallest missing positive uh find the smallest missing positive integer integer so let's take some examples the first so let's take some examples the first example we have example we have this array of one two and zero and the this array of one two and zero and the first missing positive integer is three first missing positive integer is three move on to a second example in this case move on to a second example in this case the the uh the first missing positive integer is uh the first missing positive integer is one one okay so let's think how can okay so let's think how can we solve this problem we solve this problem okay one important thing to notice is okay one important thing to notice is like we have at most n elements like we have at most n elements it's the length of the array so it's the length of the array so the result will be between one and n the result will be between one and n plus one plus one as the n is the length of the array as the n is the length of the array so uh for this first example uh so uh for this first example uh the first missing positive integer is the first missing positive integer is one one and one is between one and n plus one and one is between one and n plus one in this case we have uh four elements so in this case we have uh four elements so n is equal to four n is equal to four uh n plus one is equal to five so the uh n plus one is equal to five so the result 5 is between 1 and result 5 is between 1 and n plus 1 5 in this case okay n plus 1 5 in this case okay move on now to a brute force solution move on now to a brute force solution a brute force solution would be a brute force solution would be like if we use two nested loops and try like if we use two nested loops and try to to figure out the first missing positive figure out the first missing positive integer integer to the array so like to the array so like it's important to remember that the it's important to remember that the result is between result is between one and and plus one so we will use two one and and plus one so we will use two nested loops the first loop will uh nested loops the first loop will uh loop between one and n plus one and for loop between one and n plus one and for each possible result we will check if each possible result we will check if this possible result exists in the array this possible result exists in the array or not so if or not so if this elements is equal to the possible this elements is equal to the possible result so we will return it result so we will return it else we will return n plus 1. else we will return n plus 1. and this solution is a big o of n square and this solution is a big o of n square of of time complexity but let's think time complexity but let's think about a better solution on how can we about a better solution on how can we reduce the time complexity to reduce the time complexity to big o of n of time complexity but this big o of n of time complexity but this better solution it will be a big o of n better solution it will be a big o of n of space complexity okay of space complexity okay the idea is to use data structure to the idea is to use data structure to save the different save the different elements so like instead of like elements so like instead of like looping through the different elements looping through the different elements and in and in each case test it like we we are going each case test it like we we are going to to save the different elements that exist save the different elements that exist in the array into a data structure in the array into a data structure and test on them and test on them so the idea is to use a set so the idea is to use a set okay so if we have this array one one okay so if we have this array one one three the set will be one three the set will be one three and the first missing uh number is three and the first missing uh number is two two okay this is uh okay this is uh the pseudo code of this solution so we the pseudo code of this solution so we will will loop through the different elements of loop through the different elements of the array and add them to the set the array and add them to the set and the second we're going to loop and the second we're going to loop through the different possible results through the different possible results and tests and tests if this results exists if this results exists in the set or not if yes in the set or not if yes we may need to return it if not we may need to return it if not we will return n plus one since the we will return n plus one since the result result is between n and n plus one but is between n and n plus one but let's optimize try to optimize our let's optimize try to optimize our solution solution okay i came up with this okay i came up with this solution how can we achieve this solution how can we achieve this the idea is to mimic the set the idea is to mimic the set functionality okay but how functionality okay but how we are using the array and an important we are using the array and an important thing to remember thing to remember another time is that the result is another time is that the result is between one and between one and and plus one so and uh and plus one so and uh it's important to remember also that we it's important to remember also that we can can access any element of the array access any element of the array within a constant time so how can we use the these two points to solve our problem to achieve a big o of one of space complexity the idea is to use the positions within the array since the result is at most between one and n plus one and like if we have like any possible number we will like tag the position of the value of the elements the array and to the negative value so for this first example we have one one and three we will go go through the different elements we have one so we will go to the element of index one and we'll we will assign the negative version of it okay so one one second we will go we will move forward this is the second element so we will assign again the negative version of this position so it's also minus one and finally uh we we can move forward so three so we will assign the negative version of the element at the third position of the array minus three and finally we just need to loop through this array and to return the first the position of the first positive element the first positive element in the array is at the position two so that's the result in this case but we have some pre-processing parts that we need to verify so we may need to like be sure that the elements or the elements are between like one and and the length of the array else we may need to solve this problem using some other solution okay so we may need to like test if one exists or not if yes so we will pass else will return one since it's the two first positive integer and we will loop through the different elements if the element is equal or less to zero we will assign the value of one instead and if the element is bigger than n also we may need to assign the value 1 to it okay so this result we will find that 50 is bigger than 3 the length of the array and -5 is less than 0 and -5 is less than 0 so we will assign one to and finally if so we will assign one to and finally if we will we will execute the same algorithm execute the same algorithm to this array we will find that 2 is the to this array we will find that 2 is the first missing integer and exactly that's first missing integer and exactly that's the case the case okay let's move to the implementation okay let's move to the implementation so we may need this to solve it okay so we may need this to solve it okay this is an online python compiler okay this is an online python compiler okay so let's create our so let's create our solution class let's create a our function the famous first missing that needs an array that needs an array let's parameter okay the first thing let's parameter okay the first thing that we may need to do is to that we may need to do is to get the length of the array to a get the length of the array to a separate separate variable on the test and to variable on the test and to test and to test if one test and to test if one exists or not and to test if exists or not and to test if we have an empty array okay we have an empty array okay so if not so if not nouns we will return one okay the second thing to do is like to to like change or elements uh less or equal to zero or bigger than n to 1 okay so we may need to loop through the okay and to test if okay and to test if the element or the elements or the elements we can so less or equal we can so less or equal the element is bigger than the element is bigger than n so we may need to assign and then after doing this and then after doing this we will move to the we will move to the main part through the different elements again so let's get the absolute value of so let's get the absolute value of this the element absolute value okay like one or two absolute value okay like one or two and then we need to to assign the negative version of the value at the position because like of the shift of because like of the shift of the indexes i might need to assign the negative and finally we just need to and finally we just need to find the first positive find the first positive element and to return its position element and to return its position okay so finally we may need to and test if the element and test if the element is greater than zero is greater than zero so we may need to return so we may need to return its position we may need to add one its position we may need to add one because of this shift else if like uh we didn't find the possession plus one sense the result as equal to plus one sense the result as equal to at most n plus one okay at most n plus one okay let's execute this by creating a new let's execute this by creating a new instance instance of the solution to use some relevant examples okay let's test okay let's test another example an empty array members okay all right with capital s okay okay great so for the first example the two first missing positive number is two like we have one so the first element is two for an empty array so uh the two first element as one for this example with the negative elements or elements bigger than the length of the array for in this case we will have three on the first element that's correct so thank you for watching
2024-03-20 09:14:32
41
https://i.ytimg.com/vi/R…axresdefault.jpg
First Missing Positive | LeetCode 41 (Hard) | FAANG | O(n) Solution | 100CodingChallenge ( 1/100 )
GFj20l9WIh4
hello everyone so in this video we'll go over one more problem from lead code the over one more problem from lead code the problem is count servers that problem is count servers that communicate so let us go over the communicate so let us go over the problem statement directly the problem problem statement directly the problem statement goes like this that you are statement goes like this that you are given a map of a server center given a map of a server center represented as an m cross n integer represented as an m cross n integer matrix that is named as grid now where matrix that is named as grid now where one means that the cell there is a one means that the cell there is a server and zero means that there is a no server and zero means that there is a no server as you can see in the diagram so server as you can see in the diagram so there is a grid that is given to you in there is a grid that is given to you in this first example it's a one two by two this first example it's a one two by two grid and uh grid and uh one means that there's a server add here one means that there's a server add here in the first row so this is the first in the first row so this is the first row second row okay and the first row in row second row okay and the first row in the first column it is one server and the first column it is one server and the second row second column there is the second row second column there is one more server one more server fine now it is mean that two servers are fine now it is mean that two servers are set to communicate if they are set to communicate if they are like if they are on the same row or on like if they are on the same row or on the same column so two servers can only the same column so two servers can only communicate that in that way return the communicate that in that way return the number of servers that can communicate number of servers that can communicate with any other server cool so with any other server cool so just find out any server that is in a just find out any server that is in a communicating state that can communicate communicating state that can communicate to any other server it doesn't matter to any other server it doesn't matter which server but it can communicate to which server but it can communicate to any other server and if a server is that any other server and if a server is that that is isolated cannot communicate to that is isolated cannot communicate to any no other servers then you have to any no other servers then you have to neglect that now in this example as you neglect that now in this example as you can see this server cannot communicate can see this server cannot communicate to any other server like there is no to any other server like there is no one more computer on the same row or in one more computer on the same row or in the same column like same for this uh the same column like same for this uh now if you come down to this this now if you come down to this this computer can communicate to this as well computer can communicate to this as well as this company could communicate to as this company could communicate to this and this communicate computer can this and this communicate computer can communicate to this communicate to this similarly for this this server can similarly for this this server can communicate to this and vice versa this communicate to this and vice versa this will communicate to this vice versa but will communicate to this vice versa but this cannot communicate to anyone and this cannot communicate to anyone and thus it is left out so total number is thus it is left out so total number is the number you have to print out is how the number you have to print out is how many servers can communicate okay so as many servers can communicate okay so as you can see that is four now what you you can see that is four now what you can do here is that in this grid that is can do here is that in this grid that is m cross n grid you have to output that m cross n grid you have to output that how many servers can communicate you can how many servers can communicate you can pause of this video try to think over of pause of this video try to think over of your own how you can do about for this your own how you can do about for this problem it's not too much difficult you problem it's not too much difficult you can directly see that can directly see that the main intuition for this problem is the main intuition for this problem is that you have to see whether there are that you have to see whether there are more than some computer on the same row more than some computer on the same row so you have to find out for like how so you have to find out for like how many computers are there in the same row many computers are there in the same row and save column can you think over that and save column can you think over that in that direction first you have to in that direction first you have to easily find out how many computers are easily find out how many computers are there in the same row and same column there in the same row and same column fine and then what you can do next is fine and then what you can do next is for every computer you just have to for every computer you just have to check that check that if this computer is in a community if this computer is in a community community state or not communicating community state or not communicating stakeholder state or not how you can stakeholder state or not how you can check that for a particular computer to check that for a particular computer to be in a communicating state there should be in a communicating state there should be at least one more computer in the be at least one more computer in the same row in the same column then only same row in the same column then only you can take that as in a communicating you can take that as in a communicating state or it's not so that's a very state or it's not so that's a very simple observation if i can just draw it simple observation if i can just draw it out for one example out for one example if let's take you have a grid like this if let's take you have a grid like this and just randomly draw out some and just randomly draw out some computers computers okay so let's say that one computer is okay so let's say that one computer is here one computer is here one computer here one computer is here one computer is here and one computer is here is here and one computer is here uh that's it okay now these computers uh that's it okay now these computers can communicate with each other uh this can communicate with each other uh this computer will not so what you will do computer will not so what you will do here is that you have to first make a here is that you have to first make a map like two vectors that is one for the map like two vectors that is one for the column wise column wise and one for the row wise and one for the row wise then what you can do is you have to fill then what you can do is you have to fill that how many computers are there in the that how many computers are there in the particular row okay so uh for this as particular row okay so uh for this as you can see i'm talking about this so you can see i'm talking about this so there are four points four these are the there are four points four these are the four four uh as you can see uh columns first uh as you can see uh columns first column there are two computers or column there are two computers or servers whatever you can say there only servers whatever you can say there only one there is actually here in this line one there is actually here in this line there is one there is zero and the first there is one there is zero and the first line also there is zero similarly for uh line also there is zero similarly for uh as you can see for this line there is as you can see for this line there is zero for this line there is one for this zero for this line there is one for this line it is two for this line it is one line it is two for this line it is one okay now you can iterate over every so okay now you can iterate over every so you can actually cut it like generate you can actually cut it like generate this how you can generate this like you this how you can generate this like you can do this is o of n square you can can do this is o of n square you can iterate over every point and update it iterate over every point and update it in the same like in the uh what you can in the same like in the uh what you can say column as well as in the row okay say column as well as in the row okay for like you can iterate over this whole for like you can iterate over this whole matrix and whenever you find out the matrix and whenever you find out the server you can update that there is a server you can update that there is a particular server and update the particular server and update the particular row as the as well as column particular row as the as well as column fine after doing that what you'll do in fine after doing that what you'll do in the end you'll again do an o of n square the end you'll again do an o of n square or of not n square exactly of n into m or of not n square exactly of n into m because it can be different you have to because it can be different you have to read over the matrix again and what you read over the matrix again and what you will do you have to check that whether i will do you have to check that whether i want to take this server whether it is want to take this server whether it is in a communicating state or an isolated in a communicating state or an isolated server if it is a isolated server or not server if it is a isolated server or not if it is communicating state they should if it is communicating state they should be at least be at least like two like more than two computers like two like more than two computers because this is already taken i have to because this is already taken i have to find out that there is at least one more find out that there is at least one more computer in the same row computer in the same row okay in the same row or in the same okay in the same row or in the same column now that can be said here because column now that can be said here because we can just check that whether there's we can just check that whether there's one more computer so there is one which one more computer so there is one which means that there is no computer in the means that there is no computer in the same row but there is one more component same row but there is one more component in the same column so i can take that in the same column so i can take that similarly i'll iterate over everything similarly i'll iterate over everything and when i come to this it will tell and when i come to this it will tell that there is only one computer in the that there is only one computer in the in this particular row and only one in this particular row and only one component in this particular column so i component in this particular column so i cannot take that similarly just count cannot take that similarly just count all of them and then print it out that's all of them and then print it out that's the whole logic for this problem nothing the whole logic for this problem nothing much more much more let us move down to the actual uh code let us move down to the actual uh code port part of this video we'll first find port part of this video we'll first find out the dimensions of the grid okay make out the dimensions of the grid okay make a row and column that is row for coro a row and column that is row for coro and column for column and column for column and then what you'll do is over the and then what you'll do is over the whole matrix of the whole matrix using whole matrix of the whole matrix using two for loops nested for loops and just two for loops nested for loops and just check that whether a particular grid is check that whether a particular grid is giving a server giving a server if it is giving a server what you'll do if it is giving a server what you'll do you'll update the particular row as well you'll update the particular row as well as column increase by one because as column increase by one because everything is initialized with zero and everything is initialized with zero and then you'll increase by one just thus then you'll increase by one just thus finding out the column frequency and the finding out the column frequency and the row frequency how many servers are there row frequency how many servers are there and then total is the total amount of and then total is the total amount of servers that are communicating state servers that are communicating state again it right over the whole grid okay again it right over the whole grid okay so another condition is if the so another condition is if the particular grid is one which means that particular grid is one which means that there is a server down there also and there is a server down there also and either of them is true either there is either of them is true either there is up in this particular row row is greater up in this particular row row is greater than or equal to two which means that than or equal to two which means that there are more than two computers in the there are more than two computers in the particular row or there are more than particular row or there are more than two computers in the particular column two computers in the particular column and it is in a or state but it is and and it is in a or state but it is and with this condition with this condition i hope you get the point so this is like i hope you get the point so this is like a condition you have to satisfy if this a condition you have to satisfy if this condition is satisfied the total will condition is satisfied the total will increment by one that is there is a increment by one that is there is a server that we are on that is in the server that we are on that is in the communicating state take that and in the communicating state take that and in the end print that answer end print that answer so i hope you get the point how we have so i hope you get the point how we have write down the code for this problem as write down the code for this problem as well as the logical part so thank you well as the logical part so thank you for watching this video till the end i for watching this video till the end i will see you next one till then keep will see you next one till then keep coding and bye
2024-03-19 17:50:27
1,267
https://i.ytimg.com/vi_w…xresdefault.webp
1267. Count Servers that Communicate | LEETCODE MEDIUM | FREQUENCY MAP | CODE EXPLAINER
y_ATnngpdFg
hello everyone welcome to another one of my lead code videos and this one we'll my lead code videos and this one we'll do lead code one two sum and I'll try to do lead code one two sum and I'll try to make this a little bit more beginner make this a little bit more beginner friendly because it is likely that a friendly because it is likely that a good percentage of you watching this good percentage of you watching this video are just starting out on lead code video are just starting out on lead code so yeah let me help you start out your so yeah let me help you start out your journey and provide you a good journey and provide you a good explanation for how to solve this explanation for how to solve this problem problem so so the question is basically we are given the question is basically we are given an array of integers numbers right so as an array of integers numbers right so as an example we have 2 7 11 15. and we're an example we have 2 7 11 15. and we're also given a number Target right so in also given a number Target right so in this case like Target is nine this case like Target is nine and we are going to return the indices and we are going to return the indices of two numbers that add up to Target so of two numbers that add up to Target so indices are basically indices are basically the indexes of the array so the first the indexes of the array so the first element is index zero the second element element is index zero the second element is index one and so on right so is index one and so on right so we have to return the indexes in a form we have to return the indexes in a form of array of array of the two elements that sum up to of the two elements that sum up to Target right so in this case we return 0 Target right so in this case we return 0 and 1 because if you notice 2 plus 7 and 1 because if you notice 2 plus 7 so sum up to 9 and what are the indices so sum up to 9 and what are the indices of 2 and 7 it's 0 and 1. right so that's of 2 and 7 it's 0 and 1. right so that's why we return 9 and they say we can why we return 9 and they say we can return the answer in any order so it return the answer in any order so it could either be could either be 0 1 or 1 0. 0 1 or 1 0. and just one more example for and just one more example for completeness sake if we have this every completeness sake if we have this every three to four and our Target is six three to four and our Target is six in this case 2 plus 4 is equal to 6 and in this case 2 plus 4 is equal to 6 and the indices of that are 1 and 2 the indices of that are 1 and 2 respectively so that's why we return one respectively so that's why we return one two and obviously we can assume that we two and obviously we can assume that we have exactly one solution so we don't have exactly one solution so we don't really need to handle the case where we really need to handle the case where we can't find this or there are more than can't find this or there are more than one answers right so one answers right so how do we go about solving this problem how do we go about solving this problem so I've written the array again here so I've written the array again here just for example sake now one way to just for example sake now one way to solve this problem is you know we take solve this problem is you know we take each element of the array each element of the array and compare it to every other element and compare it to every other element until we find the sum that is equal to until we find the sum that is equal to our Target right so for example first we our Target right so for example first we take two take two and then we try two plus seven and then we try two plus seven and then we try two plus eleven and then we try two plus eleven and then we try 2 plus 15 and then we try 2 plus 15 and you know if we still don't find the and you know if we still don't find the sum then we move on to the next one and sum then we move on to the next one and then we try 7 plus 11. then we try 7 plus 11. 7 plus 15. 7 plus 15. right and if we still don't find it then right and if we still don't find it then we move on to the next one and then we we move on to the next one and then we try 11 plus 15. right so we don't need try 11 plus 15. right so we don't need to try the ones previously because they to try the ones previously because they would have been tried when we were would have been tried when we were running through those so running through those so overall what will be the how many overall what will be the how many operations will we do in the worst case operations will we do in the worst case if we were to use this algorithm right if we were to use this algorithm right so so the first one will be compared to n the first one will be compared to n minus 1 other elements right so it will minus 1 other elements right so it will be n minus 1 elements be n minus 1 elements you know to be compared for the first you know to be compared for the first one the second one will be compared to n one the second one will be compared to n minus two elements right so we'll try n minus two elements right so we'll try n minus two pairs right and so on until minus two pairs right and so on until the last one is only compared to the last one is only compared to one element right so until one so this one element right so until one so this is the summation of 1 to n minus 1 which is the summation of 1 to n minus 1 which is is um just equal to n times n minus 1 over um just equal to n times n minus 1 over 2. 2. and this basically is and this basically is going to be like N squared over 2 going to be like N squared over 2 minus one half minus one half so this so this these this is the number of operations these this is the number of operations we'll end up doing in the worst case we'll end up doing in the worst case right so it's N squared over 2 minus one right so it's N squared over 2 minus one half and in terms of order it's it's a N half and in terms of order it's it's a N squared algorithm right so it's a big O squared algorithm right so it's a big O of N squared algorithm because of N squared algorithm because as our n increases as our n increases the number of operations will you know the number of operations will you know increase as a square proportion to the N increase as a square proportion to the N right so this is a a kind of you know right so this is a a kind of you know good initial solution that will get us good initial solution that will get us the correct answer because we'll keep the correct answer because we'll keep comparing all the possible Pairs and comparing all the possible Pairs and once as soon as we get a target of like once as soon as we get a target of like our whatever Target T's we'll just our whatever Target T's we'll just return those indices right return those indices right but the question is can we do better but the question is can we do better like how can we optimize this solution like how can we optimize this solution so to optimize the solution like you so to optimize the solution like you know let's say when we're taking the know let's say when we're taking the first element let's say number two we first element let's say number two we know that we already know the Target know that we already know the Target right so we know that we're looking for right so we know that we're looking for some number X some number X which will equal to the Target so let's which will equal to the Target so let's say the target is T right so there's say the target is T right so there's only really one number here where only really one number here where because if you solve for x that would be because if you solve for x that would be T minus two right so there's only really T minus two right so there's only really one number one number that will satisfy the value of x that will satisfy the value of x that we should look for in the entire that we should look for in the entire array right so which is going to be T array right so which is going to be T minus 2 or T minus the whatever element minus 2 or T minus the whatever element we're comparing right so really our only we're comparing right so really our only the question we need to ask is you know the question we need to ask is you know is there an X in the array right so is X is there an X in the array right so is X present in the array and if yes what is present in the array and if yes what is the index of X right so the index of X right so what kind of data structure allows us to what kind of data structure allows us to to do this in efficiently right so if we to do this in efficiently right so if we have a a data structure have a a data structure where we have a map a hash map right so where we have a map a hash map right so if we have a hash map of the number n if we have a hash map of the number n to the index right to the index right then we can create a hash map of this then we can create a hash map of this array so we can see like two array so we can see like two you is the key and the index is the you is the key and the index is the value is going to be zero value is going to be zero seven is the key the value is one seven is the key the value is one 11 is the key 11 is the key the value is 2. and 15 is the key the value is 2. and 15 is the key the value is 3. so now once we have this the value is 3. so now once we have this hash map this is just going to be hash map this is just going to be Crea we can create this hash map in on Crea we can create this hash map in on time right because we just need to time right because we just need to iterate through the array once to be iterate through the array once to be able to create this hash map right and able to create this hash map right and once we have this hash web then we'll once we have this hash web then we'll iterate through the array again okay now iterate through the array again okay now for number two for number two do I have already uh do I have already uh T minus 2 in the T minus 2 in the array and then we'll find for example if array and then we'll find for example if T was 9 we find oh yes we have seven T was 9 we find oh yes we have seven index one so we just returned that right index one so we just returned that right and looking up something in the hash map and looking up something in the hash map is o1 because it's a you know it's a is o1 because it's a you know it's a hashed data structure so hashed data structure so it allows us to efficiently look up each it allows us to efficiently look up each element so now element so now we'll be doing n operations to populate we'll be doing n operations to populate the hash map and then another n the hash map and then another n operations going through each of these operations going through each of these and finding T minus that X whatever that and finding T minus that X whatever that X is at each index X is at each index in the hash map right which is another n in the hash map right which is another n operation so it's going to be two n operation so it's going to be two n operations and that is or just an order operations and that is or just an order of n algorithm of n algorithm which is much better than our previous which is much better than our previous N squared algorithm because this N squared algorithm because this algorithm just grows linearly as n algorithm just grows linearly as n increases versus increases versus the other one would go grow by like a the other one would go grow by like a square proportion as n increases so now square proportion as n increases so now let's go ahead and just code this let's go ahead and just code this solution solution so we'll start out with our map of so we'll start out with our map of integer integer to integer which will be our element to to integer which will be our element to Index right this is the map we said we'd Index right this is the map we said we'd create first create first and we'll just go through each element and we'll just go through each element in the nums array so we'll say well I in the nums array so we'll say well I equals 0 I less than lumps dot length I equals 0 I less than lumps dot length I plus plus so this will create a loop plus plus so this will create a loop from 0 to the last index of nums from 0 to the last index of nums and here we'll just say and here we'll just say LM to index dot put LM to index dot put the element so the key will be our the element so the key will be our element which will be num element which will be num it's at I and this should be nums it's at I and this should be nums so the it will be num set I the element so the it will be num set I the element and then the index which is just I right and then the index which is just I right so this would populate our hash map so this would populate our hash map for all of the element and then what we for all of the element and then what we need to do is just again go through the need to do is just again go through the nums so we'll just again iterate through nums so we'll just again iterate through the nums and now you know our X which is the nums and now you know our X which is basically what we need to look for basically what we need to look for is going to be Target minus n right so is going to be Target minus n right so whatever n we're at we should look for whatever n we're at we should look for Target minus n Target minus n and then you know if our LM to index dot and then you know if our LM to index dot contains X contains X so that means if we have X in the hash so that means if we have X in the hash map map then we should get the index then we should get the index of of X so we we'll just re so we'll say index X so we we'll just re so we'll say index of X is equal to LM to index dot get X of X is equal to LM to index dot get X and our current index will be the index and our current index will be the index of n so we actually need to of n so we actually need to uh create a index based Loop here so we uh create a index based Loop here so we have an index based Loop here have an index based Loop here and our X will be Target minus nums at I and our X will be Target minus nums at I right because that's our number at this right because that's our number at this element element and then and then here the index of I is going to be just here the index of I is going to be just I so we'll just return here new and I so we'll just return here new and I comma index of X that means we have I comma index of X that means we have found our found our pair pair right and right and at the end if we aren't able to find at the end if we aren't able to find anything we'll just return an empty anything we'll just return an empty array but we are pretty much guaranteed array but we are pretty much guaranteed here that we won't reach this case here that we won't reach this case because they guarantee exactly one because they guarantee exactly one solution so hopefully we'll be able to solution so hopefully we'll be able to return something we won't run into the return something we won't run into the case where we end up here case where we end up here so so let's run the solution see if it works let's run the solution see if it works and then we'll do one more optimization and then we'll do one more optimization before we close the video so we actually have a error here because you know in this case we have three is in our map and then we saw six as the target but then you know three and three add up to six but you can't actually use the same element twice so yeah this was actually the optimization I was going to do but turns out that we need to do that optimization so what we'll do is we'll keep populating our map and instead of doing this logic over here we'll just move this into the upper Loop right so before we insert it into the map we'll put this logic here so basically we'll say okay this is our X which we're looking for have we seen this before right so have we seen Target minus nums at I before right so if we have seen it before we get the index and return it otherwise if we haven't seen it before we insert it in the map so that something in the future can use it so this will guarantee that you know we don't use the same number twice because we aren't putting it in the map until then unless we have checked if a previous one is matching right and we would we don't return and only then do we return if a previous one is matching so the current one won't be considered twice so now let's run the code hopefully this works all right this passes all the test cases and let's submit perfect so this is an accepted solution thank you so much for watching I'll see
2024-03-18 09:37:21
1
https://i.ytimg.com/vi/y…axresdefault.jpg
Leetcode 1 Two Sum (Java) - BEGINNER FRIENDLY
goKHmMUj9yA
hey hey everybody this is larry this is day 19 of the lead code daily challenge day 19 of the lead code daily challenge hit the like button hit the subscribe hit the like button hit the subscribe button join my discord let me know what button join my discord let me know what you think about today's forum this you think about today's forum this problem is link problem is link list psycho 2. list psycho 2. so the second one is that the one with so the second one is that the one with the pointer uh we we're learning the note right okay we we're learning the note right okay yeah so yeah so what is negative one nick what is it what is negative one nick what is it just return none yeah i think it just returned none right oh do not modify wait no we're not modifying it given that we turn the node okay we turn none okay fine it's actually the first line i just read it backwards okay yeah so this is the one way you have to actually do a return um first of all i i think the the first thing is um you know you don't know how to do this uh or at least how to do the first step of detecting a cycle definitely go i think there is a previous problem with is just detecting a psycho um we'll go over it really quickly but you know you get two problems at the same time as opposed uh if you haven't done it yet but the idea is that [Music] the idea is that you have two pointers uh there there's a couple of names that go by this but basically you have a first point and a slower pointer and then if there's a cycle so the only two cases right there's a cycle and there's no cycle if there's a cycle then you venture they'll catch up uh let me actually pull up paint let's see oh that was already up huh that's awkward but uh anyway yeah let's say you have uh you know some node and you know there are only two cases right one is no cycle no psycho is kind of obvious if you have two pointers uh eventually you know this goes to none right uh eventually you just go outside and then you'll reach a nun and then you're you're happy you're good you're living your life and there's no cycles however if there's a cycle right then eventually if there's a cycle right then eventually um because of i guess um because of i guess [Music] [Music] do i want to say induction but the idea do i want to say induction but the idea is that you have one point that moves is that you have one point that moves twice twice and then one that goes one then then and then one that goes one then then here let's say you start with here here let's say you start with here um um yeah let's say you start here and then yeah let's say you start here and then after one step you have one pointer here after one step you have one pointer here and one pointer here right after two and one pointer here right after two steps steps you would have one pointer here and then you would have one pointer here and then the other one would have gone two more the other one would have gone two more here right so then the idea is that the here right so then the idea is that the fast pointer um the fast pointer will gain one will basically gain one once um uh it enters the loop right what i mean by that is that every iteration every step that uh the slower one takes the fast one takes two so that eventually will catch up to it because of i guess is it induction i don't know but but like let's say the the distance between them is x after one iteration will be x minus one and so forth right so that's basically the idea behind that and that's um to be honest it's one of those trivia things i don't know if you could come up with if you haven't heard of it before but i just feel like it's one of those things that um yeah it just becomes like people just know about it right and when people know about it that it's so common uh i don't even know if it's a interview question anymore because it's too common to be an individual question but that's the idea right and then now uh the idea is then okay let's say there is there is a cycle right there's a cycle um you have to try to figure out where the starting point is um there are a couple of ways to kind of represent this as a system of equations is how i want to think about it um i actually don't remember this particular part with respect to like the formula or the code so so we'll try and see if we can prove it from scratch so this part may be a little bit murky and if so then you know feel free to uh feel free to watch my card um uh fast forward watch on uh faster speed or so forth so okay let's say there's a cycle right what does that mean [Music] that means that's the slow pointer uh let's say uh yeah let's say the slope let's say uh yeah let's say the slope let's say there's two parts right a uh let me let there's two parts right a uh let me let me bring up paintbrush again hang on me bring up paintbrush again hang on maybe that's a little bit easier for a maybe that's a little bit easier for a quick visualization uh but yeah let's quick visualization uh but yeah let's say you have this and then let's say the say you have this and then let's say the part before the cycle is let's use part before the cycle is let's use another color another color let's say the part before this let's say the part before this is a is a and then and then this part um this part um and then the part where they meet will and then the part where they meet will be b right be b right let's say they meet here i don't know let's say they meet here i don't know this is just an example let's say they this is just an example let's say they meet here right then that's b meet here right then that's b um what does that mean right um then here we can kind of try to figure out the formulas is what i was going to say and let's see if we can do that right so the slow pointer would move a plus b just by definition um so in this case i think one observation to know here is that um the slow pointer will not make one full cycle through because like i said no matter where the the fast pointer is let's say the fast point let's say the the length of the cycle is equal to c um and the fast point there is one space ahead right or c minus one space behind if you want to put it that way that means that it will take c minus one um iteration to go right and of course in that case the slow point it would have only might move c minus one case so it would never make one full cycle just an observation right um i don't know if it's a useful observation but it is an observation because like i said i'm trying to um try to prove this by uh from scratch and figure it out right so yeah so then the faster pointer of course it goes 2a or 2a plus 2b um and then there's another way of phrasing it right so this is just two times the slower pointer just by definition um and now the question is can i you see in this right in either one um well we where do they meet uh this is the part that i'm always a uh this is the part that i'm always a little bit sketchy about and it's such little bit sketchy about and it's such such trivia such trivia hmm oh yeah and i think it goes without oh yeah and i think it goes without saying we're trying to do it with all of saying we're trying to do it with all of one memory because obviously if we have one memory because obviously if we have of n memory this is even more you know of n memory this is even more you know we just have a hash table or a lookup we just have a hash table or a lookup table or something like that and that table or something like that and that would be uh would be uh you know like a four loop and silly so you know like a four loop and silly so yeah um so let's incorporate cycles into this right so the idea behind this is let's see let me see if i could have my visualization up real quick so this means that so this means that there is some head so the slower point that moved from a and then will be part of the cycle okay how how far did the the faster pointer the faster pointer when it moves to b the faster pointer when it moves to b what does that mean right what does that mean right and there's this formula as well but and there's this formula as well but that means that that means that it moves a plus because the a is the head c is the length of the cycle right do you say let me think about this for a second ah so bad at this this linked list stuff is so useless if you ask me but that's besides the point you i know people could say that about anything but it just doesn't really come up in competitive either not even um yeah but okay what am i what am i saying okay let's see let's see i'm just tired today okay let's see right so a is the part that means that it has so b is the length that is traveled so b is the length that is traveled inside the loop so that means that the inside the loop so that means that the faster point of a faster point of a meet pointer at b meet pointer at b plus the cycle right um because the cycle is one cycle um we assume that the faster go one foo and then plus and then um and then catches up at b does that make sense hopefully that makes sense um let me draw it up really quick again actually um i think this is right though but let's talk about this again um if we okay okay let's say this is a let's say this is a let's say they meet uh let's say they meet uh let's say they meet here right so then let's say they meet here right so then this is b and then of course the cycle length for c this is c um right so so that means that because in order for for the fast pointer to reach all the way back to and then one cycle later right so of and then one cycle later right so of course if you draw it this way then it's course if you draw it this way then it's clear that this is a clear that this is a um um b is this part b is this part um already and then c is the the cycle um already and then c is the the cycle right the length of the cycle just to right the length of the cycle just to kind of visually show the formula that kind of visually show the formula that we kind of uh that i have here which i we kind of uh that i have here which i was trying to do it in my head which is was trying to do it in my head which is i think fine in theory but you know i'm i think fine in theory but you know i'm trying to trying to show you a little bit right so okay so show you a little bit right so okay so in this case in this case then that means that then that means that well i mean obviously these two are the well i mean obviously these two are the same which means that the same which means that the um um [Music] [Music] this is the number of steps this should this is the number of steps this should you go to you go to do and of course this if you subtract a do and of course this if you subtract a and b plus both sides that a plus b is and b plus both sides that a plus b is equal to c equal to c is that right that is huh maybe some people just memorized this then i guess it's very easy to remember i just never i don't think i ever remember this but uh but that's actually if that's true then that's good i i am not super confident at this particular point not gonna lie uh i'm a little bit rusty and yeah and you could kind of see me actually solve a problem that i don't really you know like like this is almost like ad hockey weird problem right so okay in this case okay so what does this mean this means this is the length of the cycle right that means that the slow pointer has moved the length of the cycle by the time it meets man that sounds really awkward but is that true let's see i mean one thing that i like to do is uh to verify myself before i kind of invest more time in it is take a you know take to take a case and then see where where it goes like for example example one what happens here right and you kind of so so move one each move one each and then two and then two and then three and then three huh i guess that is the i guess that i mean it works for this one so okay wow that is uh i guess that's how people remember that because i do know people like did this really quickly and i'm like yeah i don't know because i i i don't like memorizing these trivias but i guess this one's actually not that bad to remember but i don't know i still don't like it so that's why i don't remember it but as you can see you can put uh kind of figure this out where i don't know about very quickly but pretty okay right okay so then that means that okay we know the cycle length how do we uh how do we get the starting pointer right um and the the point there is of course just a that's basically effectively the the answer that we're trying to get which is a so then we already s so then here um what is a right a is equal to of course c minus b um but can i represent this in terms of but can i represent this in terms of motion um okay so so we have a okay so the length that it goes is the length of the cycle right so what does that mean so that means that we're in in the cycle um and this is the length of the cycle minus b that means that if we have a pointer that moves b would that give us a no what we want what we want so a is equal to this stuff man i am not man i am not knowing this at all uh knowing this at all uh [Music] [Music] so we want to find a which is c equals so we want to find a which is c equals to b but we're trying i'm trying to to b but we're trying i'm trying to think about how to do pointer arithmetic think about how to do pointer arithmetic because we don't we actually in theory because we don't we actually in theory know c or b um but if we move hmm is that a good way about it uh we also uh we also do have all these other things do have all these other things so basically if we move another if we move another a plus b we get is that helpful is that helpful um don't know how do we find a or b then given these okay so we have a fast pointer this part i'm not i'm a little sketched okay so let's say we have another point okay so let's say we have another point there right so what happens if we have another fast pointer i'm just like throwing up random ideas if we're not a fast pointer and we are at um [Music] then effectively what we're doing is and then on the fast one we add a plus b and then on the fast one we add a plus b plus three plus c plus three plus c right which i guess is just adding two cycles on both sides does that help at all man just what i'm really bad today man just what i'm really bad today um um okay so let's say we have this thing and okay so let's say we have this thing and we want to add or maybe this thing right so we're at actually let's step back for a second right so hmm so we know that this is the length of the cycle and that means that we we know that um so that means that if we add another a then this is the cycle and this will be c and then we will get a okay i think that's how i do uh i think sorry about the red herring um [Music] yeah okay i think that's how you do it right is that okay you have a and b if we do if yeah let me say it in a way if we do if yeah let me say it in a way that i think i understand now that the that i think i understand now that the thing is up uh okay so now we thing is up uh okay so now we have a plus b on a slow pointer um and have a plus b on a slow pointer um and so in order so we add another a to this so in order so we add another a to this then we know that this is equal to c then we know that this is equal to c which is equal to which is equal to um because if a plus c is of course um because if a plus c is of course equal to c equal to c sorry a plus c in this sorry a plus c in this uh uh linked list of arithmetic is equal to a linked list of arithmetic is equal to a because because c just cancels out right like it just c just cancels out right like it just loops around so that means that in the loops around so that means that in the beginning we would have a so that means beginning we would have a so that means that that from here from here um from from where we are now we have to um from from where we are now we have to move another a right move another a right um and we move and other a maybe that well okay maybe i'm maybe that doesn't make sense or like it makes sense but how do i get or like it makes sense but how do i get this again i think i had some idea in my this again i think i had some idea in my head but now i i'm a little bit lost head but now i i'm a little bit lost again i mean what i'm saying is right but how i mean what i'm saying is right but how do i get that again do i get that again uh okay so we have a plus b uh okay so we have a plus b and let's say we move i mean if we know how to move another a i mean if we know how to move another a then we just then we just know the a right so that's actually know the a right so that's actually maybe maybe uh uh a circular logic thing uh uh a circular logic thing man i'm really bad today on this one man i'm really bad today on this one uh let's see uh let's see maybe that wasn't the right way to go i maybe that wasn't the right way to go i was gonna do something like okay maybe was gonna do something like okay maybe if we add another if we add another [Music] when would okay i guess my question is when would like if we start another fast pointer like if we start another fast pointer from the get go from the beginning right from the get go from the beginning right um um okay maybe i'll write it here um let's say we reset this to zero after after finding this thing um let's say we want another um until they meet again what does that mean right because now because now what happens is that one psycho is going what happens is that one psycho is going to be one cycle is going to be c i guess because a could be because a could be large and the first point it would catch large and the first point it would catch up one at a time does that even up one at a time does that even wow i really have no idea how to do this wow i really have no idea how to do this hmm today anyway because i feel like hmm today anyway because i feel like i've done this before i've done this before but i'm missing um but i'm missing um okay so we have this thing okay so we have this thing where's the faster pointer again the where's the faster pointer again the faster pointer is a plus b plus c oh faster pointer is a plus b plus c oh yeah we knew that because they're both yeah we knew that because they're both at the same place at the same place that's how they meet that's how they meet um okay let's see let's see how is there a way i can move just b how is there a way i can move just b steps or a steps i guess if we just add steps or a steps i guess if we just add a steps and this would be a steps and this would be not a trivial in a way not a trivial in a way as we already said um is that true no i guess not i was um is that true no i guess not i was going to say maybe we could going to say maybe we could uh like we could calculate this by uh like we could calculate this by sending another sending another uh another pointer moving c uh another pointer moving c but that doesn't really change anything but that doesn't really change anything because now we know the length of c because now we know the length of c but we do not know a or b what if we no that doesn't make sense i was going to say well we sent a second slow pointer but it's also there's a chance that they just never meet right so that's just silly if we have a second fast pointer where if we have a second fast pointer where do they meet do they meet i i guess i was a little bit lazy not i i guess i was a little bit lazy not lazy i just don't know how to do that lazy i just don't know how to do that one one right right then that means that the fast pointer then that means that the fast pointer is going to be a plus b behind um what happens if we have a second um what happens if we have a second slow pointer okay i i think now i i remember the idea that i kind of lost a little bit because which is actually ridiculous now that i which is actually ridiculous now that i think about it i mean i actually alluded think about it i mean i actually alluded to the same ideas but uh but to the same ideas but uh but sometimes math is just ridiculous and sometimes math is just ridiculous and and it's also one of those things where and it's also one of those things where if you knew the answer you could prove if you knew the answer you could prove it easily but i don't know how people it easily but i don't know how people come up with stuff like this but the come up with stuff like this but the idea is the same right is this this plus idea is the same right is this this plus a is equal to c plus a so this is of a is equal to c plus a so this is of course now we have um course now we have um now we have c but the idea is that now we have c but the idea is that um and we kind of um and we kind of touched upon this before we add eight a touched upon this before we add eight a steps on each side but the key thing to steps on each side but the key thing to know here is that know here is that um that means that the two pointers meet at that means that the two pointers meet at the same time and the second slow the same time and the second slow pointer i think that's basically the pointer i think that's basically the idea here idea here um because okay let me bring back the paintbrush thingy again um so basically let's say we have here so basically let's say we have here right um and right um and and this this this actually may not be and this this this actually may not be true because i might have missing some true because i might have missing some notes but notes but actually no this is actually right but i actually no this is actually right but i don't know uh by accident really but don't know uh by accident really but yeah but let's see what they mean here yeah but let's see what they mean here right that means that right that means that because this is a plus b because this is a plus b here here um and we know that um and we know that another additional a another additional a this completes the cycle because that's this completes the cycle because that's also the definition of a plus b but that also the definition of a plus b but that means that because of that means that because of that if we have another slow pointer starting if we have another slow pointer starting in the beginning they will meet at in the beginning they will meet at exactly here because this a is equal to exactly here because this a is equal to this a i think i had the math right this a i think i had the math right but i missed the visualization in which but i missed the visualization in which they meet at the same point and if they they meet at the same point and if they meet at the same point then you can just meet at the same point then you can just return that answer return that answer this is also this is also honestly a ridiculous ridiculous problem honestly a ridiculous ridiculous problem if you haven't done it or seen it before if you haven't done it or seen it before i've seen it before and i've seen it before and why i refuse to remember it or memorize why i refuse to remember it or memorize it because it's not really it's just one it because it's not really it's just one of those things either you remember you of those things either you remember you you don't you and i don't put any effort you don't you and i don't put any effort into memorizing this because it's into memorizing this because it's whatever um but whatever um but but that said that's uh that's actually but that said that's uh that's actually amazing so amazing so that allows us that allows us that's it right the the tail that's it right the the tail um um if you send a second slow point that if you send a second slow point that they intersect at the starting point they intersect at the starting point okay so this is already a long video but okay so this is already a long video but hopefully you kind of see my thought hopefully you kind of see my thought process including a couple of times process including a couple of times where i was way close like i saw this where i was way close like i saw this idea i knew i just saw the mathematical idea i knew i just saw the mathematical thing but i think i confused myself with thing but i think i confused myself with the math uh the math with the the math uh the math with the visualization and also what it means visualization and also what it means physically right in terms of the linked physically right in terms of the linked list um and i think once we list um and i think once we um kind of put that all together um kind of put that all together everything is good again everything is good again okay okay let's uh let's uh let's get it to let's get it to um um yeah yeah let's get started on this then um and let's get started on this then um and this hopefully this hopefully uh even though it's really long and i uh even though it's really long and i hope you watched it on a faster speed hope you watched it on a faster speed until at least the end uh hope this is a until at least the end uh hope this is a very good very good understanding problem because this is understanding problem because this is hard hard if you uh you haven't done it before so if you uh you haven't done it before so yeah um okay so then now we move yeah um okay so then now we move and this is what i'm doing now is just and this is what i'm doing now is just the array this part i say is standard the array this part i say is standard with voids algorithm and it actually with voids algorithm and it actually comes into play with different other comes into play with different other problems as well um which is why i know problems as well um which is why i know it because it because in this case there's a linked list right in this case there's a linked list right of course so and like i said i don't of course so and like i said i don't care for linked list per seg it doesn't care for linked list per seg it doesn't come up that much but you can actually come up that much but you can actually use this on use this on other things that are not linked list other things that are not linked list but it has a linked list e but it has a linked list e uh thing right like one one thing that uh thing right like one one thing that is used is if you have a function like is used is if you have a function like if you have if you have for example f of x um and you want to for example f of x um and you want to see is there a cycle um uh dot dot right is there a cycle um and uh dot dot right is there a cycle um and of course in this case freud's algorithm of course in this case freud's algorithm would be uh the slow and the fast would be uh the slow and the fast pointer um could used to be used to pointer um could used to be used to solve this in constant space if that's solve this in constant space if that's your need right so there are a lot of your need right so there are a lot of like stuff like this like stuff like this and then you could kind of even do and then you could kind of even do another loop to get the entry point another loop to get the entry point again um which is kind of like i said again um which is kind of like i said kind of miraculous but in either case kind of miraculous but in either case uh uh yeah maybe i could use that because i yeah maybe i could use that because i think actually interestingly think actually interestingly a couple of days ago i did a code first a couple of days ago i did a code first form where i was running out memory um form where i was running out memory um though this is a little bit slower so i though this is a little bit slower so i don't know but yeah so maybe that could don't know but yeah so maybe that could have been helpful anyway so yeah wow have been helpful anyway so yeah wow how do i want to write this um yeah uh well fast is not none fast is equal to fast.next if s dot next is not none uh but fast it's not none as fast as you go to fast down next slow as you're gonna slow down next there's this part i'm a little bit sketchy about in that i always forget how to write uh the loop in that there's a there's not enough by one um but if this is if this is a little bit off i'll have to just modify it but uh but yeah they're the same then we break and of course they're the same so you could just take either one um doesn't really matter right like so we'll just start slow as you go ahead again and then now while slow is not you go to head slow [Music] next and then just return slow again uh again it doesn't matter which one you return because they're the same right that's the variant let's give it a spin maybe i'm off by one maybe not hopefully not okay uh let's see oops add a few more cases oh oh i i um i uh watched my card i didn't i didn't do the case where um yeah i didn't do the case where um yeah i didn't do the case where um um you know this is true you know this is true yeah the the non link the the non-psycho yeah the the non link the the non-psycho case is what i forgot um and that looks case is what i forgot um and that looks okay let's give it a submit done it okay let's give it a submit done it apparently is it a year and a half ago apparently is it a year and a half ago okay cool um yeah okay cool um yeah that's all i have for this one i know that's all i have for this one i know this is a longer video um this is a longer video um but i hope that but i hope that i hope that i mean because you know to i hope that i mean because you know to be frank this is a be frank this is a this is a problem that a lot of people this is a problem that a lot of people have videos on so so i don't really you have videos on so so i don't really you know like i don't feel like know like i don't feel like you know if you only want the answer you know if you only want the answer then i apologize uh the video is a then i apologize uh the video is a little bit long but if you want to see little bit long but if you want to see how someone whom um have some idea but how someone whom um have some idea but wanted to kind of uh do the thought wanted to kind of uh do the thought process about how to process about how to how to solve this problem from scratch how to solve this problem from scratch not really scratching i'm not gonna lie not really scratching i'm not gonna lie but like to salvage live um hopefully but like to salvage live um hopefully this was a good this was a good good uh attempt to kind of kind of uh good uh attempt to kind of kind of uh visualize that uh let me know what you visualize that uh let me know what you think let me know how you did let me think let me know how you did let me know if you did it in constant space uh know if you did it in constant space uh that's all i have stay good stay healthy that's all i have stay good stay healthy good morning to good mental health uh have a great rest of the week and i'll
2024-03-21 12:38:17
142
https://i.ytimg.com/vi/g…axresdefault.jpg
142. Linked List Cycle II - Day 19/31 Leetcode January Challenge
RMIm1Sy79aw
hello welcome to my channel today if you have leeco have leeco 438 find all anagrams in a string 438 find all anagrams in a string so given a string s and a non-empty so given a string s and a non-empty string string p find all the star indices p find all the star indices of piece anagram in s of piece anagram in s so later you will see the condition here so later you will see the condition here and and also another condition in non-empty also another condition in non-empty string p so as we know that and take a string p so as we know that and take a look at example right here we have s x look at example right here we have s x input a string another string p input a string another string p right here so uh the indices right here so uh the indices of zero which is in here of zero which is in here you can find the anagram of you can find the anagram of p so this mean abcs in here p so this mean abcs in here that have all the character in p abc that have all the character in p abc here here and also in this uh right here six and also in this uh right here six it also contain the anagram here so i it also contain the anagram here so i have bac have bac also have the same character also have the same character of abc here so now we have that two of abc here so now we have that two indices and indices and output for the outcome output for the outcome and another example here so you have a b and another example here so you have a b that have that have a b two character also b a's also a b two character also b a's also have a and b in here another index of have a and b in here another index of a and b and that's also a and b and that's also contained that two same character contained that two same character so the output will be this three index so the output will be this three index and this one is really really classic and this one is really really classic because it's using the sliding window because it's using the sliding window and i think it's really good to and i think it's really good to demonstrate this question to you demonstrate this question to you and for the beginning with the sliding and for the beginning with the sliding window problem window problem how we uh take care of this problem is how we uh take care of this problem is first first we just take a look at example two now we just take a look at example two now we have a table we have a table of 26 character of 26 character and you see a ends here b is here and you see a ends here b is here and so on to z and so on to z and we accumulate that we have one a and we accumulate that we have one a we also have one b so this is called we also have one b so this is called table table oh hold on o y is not writing okay finally so in here we know we need to to balance so in here we know we need to to balance it it so we need this through two from here to so we need this through two from here to balance this out balance this out so now we have a window start lab here so now we have a window start lab here and also have a window right here so and also have a window right here so the left side windows in here right side the left side windows in here right side window here window here so we need to expand that so as we so we need to expand that so as we expanded expanded the right side to here the right side to here then we have character a and we see then we have character a and we see character a character a and go back to this table and you see oh and go back to this table and you see oh a we cancel this out then since we cancel it out and here become zero so think this is zero how many do we need to balance it it become one so the two deducted by one things is zero right now so and we always keep the windows uh become two keep the two window and now we have right in here and later because this is only have window one only you need to expand the window become two range and now you see the window currently is and now you see the window currently is a b a b right now and you see b is right here right now and you see b is right here and come to the table again can the and come to the table again can the cancel this cancel this deducted by one and now deducted by one and now we have a balance of zero so since balance is zero then we found it and then what we do is output this left side left side which is zero into the array output and since this window is already fit for the size and we need to move the left pointer to b right here and right pointers right here so after you move this one you have to add this back at the a back in here so after it add a back here increase the balance again and then this is one loop and you come back to here to see if the rain windows is size of two so now window is a size of one expand the right side pointing to here so you have b and a process a then uh you cancel this out becomes zero and there's another balance of zero again so that's how you keep looping to indeed to the end of the string and you find all the possible solution and put it to the array and this is the idea of the sliding window problem let's take a look at the code now first we have a list of integer output so equal to new array this is just a template since p is a non-empty one so we uh have a simple hk check for s so s is equal to no or stop lane equal to zero then what we do is we turn output so just as cases and first thing we need to do is have a table here so the table will 26 space and then we loop through the p all the characters c and p two so every category in here then we need so every category in here then we need to put table c minus a in here accumulated for example if is the character is a a minus a so it's zero so that will have a zero as index they put it to the right place so b will be one for sure b minus a character is one so now accumulate that to the table now and we'll initialize that equal to zero initialize rise equal to zero so now we know um we're looking for how so now we know um we're looking for how many many because p is always two i mean p is because p is always two i mean p is slings always the balance slings always the balance so we're looking for how many characters so we're looking for how many characters we need to cancel we need to cancel out so now we have the balance starting out so now we have the balance starting at p dot lane so at p dot lane so now we have the right it's always less now we have the right it's always less than than stop link th so we have right look through the entire s string what we can do string what we can do is move the right side is move the right side we start moving the right side so after we start moving the right side so after we move the right side we move the right side we need to have so let's have a we need to have so let's have a um ins um ins current equal to s dot current equal to s dot character right psi character right psi minus a so this is minus a so this is the right side character and minus a the right side character and minus a is the index of that character is the index of that character so we will first table we will minus that character for example you have one and one here because a and b if we see a then we minus from here we deduct it from here because you're adding this to the table so you minus this from the balance so if table curve the current index is bigger or equal to zero that mean is um that's something that they're looking um that's something that they're looking for so a is for so a is is belong to p is belong to p [Music] [Music] so at that case and balance minus minus so mean balance will deduct by one two so you're looking for one less so you define you're looking for two and you have one is in here then you have less one less character you're looking at looking for then balance deducted one and right also increased by one because you're moving the right windows move the right move the right window so we check where balance is if balance so we check where balance is if balance equals zero that means we only looking equals zero that means we only looking finish looking all the balance finish looking all the balance from p from p then um we have output at left so left will be the current uh windows left side and that's the in this indices index that we're looking for so add it to the and if we check the windows if the window is smaller than 2 in here then you need to expand the right side but when you expand it to the right p size already then you start moving the p size already then you start moving the left left pointer so mean right minus pointer so mean right minus left equal to at that time the window need to at that time the window need to change by moving the left side change by moving the left side so we also do the same as so we also do the same as moving the right side so we can keep the moving the right side so we can keep the current current as stop chart at as stop chart at left and left and looking for the index of that character looking for the index of that character and put it to current so we and put it to current so we put the current put the current [Music] [Music] back to the table because you're back to the table because you're deducting deducting 1 from the the window 1 from the the window then we have to add this back to the then we have to add this back to the table table to see how many uh character in that to see how many uh character in that window and after we add it back we have window and after we add it back we have a check a check if table current um and the balance will add it back so after you add one if the table have one or more that character that mean the balance should be adding by one because you're looking for more if you give up you give up one of the things that belong to this um table or beyond to p then you definitely need to add back one more target in the balance so this is how we move so this is how we move the left pointer the left pointer windows so i think this is it for the moving window and now return output let's submit it cool let's submit it cool um and i think that's it for this um and i think that's it for this questions questions is sometimes it took me a while to think is sometimes it took me a while to think about the lab windows about the lab windows and it's normal and i think you should and it's normal and i think you should try to draw it out and nothing's easier try to draw it out and nothing's easier to understand to understand so other than that if you have more so other than that if you have more questions and please feel free to questions and please feel free to comment below comment below and i will see you in the next video bye
2024-03-22 12:17:21
438
https://i.ytimg.com/vi/R…axresdefault.jpg
Leetcode 438 - Find All Anagrams in a String (JAVA Solution Explained!)
YmhwaWOixhU
Roman number to integer so basically we have given a Roman number in the have given a Roman number in the question and we have to find the integer question and we have to find the integer for the same so here I have written the for the same so here I have written the program for that if you can see the program for that if you can see the solution the map I have formed in the solution the map I have formed in the map I have just kept the Roman number map I have just kept the Roman number with respective number and here I'm just with respective number and here I'm just taking a for loop with this for loop I taking a for loop with this for loop I will be just returning the sum and then will be just returning the sum and then you can see this is like complete video you can see this is like complete video and the explanation is already available and the explanation is already available on the channel and you can check that as on the channel and you can check that as well and do subscribe to code for well and do subscribe to code for placement guys for more such videos you placement guys for more such videos you can see the beat time is 55 which is not can see the beat time is 55 which is not so good but still the uh this is one of so good but still the uh this is one of the best approach to do so so do check the best approach to do so so do check out the complete video you can pause out the complete video you can pause this video and get the code as well this video and get the code as well thank you guys
2024-03-19 14:42:16
12
https://i.ytimg.com/vi/Y…pYdfY35rAQ92Sm6A
Leetcode 13. Roman to Integer #java
1TtWF2ZLNzk
hello guys welcome back to take those and in this video we will see how to and in this video we will see how to find X raised to the power of n we will find X raised to the power of n we will see the most optimal binary see the most optimal binary exponentiation technique in this problem exponentiation technique in this problem and this is from lead code number 50 and and this is from lead code number 50 and it is a very important math algorithm it is a very important math algorithm problem which you should never skip problem which you should never skip before looking at the problem statement before looking at the problem statement I would like to announce about our DSA I would like to announce about our DSA live training program which will live training program which will guarantee understanding of every guarantee understanding of every programming concept it makes you programming concept it makes you interview ready in just three months and interview ready in just three months and it will maximize your offers so that you it will maximize your offers so that you get the best possible pay and in the get the best possible pay and in the best possible company you can all the best possible company you can all the sessions will be live interactive sessions will be live interactive sessions so you will get the feel of a sessions so you will get the feel of a live class and you can ask all your live class and you can ask all your doubts throughout the class in order to doubts throughout the class in order to get more details please WhatsApp us on get more details please WhatsApp us on this given number let us now look at the this given number let us now look at the problem statement problem statement so let's see the problem statement the so let's see the problem statement the problem is very simple like we are given problem is very simple like we are given a to the power of B and we just want to a to the power of B and we just want to find the final answer for this so let's find the final answer for this so let's take an example like uh 2 to the power 8 take an example like uh 2 to the power 8 and if you want to calculate 2 to the and if you want to calculate 2 to the power 8 the simplest way would be to power 8 the simplest way would be to take the base exponent number of times take the base exponent number of times that means take two eight number of that means take two eight number of times and you just keep on multiplying times and you just keep on multiplying the the two eight times and if you do the the two eight times and if you do that then you will finally get the that then you will finally get the result but the number of operations result but the number of operations which you are doing is order of B hence which you are doing is order of B hence the time complexity for this approach the time complexity for this approach will be order of B so this is the will be order of B so this is the simplest possible approach now there simplest possible approach now there exist another idea which you can use to exist another idea which you can use to actually solve this problem so if you actually solve this problem so if you can look at 2 to the power of 8. the way can look at 2 to the power of 8. the way we can write 2 to the power 8 is 4 to we can write 2 to the power 8 is 4 to the power 4 as well and you can see 2 to the power 4 as well and you can see 2 to the power 16 it can also be represented the power 16 it can also be represented as 4 to the Power 8 2 to the power 32 as 4 to the Power 8 2 to the power 32 can also be represented as 4 to the can also be represented as 4 to the power 16. now what is happening here if power 16. now what is happening here if you see let's say I write 2 4 times you see let's say I write 2 4 times right if I write 2 4 times it is right if I write 2 4 times it is equivalent to 2 to the power 4. now 2 to equivalent to 2 to the power 4. now 2 to the power 4 I am saying that it can also the power 4 I am saying that it can also be written as 4 to the power 2 and how be written as 4 to the power 2 and how is this happening let's say we Club is this happening let's say we Club these two twos together now you can these two twos together now you can write them as 4 and this will become write them as 4 and this will become another 4. now if you multiply them then another 4. now if you multiply them then it will turn out to be 4 to the power 2. it will turn out to be 4 to the power 2. so with this logic we can say that 2 to so with this logic we can say that 2 to the power 8 can also be written as 4 to the power 8 can also be written as 4 to the power 4. this is nothing but the power 4. this is nothing but squaring the base and taking half of the squaring the base and taking half of the exponent and this is pretty logical this exponent and this is pretty logical this is a very simple example for the same is a very simple example for the same logic Now using the same logic we can logic Now using the same logic we can also say that 2 to the power 8 can be also say that 2 to the power 8 can be written as just Square the base and half written as just Square the base and half the exponent and you can write it as 4 the exponent and you can write it as 4 to the power 4 and simply 4 to the power to the power 4 and simply 4 to the power 4 can be written as just Square the base 4 can be written as just Square the base and half of the exponent so 4 Square and half of the exponent so 4 Square will be 16 and half of this 4 will be 2 will be 16 and half of this 4 will be 2 so 16 to the power 2 right even again if so 16 to the power 2 right even again if you start extending it it will be 16 you start extending it it will be 16 square which is I think 256 to the power square which is I think 256 to the power 1 so you will see that 2 to the power 8 1 so you will see that 2 to the power 8 final answer is 256. instead of final answer is 256. instead of following this technique if you had following this technique if you had followed the previous technique of the followed the previous technique of the simple approach of like multiplying two simple approach of like multiplying two eight times then that would have given eight times then that would have given you 256 but in eight number of steps in you 256 but in eight number of steps in this case you see that there are only this case you see that there are only three steps one two and three three steps one two and three right so this is heavily reducing the right so this is heavily reducing the number of steps so let's solve an number of steps so let's solve an example with this idea now if you look example with this idea now if you look at the idea it is just squaring the base at the idea it is just squaring the base and dividing the exponent by two so and dividing the exponent by two so let's uh Take 2 to the power 8. so if we let's uh Take 2 to the power 8. so if we take 2 to the power 8 then we can write take 2 to the power 8 then we can write it as 2 to the power 4 into 2 to the it as 2 to the power 4 into 2 to the power 4 which is like dividing it into power 4 which is like dividing it into two parts and simply this can be written two parts and simply this can be written as 4 to the power of 4 okay as 4 to the power of 4 okay now if we take again 4 to the power 4 we now if we take again 4 to the power 4 we can write it as 16 to the power of 2 can write it as 16 to the power of 2 with the same logic and again if we take with the same logic and again if we take 16 to the power 2 we can write it as 256 16 to the power 2 we can write it as 256 to the power 1 and whenever you reach to to the power 1 and whenever you reach to power 1 that is where you stop so 256 is power 1 that is where you stop so 256 is your final answer for 2 to the power 8. your final answer for 2 to the power 8. now if you try solving a similar problem now if you try solving a similar problem 2 to the power 9 where the power is odd 2 to the power 9 where the power is odd you will definitely fall into a problem you will definitely fall into a problem like if you divide this 9 by 2 it will like if you divide this 9 by 2 it will be 4 right so you have to write it as 2 be 4 right so you have to write it as 2 to the power 4 into 2 to the power 4 to the power 4 into 2 to the power 4 into 2 to the power 1 so you will see into 2 to the power 1 so you will see that this 2 to the power 1 is not that this 2 to the power 1 is not matching this 2 to the power force and matching this 2 to the power force and this is just an extra value which is this is just an extra value which is equal to the base so this has to be equal to the base so this has to be saved somewhere so let's save to 2 to saved somewhere so let's save to 2 to the power 1 somewhere right and let's the power 1 somewhere right and let's call it result call it result now once we get 2 to the power 4 like now once we get 2 to the power 4 like this can be written as 4 to the power of this can be written as 4 to the power of 4 isn't it now this 4 to the power 4 can 4 isn't it now this 4 to the power 4 can be again written as 16 to the power 2 be again written as 16 to the power 2 and again 16 to the power 2 will become and again 16 to the power 2 will become 256 to the power 1 so you will see that 256 to the power 1 so you will see that 256 is the final answer here and there 256 is the final answer here and there was something which was lost due to was something which was lost due to dividing an odd number by 2 and hence it dividing an odd number by 2 and hence it was saved in results so finally this 256 was saved in results so finally this 256 will be multiplied by this result will be multiplied by this result and it will become 512 and it will become 512 so you will see that there is only one so you will see that there is only one thing you need to take care of in case thing you need to take care of in case of the odd powers for even Powers uh of the odd powers for even Powers uh dividing by 2 actually doesn't make you dividing by 2 actually doesn't make you lose any power like any of the base lose any power like any of the base value and when the odd number comes like value and when the odd number comes like when the power is odd then you will when the power is odd then you will definitely lose one of the values okay definitely lose one of the values okay so that has to be saved somewhere and so that has to be saved somewhere and that is where uh the result actually that is where uh the result actually comes into picture comes into picture so let's take one of the problem and do so let's take one of the problem and do a dry run of the entire logic and then a dry run of the entire logic and then you will easily understand so the right you will easily understand so the right hand side is actually the entire code of hand side is actually the entire code of the logic which we discussed which is the logic which we discussed which is binary exponentiation binary exponentiation and on the left hand side let's take an and on the left hand side let's take an example 2 to the power 13 and by the way example 2 to the power 13 and by the way this technique is known as binary this technique is known as binary exponentiation binary because we are exponentiation binary because we are dividing by 2 and exponentiation because dividing by 2 and exponentiation because the base is exponentially increasing and the base is exponentially increasing and the steps are reduced to logarithmic the steps are reduced to logarithmic order right so let's just do a dry run order right so let's just do a dry run on this entire code so let's take the on this entire code so let's take the example of solving 2 to the power 13. so example of solving 2 to the power 13. so if you take 2 to the power 13 and let's if you take 2 to the power 13 and let's also take all the variables so the also take all the variables so the variables are result which is equals to variables are result which is equals to 1 and then you have a and b so a is 1 and then you have a and b so a is equals to 2 and B is equals to 13 right equals to 2 and B is equals to 13 right which is a to the power B format which is a to the power B format now in the first step you will see if B now in the first step you will see if B is greater than 0 so 2 to the power 13 is greater than 0 so 2 to the power 13 again it can be written as 2 to the again it can be written as 2 to the power 6 into 2 to the power 6 into 2 to power 6 into 2 to the power 6 into 2 to the power 1 now this has to be saved the power 1 now this has to be saved somewhere so definitely if B mod of 2 somewhere so definitely if B mod of 2 where B is 13 in this case right so if B where B is 13 in this case right so if B mod of 2 that means if B is a odd number mod of 2 that means if B is a odd number then definitely this 2 to the power 1 then definitely this 2 to the power 1 has to be saved in the result so this has to be saved in the result so this result will be multiplying to the power result will be multiplying to the power 1 and this will become 2. 1 and this will become 2. and in The Next Step you square the base and in The Next Step you square the base so the base will become 4 and the so the base will become 4 and the exponent will be halved so now the next exponent will be halved so now the next problem to be solved is 4 to the power problem to be solved is 4 to the power 6. now is this 6 an odd number you will 6. now is this 6 an odd number you will see that no it is not an odd number so see that no it is not an odd number so definitely you can write here 16 to the definitely you can write here 16 to the power 3 for this power 3 for this so what we are basically doing is just so what we are basically doing is just squaring the base and making the squaring the base and making the exponent go to half so now you have a exponent go to half so now you have a problem 16 to the power 3. so we can problem 16 to the power 3. so we can write 16 to the power 3 as 16 to the write 16 to the power 3 as 16 to the power 1 into 16 to the power 1 into 16 power 1 into 16 to the power 1 into 16 to the power 1 now these two can be to the power 1 now these two can be clubbed together and it can be written clubbed together and it can be written as 256 to the power 1 okay and this is as 256 to the power 1 okay and this is an extra value because the power was an an extra value because the power was an odd number now this has to be saved odd number now this has to be saved somewhere and and that will be saved in somewhere and and that will be saved in the result so you will be multiplying 16 the result so you will be multiplying 16 to the power 1 here and this will make to the power 1 here and this will make it 32 right it 32 right and now you have 256 to the power 1 you and now you have 256 to the power 1 you will see that again B greater than 0 is will see that again B greater than 0 is true and you will see that the power 1 true and you will see that the power 1 is odd so this 256 has to be multiplied is odd so this 256 has to be multiplied here and this will be present at this here and this will be present at this place and you will get the final result place and you will get the final result as as 8192 and again in The Next Step this 256 8192 and again in The Next Step this 256 will be squared up and this one will be will be squared up and this one will be halved so 1 by 2 will become 0 and so halved so 1 by 2 will become 0 and so the while loop will be breaking so the while loop will be breaking so whatever is saved in your result will be whatever is saved in your result will be returned and that will be 8192 and this returned and that will be 8192 and this will be your final answer will be your final answer so you can now calculate how many steps so you can now calculate how many steps did you take you will see that how a was did you take you will see that how a was growing so A's value became a square and growing so A's value became a square and then it became e to the power 4 and then it became e to the power 4 and again it was squared right so every time again it was squared right so every time you will see that the base was getting you will see that the base was getting squared up and the exponent was getting squared up and the exponent was getting hard so from B it turned out to be B by hard so from B it turned out to be B by 2 and again B by 4 and so on it went on 2 and again B by 4 and so on it went on until we reached to 1. you know that if until we reached to 1. you know that if we keep dividing a number by 2 the we keep dividing a number by 2 the number of steps will be log of B base 2 number of steps will be log of B base 2 exactly these many steps right so you exactly these many steps right so you now know what will be the total number now know what will be the total number of steps to solve a to the power B that of steps to solve a to the power B that will be order of log B right and since will be order of log B right and since we are always dividing by 2 hence the we are always dividing by 2 hence the name binary came and uh this is name binary came and uh this is logarithmic order or you can say base is logarithmic order or you can say base is exponentially increasing and that's why exponentially increasing and that's why the name binary exponentiation so even the name binary exponentiation so even if you go ahead and solve the problem if you go ahead and solve the problem power of X comma n in this case the x is power of X comma n in this case the x is given as double but still the code would given as double but still the code would exactly be the same so you can just go exactly be the same so you can just go ahead and try solving this problem it is ahead and try solving this problem it is a very important math algorithm problem a very important math algorithm problem if you like this video then please hit if you like this video then please hit the like button and subscribe to our the like button and subscribe to our channel in order to watch more of this channel in order to watch more of this programming video see you guys in the programming video see you guys in the next video thank you
2024-03-20 09:58:14
50
https://i.ytimg.com/vi_w…xresdefault.webp
Binary Exponentiation | Pow(x,n) | Leetcode #50
1GGAORO71g4
[Music] hello everyone hello everyone welcome to quartus camp we are a 27th welcome to quartus camp we are a 27th day of mail it goes challenge day of mail it goes challenge and the problem we are going to cover in and the problem we are going to cover in this video is maximum product of this video is maximum product of word length the input given here is a word length the input given here is a string array which consists of words string array which consists of words and we have to return the maximum and we have to return the maximum product product of any two words and the words should of any two words and the words should not have the same characters not have the same characters so let's understand this problem with an so let's understand this problem with an example so here is a given example if example so here is a given example if you observe the words they do not you observe the words they do not share the same characters are a b c w share the same characters are a b c w n foo is one pair so if you see the n foo is one pair so if you see the length of a b c w is four length of a b c w is four and the length of four is three that and the length of four is three that multiplies to twelve multiplies to twelve and next a b c w and and next a b c w and [Music] [Music] x t f n is also not having same x t f n is also not having same characters characters and again the product of the lengths of and again the product of the lengths of these two words are going to be 16 these two words are going to be 16 and the other words are ba z and the other words are ba z and x t f n and again the product is and x t f n and again the product is going to be 12. going to be 12. so out of all these combinations 16 is so out of all these combinations 16 is going to be the maximum value or going to be the maximum value or the product of these two words a b c w the product of these two words a b c w and x t f when they both have different and x t f when they both have different characters characters and the length equal to four each and if and the length equal to four each and if you multiply they both you multiply they both then it is going to be 16 and that is then it is going to be 16 and that is going to be an output so if you want to going to be an output so if you want to approach this problem in a brute force approach this problem in a brute force way then you are going to have way then you are going to have two for loops which is nested and they two for loops which is nested and they are going to compare are going to compare each word with every other word in the each word with every other word in the input and we are going to compare input and we are going to compare those two words that whether they have those two words that whether they have common characters or not common characters or not and if they have common characters then and if they have common characters then skip it if not skip it if not then multiply its value and have it in a then multiply its value and have it in a variable which compares every time and variable which compares every time and update it with the maximum value and update it with the maximum value and finally return the result finally return the result and that is actually going to take cubic and that is actually going to take cubic time that obviously going to do time that obviously going to do a time limit exceeded result so how do a time limit exceeded result so how do we approach this in an optimal way we approach this in an optimal way so there comes the help of bitwise so so there comes the help of bitwise so instead of instead of comparing each word with every other comparing each word with every other word and iterate word and iterate we are going to assign a integer value we are going to assign a integer value to each word in the given input to each word in the given input after assigning we are going to compare after assigning we are going to compare those values and those values and come up with a result so as i said we come up with a result so as i said we are going to are going to put an integer value to each word in the put an integer value to each word in the given input so how do we arrive at the given input so how do we arrive at the integer number integer number so first we are going to represent the so first we are going to represent the given word in form of binary given word in form of binary and then convert that binary number to and then convert that binary number to an integer number an integer number so consider our alphabet starting from a so consider our alphabet starting from a to z to z are going to point at each integer value are going to point at each integer value starting from 0 to 26 that is nothing starting from 0 to 26 that is nothing but a represent but a represent 0 b represent 1 and so on and is it 0 b represent 1 and so on and is it represent 26 represent 26 so we are going to have a 32-bit integer so we are going to have a 32-bit integer number number where we are going to fill the bits with where we are going to fill the bits with ones or zeros according to the character ones or zeros according to the character present present so let's start with the first word abc w so let's start with the first word abc w so we are going to fill in so we are going to fill in once at the character so a b c once at the character so a b c and w will be having once and all other and w will be having once and all other positions will be having positions will be having zeros so once we fill with ones and zeros so once we fill with ones and zeros it is representing a binary number zeros it is representing a binary number so if you convert this to an integer you so if you convert this to an integer you will get an integer value for example if will get an integer value for example if you convert this particular binary you convert this particular binary number to a decimal value number to a decimal value then for a b c w it will be converted to then for a b c w it will be converted to 4 1 9 4 1 9 4 3 double 1 some integer value which is 4 3 double 1 some integer value which is 32 bit integer 32 bit integer same way we are going to create these same way we are going to create these kind of integer values to kind of integer values to all other strings in the input for all other strings in the input for example for a second string example for a second string we will be having one set only b a we will be having one set only b a and z all others are going to be zeros and z all others are going to be zeros and and the same way we are going to assign an the same way we are going to assign an integer value to integer value to each number so the second step is once each number so the second step is once we we have our integer values ready we are have our integer values ready we are going to compare going to compare each integer value to arrive at our each integer value to arrive at our solution so the condition given here in solution so the condition given here in the problem statement is the problem statement is no two words should have common no two words should have common characters characters so as we are representing the words in so as we are representing the words in binary format we are going to perform an binary format we are going to perform an under operation between those binary under operation between those binary numbers numbers and if any number comes all 0 and if any number comes all 0 that means the words are not having that means the words are not having common characters common characters then we are going to perform the product then we are going to perform the product operation so just for a work around let operation so just for a work around let us consider we are having only four us consider we are having only four characters and we are representing that characters and we are representing that in a four in a four bits binary number so let's say our bits binary number so let's say our words are a b and c d words are a b and c d so in that case the first word is gonna so in that case the first word is gonna represent it as one one zero zero represent it as one one zero zero and the second word is gonna represent and the second word is gonna represent it as zero zero one one it as zero zero one one so if you perform an and operation to so if you perform an and operation to these two strings these two strings then it is gonna become all zeros then it is gonna become all zeros because because in and if there is one zero then it is in and if there is one zero then it is going to be zero in the solution going to be zero in the solution so as these are having zeros at all four so as these are having zeros at all four positions they are going to positions they are going to become all zeros so in that case we can become all zeros so in that case we can identify identify these two strings are not having common these two strings are not having common characters characters if suppose the words are a b and b c if suppose the words are a b and b c then in that case we will be then in that case we will be representing the numbers as 1 1 0 representing the numbers as 1 1 0 0 and 0 1 1 0 0 and 0 1 1 0 so if you perform and operation to 1 1 0 so if you perform and operation to 1 1 0 0 0 and 0 1 1 0 then in that case it is and 0 1 1 0 then in that case it is going to have going to have 0 1 0 0 which actually means we have 0 1 0 0 which actually means we have b in common between both the strings so b in common between both the strings so yes yes by doing these and operation we are by doing these and operation we are going to identify going to identify whether we are having common characters whether we are having common characters or not so if or not so if there is all zeros after performing and there is all zeros after performing and in that case these two words are not in that case these two words are not having common characters having common characters then we are going to perform then we are going to perform multiplication operation of multiplication operation of the words length and we are going to the words length and we are going to have a variable have a variable max which is going to hold the maximum max which is going to hold the maximum product product so far and return that as a result so so far and return that as a result so hope you are understanding this approach hope you are understanding this approach and we are going to iterate each string and we are going to iterate each string and and construct an integer value and then construct an integer value and then perform an end operation so that is perform an end operation so that is gonna take gonna take big o of n cross n time big o of n cross n time and overall it is going to work and we and overall it is going to work and we go of n square time complexity go of n square time complexity so let's go to code now so first let me declare integer array to store the integer values of each word let me name check and then variable max which is actually going to be a result and let us iterate each word and each so here x is nothing but we are so here x is nothing but we are converting that converting that character to an integer so that we will character to an integer so that we will convert it to a binary number so here convert it to a binary number so here we are going to have an integer value we are going to have an integer value num num which is going to be initialized for which is going to be initialized for every character as new every character as new variable for every string as a new variable for every string as a new variable variable and for that string we are going to and for that string we are going to convert it to a number so it is nothing but we have converted that character to a number so we are doing a one sh left shift x which we have already covered in the previous problem so if suppose we are converting b as our character then b's value must be two so if we are doing one shift then the binary number of one is going to be zero zero zero one then we are doing a left shift of two times then it is going to be represented as zero one 0 0 so this is nothing but representing so yes we converted that to a character so yes we converted that to a character and we are assigning and we are assigning that value to our that value to our array so yes this is done once our array is ready we are going to iterate through you so yes we are comparing the values and if it is 0 then we are computing our max you
2024-03-24 10:24:04
318
https://i.ytimg.com/vi_w…xresdefault.webp
Maximum Product of Word Lengths | LeetCode 318 | Coders Camp
e4LtiptjgxI
hi everyone we'll see about the today asteroid Collision problem that is ask asteroid Collision problem that is ask in many company okay let's start with in many company okay let's start with the problem and the question is given the problem and the question is given you are given an asid of integer you are given an asid of integer representing the asid in a row and for representing the asid in a row and for each estro the absolute value represent each estro the absolute value represent size and the sign represented Direction size and the sign represented Direction and it is will be like posi Direction and it is will be like posi Direction and and The each asteroid move in the same speed The each asteroid move in the same speed find out the state of the asteroid all find out the state of the asteroid all the collision and if the two esto made the collision and if the two esto made the smaller one will explode if both are the smaller one will explode if both are same size both will explode and the two same size both will explode and the two asid moving in the same direction will asid moving in the same direction will never so this is the proper condition never so this is the proper condition which we have to be keep in mind while which we have to be keep in mind while creating the condition while creating creating the condition while creating the code for that first of all what they the code for that first of all what they are given they have a SES it will be are given they have a SES it will be positive or maybe negative okay then positive or maybe negative okay then they are giving they are moving in the they are giving they are moving in the same there a condition like uh what is same there a condition like uh what is the condition which we have to maintain the condition which we have to maintain if there's a condition like they are if there's a condition like they are given uh if two estro meet the smaller given uh if two estro meet the smaller one will explode it means one will explode it means if if we have a two plus one and minus if if we have a two plus one and minus one like plus a minus B if some some one like plus a minus B if some some reason one of the number is like anyhow reason one of the number is like anyhow one of the reason is one of the number one of the reason is one of the number is bigger so the smaller number will uh is bigger so the smaller number will uh get slow over there I can say and second get slow over there I can say and second condition they are given if both are the condition they are given if both are the same size both will and third condition same size both will and third condition like two asid moving in the same like two asid moving in the same direction will never obviously if both direction will never obviously if both have plus plus sign then they will never have plus plus sign then they will never Collide if one of them plus and one of Collide if one of them plus and one of them minus like one is coming and one is them minus like one is coming and one is going then they will explode otherwise going then they will explode otherwise not so coming to the input what they not so coming to the input what they given basis on that we can map the given basis on that we can map the condition or check the condition here condition or check the condition here asid equal to 5 comma 10 commus 5 so asid equal to 5 comma 10 commus 5 so first we will check both are which how first we will check both are which how much how much element we have which we much how much element we have which we can say it never Collide because of the can say it never Collide because of the same charges or same direction so you same charges or same direction so you can see we are When comparing 5 comma 10 can see we are When comparing 5 comma 10 it both both number holding the positive it both both number holding the positive number positive direction so it will number positive direction so it will never meet second come to the 10 minus 5 never meet second come to the 10 minus 5 then they are given if both of the then they are given if both of the number have one of the plus one of the number have one of the plus one of the minus and one of them get explode and minus and one of them get explode and that is which number get explode I can that is which number get explode I can say which is a smaller one so if you can say which is a smaller one so if you can say 10 and minus 5 colide resulting in say 10 and minus 5 colide resulting in 10 because it already mentioned like if 10 because it already mentioned like if toid me the smaller one will explode toid me the smaller one will explode like coming from the 10 and minus and like coming from the 10 and minus and minus one is like less one that's why it minus one is like less one that's why it will collide and when we are comparing will collide and when we are comparing five and 10 then they are never get five and 10 then they are never get Collide Collide so that's why the our output will be a 5 so that's why the our output will be a 5 comma comma 10 the from the 10 and five we are 10 the from the 10 and five we are getting the 10 and from the five and 10 getting the 10 and from the five and 10 we are they never Collide that's why we we are they never Collide that's why we are uh taking the five from there okay similarly for the second condition 8A 8 minus8 they are having a both number same and both number having charges so they will exclude thir we have input like 10A 2us 5 in this also we can compare as a previous one 2 and minus 5 when we are comparing it will be giving the result in minus 5 because as already mentioned you both are holding the sorry one of the like different different direction one is positive and one is negative so get smaller will be get discl explod I can say and when coming to the like 10 andus 5 when we comp 2 five 10 and five so in the 10 and five again it will be getting the 10 because minus 5 is a smaller number so 10 and the constant here given this 10 and the constant here given this asteroid length between the 2 to 10 asteroid length between the 2 to 10 power 4 10 to this 1,00 to 1,00 positive power 4 10 to this 1,00 to 1,00 positive then it not be equal to to Zer yeah then it not be equal to to Zer yeah obviously if it will be zero then why we obviously if it will be zero then why we will check the charges and explore the will check the charges and explore the conditions okay so this is the uh conditions okay so this is the uh problem which we have to be uh solve problem which we have to be uh solve okay so I have the code I just have to okay so I have the code I just have to be write be write and apply the same thing here what we and apply the same thing here what we discuss here as a okay so coming to the discuss here as a okay so coming to the coding part uh first of all what we have coding part uh first of all what we have asroy input error so we are taking one asroy input error so we are taking one of that in the list okay then we are of that in the list okay then we are checking like how much time or how many checking like how much time or how many time we can iterate or we can check that time we can iterate or we can check that values which is containing in Theo input values which is containing in Theo input it is positive negative same direction it is positive negative same direction different Direction when they meet when different Direction when they meet when they not they not meet like that so yeah I just created meet like that so yeah I just created the one of the list for keeping all the the one of the list for keeping all the asteroids and getting the one of the I asteroids and getting the one of the I variable for checking like the count variable for checking like the count which we have from this resulted input which we have from this resulted input from resulted estro so you can see I from resulted estro so you can see I applied the uh loop until the our count applied the uh loop until the our count will be lie between less than count like will be lie between less than count like this asteroid count till that till that this asteroid count till that till that count we can iterate okay first count we can iterate okay first condition we can see asteroid of sorry condition we can see asteroid of sorry result of I greater than zero because it result of I greater than zero because it is given in the condition it will not is given in the condition it will not equal to zero so always it will be equal to zero so always it will be greater than it will be like obviously greater than it will be like obviously uh zero Val not containing but yeah we uh zero Val not containing but yeah we have this minus to+ one range so we have have this minus to+ one range so we have to check like greater than Z or less to check like greater than Z or less than Z so first of all Weck from the than Z so first of all Weck from the first greater than positive number first greater than positive number purpose so if result of I greater than Z purpose so if result of I greater than Z and this count is Li between from Z to and this count is Li between from Z to like the number what we are iterating like the number what we are iterating from that number to end of that and from that number to end of that and third condition we can check our next third condition we can check our next element is also less than zero like it element is also less than zero like it will be like condition checking when we will be like condition checking when we have a condition to collide each other have a condition to collide each other like one is positive and one is negative like one is positive and one is negative you can see result of I + 1 is less than you can see result of I + 1 is less than zero and this number is result. Count zero and this number is result. Count minus one will be a less than from minus one will be a less than from so what we can see we can take those so what we can see we can take those number those two number in the this asid number those two number in the this asid one and asid two variable and taking the one and asid two variable and taking the absolute value from there and and then absolute value from there and and then we are comparing which one is a smaller we are comparing which one is a smaller which one is a greater because of that which one is a greater because of that we have to be explode so if you can see we have to be explode so if you can see we have when asteroid one is greater we have when asteroid one is greater comparing to asteroid 2 so we have to be comparing to asteroid 2 so we have to be remove the asteroid remove the asteroid 2 because as already mentioned in the 2 because as already mentioned in the question if one of them uh like one question if one of them uh like one number is greater one number is smaller number is greater one number is smaller then the smaller number will get expl so then the smaller number will get expl so I + one is containing the smaller number I + one is containing the smaller number comparing to aoid one so it will be comparing to aoid one so it will be getting explod and it will continue for getting explod and it will continue for moving the next next element so that's moving the next next element so that's why we are skipping that part and why we are skipping that part and removing that position and then again removing that position and then again continue second condition as we continue second condition as we mentioned asteroid 1 is always less than mentioned asteroid 1 is always less than asteroid 2 here we are checking it is asteroid 2 here we are checking it is greater than sometime it like our first greater than sometime it like our first value Also may be negative comparing to value Also may be negative comparing to the second one so who will be a less one the second one so who will be a less one we have to remove so if we are we have to remove so if we are conditioning like aoid one is less than conditioning like aoid one is less than asid 2 it means we are getting I + one asid 2 it means we are getting I + one value here from this and I value from value here from this and I value from here I can say so we can remove that here I can say so we can remove that position number so that's why we are position number so that's why we are removing and last one we have if nothing removing and last one we have if nothing like we are having a same same then they like we are having a same same then they are never never get Collide so that's are never never get Collide so that's why you can see it will be like greater why you can see it will be like greater than smaller than and equal to case all than smaller than and equal to case all the three cases we are handled here and the three cases we are handled here and in the last part we are just removing in the last part we are just removing remove um that next position current remove um that next position current position position also and last we are checking if our also and last we are checking if our number I is greater than number I is greater than zero then we have to be decrement zero then we have to be decrement otherwise we have to be maintain the I otherwise we have to be maintain the I and continue and after each iteration we and continue and after each iteration we are maintaining the I counter for the are maintaining the I counter for the tracking purpose so it will be A++ plus tracking purpose so it will be A++ plus and again we are returning the end of and again we are returning the end of that result of array that result of array so it it is containing like how much so it it is containing like how much number we have which is not collide number we have which is not collide which is preventing from the explod I which is preventing from the explod I can say so uh we are using the result uh for storing that so storage will be a big often and for time complexity I can say we are taking the length of input from the destroid so it will be a biger of so let's uh we can uh run it is getting exploded just checking the it is getting exploded just checking the condition condition okay if we can say we have a both number okay if we can say we have a both number same then it will never collide condition okay uh when we have a same condition okay uh when we have a same number number uh what I can 5 five with the same we uh what I can 5 five with the same we will run [Music] yeah so if you are taking the same yeah so if you are taking the same number with the same charges or same number with the same charges or same direction uh so they will never explode direction uh so they will never explode and both number is same that's why we and both number is same that's why we are returning also the same both number are returning also the same both number so that's it for this today hope you so that's it for this today hope you like this meet you in the next video like this meet you in the next video thank
2024-03-21 11:55:35
735
https://i.ytimg.com/vi/e…xI/sddefault.jpg
Asteroid Collision | Leetcode 735
3jvWodd7ht0
everyone welcome back and let's write some more neat code today some more neat code today so today let's look at a problem so today let's look at a problem palindrome partitioning palindrome partitioning so we're given a string s and we want to so we're given a string s and we want to partition it in such a way that partition it in such a way that every single sub-string of the partition every single sub-string of the partition is a palindrome and we want to return is a palindrome and we want to return all all possible ways that we can partition it possible ways that we can partition it in in like by following this rule and if you like by following this rule and if you don't remember a palindrome is basically don't remember a palindrome is basically a string a string that if you reverse it it's the exact that if you reverse it it's the exact same string same string so one thing to notice is no matter what so one thing to notice is no matter what string we're given it's string we're given it's possible to partition it in this way why possible to partition it in this way why is that the case is that the case because in this case we have a a b because in this case we have a a b we know that any any single character we know that any any single character like like a is a palindrome right if you reverse a a is a palindrome right if you reverse a you get a you get a any character including b is a any character including b is a palindrome right palindrome right reverse it you get b so one way to reverse it you get b so one way to partition this is take partition this is take each character and separate it right and each character and separate it right and that's what the first partition over that's what the first partition over here is right each character by itself here is right each character by itself so are there any other ways to partition so are there any other ways to partition this other than just this other than just this single way well if you take the this single way well if you take the first two characters first two characters you see that that is also a palindrome you see that that is also a palindrome right a right a a reversa is still a a and of course b a reversa is still a a and of course b by itself we know any single character by itself we know any single character is definitely a palindrome is definitely a palindrome so for the second partition we'll have so for the second partition we'll have two sub strings right two sub strings right a and b so then this is our result a and b so then this is our result because we cannot have any other sub because we cannot have any other sub strings that are phalan drums right strings that are phalan drums right a b is not a palindrome if you reverse a b is not a palindrome if you reverse it we get b a that's not the same string it we get b a that's not the same string if you take this and you reverse it you if you take this and you reverse it you get b a get b a a that's not a palindrome so the brute a that's not a palindrome so the brute force way in this case force way in this case to solve this problem happens to also be to solve this problem happens to also be the main way to solve this problem which the main way to solve this problem which is is backtracking so we are going to use backtracking so we are going to use backtracking to solve this problem and backtracking to solve this problem and what we're going to do is create what we're going to do is create every single possible way we could every single possible way we could partition this partition this and then check if those partitions form and then check if those partitions form palindromes and if they do we are going palindromes and if they do we are going to add them to our to add them to our result list right because ultimately we result list right because ultimately we want to re want to re we want a list that has every single way we want a list that has every single way to partition this to partition this while maintaining palindromes so for the while maintaining palindromes so for the first first partition we have three choices do you partition we have three choices do you see what they see what they are if we want a first partition well are if we want a first partition well the first partition can either be a by the first partition can either be a by itself right itself right so a by itself which is if we just took so a by itself which is if we just took the first the first character and said that that was one character and said that that was one partition another partition another partition is double a right if we just partition is double a right if we just took the first two characters took the first two characters as our first partition or the last one as our first partition or the last one obviously if we just took the entire obviously if we just took the entire string as our first partition string as our first partition now we will check is this a palindrome now we will check is this a palindrome how are we going to check well we can how are we going to check well we can start comparing the first start comparing the first and last characters right and we see and last characters right and we see that well they're not even equal that well they're not even equal right so this is not a palindrome so right so this is not a palindrome so we are not going to continue on this we are not going to continue on this branch branch or on this path for our depth for search or on this path for our depth for search tree but we know that this tree but we know that this by itself is a palindrome right so this by itself is a palindrome right so this is going to be our first partition now is going to be our first partition now we're going to take the remaining we're going to take the remaining characters characters a and b and try to partition them a and b and try to partition them right so for one partition of those right so for one partition of those remaining characters we could get a remaining characters we could get a single a if we took this first one single a if we took this first one another partition we could get another partition we could get is a b if we took is a b if we took both of these characters but we look at both of these characters but we look at the first character and last character the first character and last character this is not a palindrome this is not a palindrome this is a palindrome but this is not a this is a palindrome but this is not a palindrome palindrome so we don't have to continue on this so we don't have to continue on this path and from path and from here we know we already took the first here we know we already took the first two characters as our first partition two characters as our first partition so we only have one choice for our so we only have one choice for our second partition second partition and that's just the character b and we and that's just the character b and we know a single character by itself know a single character by itself does form a partition and we also know does form a partition and we also know that we have no more remaining that we have no more remaining characters right we already took the characters right we already took the first three characters first three characters so what this tells us is this is one so what this tells us is this is one possible way to partition possible way to partition to make sure that all the substrings are to make sure that all the substrings are palindromes right both of these palindromes right both of these substrings are palindromes so this is substrings are palindromes so this is one possible uh solution so now the only one possible uh solution so now the only path for us to continue we can't do this path for us to continue we can't do this and we can't do this and we can't do this and we cannot do this anymore we don't and we cannot do this anymore we don't have any more characters have any more characters so we can continue this one how many so we can continue this one how many choices do we have well we took the choices do we have well we took the first two a's first two a's right so now we only have one choice and right so now we only have one choice and that's going to be the b that's going to be the b so we for our third partition in so we for our third partition in this line is going to be b so this one this line is going to be b so this one had had two uh partitions right two strings two uh partitions right two strings this one has three and all of them this one has three and all of them happen to be palindrome so this is happen to be palindrome so this is also a possible solution so that's how also a possible solution so that's how you basically solve this problem you basically solve this problem with backtracking it's not super with backtracking it's not super efficient right it's going to be at efficient right it's going to be at least 2 to the power of least 2 to the power of n because we're brute forcing it but now n because we're brute forcing it but now let me show you the code let me show you the code so let's have our result this is what's so let's have our result this is what's going to store all of the partitions going to store all of the partitions that we that we create all the possible partitions let's create all the possible partitions let's also have also have a variable called part this is this a variable called part this is this basically stands for partitions this is basically stands for partitions this is our our current partition right so if our current partition right so if our current partition happens to be current partition happens to be this this is just going to be the single this this is just going to be the single partition the result is going to be what partition the result is going to be what stores the partitions right so this will stores the partitions right so this will possibly have you know multiple possibly have you know multiple partitions in it partitions in it and now i'm going to create a nested and now i'm going to create a nested function depth first search for function depth first search for our br our backtracking the only thing our br our backtracking the only thing i'm going to pass into it is i the index i'm going to pass into it is i the index of the character of the character we're currently at and so since this we're currently at and so since this function is function is nested inside this function these two nested inside this function these two variables as well as variables as well as s the string are going to be accessible s the string are going to be accessible in this even if we don't pass them into in this even if we don't pass them into it it so since this is a recursive function so since this is a recursive function first thing we check is the base case so first thing we check is the base case so if i if i happens to be out of bound so if it's happens to be out of bound so if it's greater than or equal to the length of greater than or equal to the length of the input string the input string s what are we going to do well in that s what are we going to do well in that case case the same thing that we did over here the same thing that we did over here right we knew that we had right we knew that we had our a valid partition and we had no more our a valid partition and we had no more characters to add so in that case we characters to add so in that case we know that this know that this is a possible solution so what i'm going is a possible solution so what i'm going to do here is basically to our result to do here is basically to our result i'm going to append the current i'm going to append the current partition that we have formed partition that we have formed but not only that i'm going to clone it but not only that i'm going to clone it because we know because we know or rather i'm gonna copy it because we or rather i'm gonna copy it because we know if we end up know if we end up in a different recursive call making in a different recursive call making changes to this variable there's only changes to this variable there's only one part partition variable so it's not one part partition variable so it's not like there are multiple like there are multiple partitions being created we only have a partitions being created we only have a single one so every time single one so every time we append to result we have to make a we append to result we have to make a copy of it copy of it and after we do that we can return and after we do that we can return because this is our base case because this is our base case if we haven't reached the last index if we haven't reached the last index what can we do well we can iterate what can we do well we can iterate through through every other character in our string every other character in our string right so right so we're going to start at i and keep going we're going to start at i and keep going until we get to the until we get to the end of the string and end of the string and for this meaning so this is going to be for this meaning so this is going to be our sub string right this is our sub string right this is every possible substring and we want to every possible substring and we want to know is it a palindrome know is it a palindrome so so the indices are going to tell us so so the indices are going to tell us if if from a string s starting at index i all from a string s starting at index i all the way to j the way to j we're going to check every possible we're going to check every possible string i'm going to add one to j string i'm going to add one to j to get rid of the off by one error and i to get rid of the off by one error and i want to want to know is this a string is this a know is this a string is this a palindrome palindrome i'm also going to pass in the indices i i'm also going to pass in the indices i and j and j so we know what our left and right so we know what our left and right boundaries are and actually since we are boundaries are and actually since we are passing in these passing in these boundaries we don't actually need to boundaries we don't actually need to create a substring we can just pass create a substring we can just pass s itself so we want to know is s a s itself so we want to know is s a palindrome if you take it palindrome if you take it to start at index i and end at index to start at index i and end at index j is this a palindrome and so if it j is this a palindrome and so if it happens to be a palm drum i'll actually happens to be a palm drum i'll actually write this helper function later we'll write this helper function later we'll just assume we have it now so if this just assume we have it now so if this happens to be a palindrome what can we happens to be a palindrome what can we do do we can to our partition we can add this we can to our partition we can add this string so s from index i string so s from index i to index j get rid of the off by 1 error to index j get rid of the off by 1 error we can add this we can add this so this is our current partition and we so this is our current partition and we want to keep want to keep because we know s this substring is a because we know s this substring is a palindrome palindrome and so now we can recursively do our and so now we can recursively do our depth first search depth first search looking for additional palindromes and looking for additional palindromes and of course we'll start at j of course we'll start at j plus one because that's going to be the plus one because that's going to be the next next character and after we do our recursive character and after we do our recursive function we have to clean function we have to clean up so since we know we only have one up so since we know we only have one single partition variable single partition variable after we have added this and added the after we have added this and added the substring and then ran our debt for substring and then ran our debt for search search looking for all possible additional looking for all possible additional partitions partitions after that we can take the string that after that we can take the string that we just added over here and then pop we just added over here and then pop that from our partition list and that's that from our partition list and that's actually our entire actually our entire depth for search function you notice we depth for search function you notice we have our base case when we go out of have our base case when we go out of bounds bounds and with this loop we are generating and with this loop we are generating every single possible substring right every single possible substring right from i to j from i to j we're checking if it's a palindrome if we're checking if it's a palindrome if it is then we're recursively continuing it is then we're recursively continuing our depth for search our depth for search if it's not a palindrome then we're just if it's not a palindrome then we're just skipping that substring altogether and skipping that substring altogether and going to the next going to the next iteration of the loop so that's our iteration of the loop so that's our entire function and the only thing left entire function and the only thing left for us to do is to actually for us to do is to actually call it so debt for search will pass in call it so debt for search will pass in zero because we know that's the start zero because we know that's the start index index and then what we're going to do is and then what we're going to do is return result return result and before i forget we know we have to and before i forget we know we have to actually write this helper function that actually write this helper function that we called before we even wrote it so we called before we even wrote it so let's write that really quickly is let's write that really quickly is palindrome palindrome it'll accept a string and it'll accept it'll accept a string and it'll accept left and right boundaries so we just left and right boundaries so we just have to check if it's a palindrome have to check if it's a palindrome so while left is less than right so while left is less than right we'll check if the character at the left we'll check if the character at the left position position doesn't equal the character at the right doesn't equal the character at the right position that means position that means it's not a palindrome so we can return it's not a palindrome so we can return false if it false if it if they are equal then we can update our if they are equal then we can update our left and right pointer so add one to left and right pointer so add one to left left and subtract one from the right pointer and subtract one from the right pointer and if this loop this entire loop and if this loop this entire loop executes and all the characters actually executes and all the characters actually were equal were equal then we'll exit the loop and then we can then we'll exit the loop and then we can return true because that means it return true because that means it is a palindrome and now let me just run is a palindrome and now let me just run it to prove to you that it works it to prove to you that it works and hopefully it's somewhat efficient and hopefully it's somewhat efficient yep it runs perfectly and yep it runs perfectly and it is pretty efficient so i hope this it is pretty efficient so i hope this was helpful was helpful if you enjoyed please like and subscribe if you enjoyed please like and subscribe it supports the channel a lot and i'll it supports the channel a lot and i'll hopefully hopefully see you pretty soon
2024-03-21 11:44:24
131
https://i.ytimg.com/vi_w…xresdefault.webp
Palindrome Partitioning - Backtracking - Leetcode 131
LUqNE7bD48w
hey what's up guys this is john here so uh today i'd like i'd like to talk so uh today i'd like i'd like to talk about this about this 174 dungeon game 174 dungeon game i think this is very interesting like i think this is very interesting like problem problem okay so let's take a look uh the blah okay so let's take a look uh the blah blah blah there's a dungeon blah blah there's a dungeon and there there's a nat knight and and there there's a nat knight and there's a trapped princess there's a trapped princess okay and the 2d dungeon here okay and the 2d dungeon here so you know at so the knight starts so you know at so the knight starts at top left corner and at top left corner and the trapped princess where the the trapped princess where the imprisoned prince princess imprisoned prince princess is located on the on the bottom right is located on the on the bottom right corner corner and on each of the cell here there's a and on each of the cell here there's a like like a house where there's like a a house where there's like a you know there's a magic orbs you know there's a magic orbs or there's a trap okay basically or there's a trap okay basically the negative numbers means that so the the negative numbers means that so the knight will lose this number of health knight will lose this number of health and the positive numbers that you know and the positive numbers that you know the knight will will gain like the knight will will gain like additional additional this number of health okay and the this number of health okay and the problem is asking you to and problem is asking you to and also of course the knight can only move also of course the knight can only move to the right or to the right or right or down down below and it asks you right or down down below and it asks you to find the what's the minimum to find the what's the minimum initial house the knights must have initial house the knights must have to be able to for the knight to be able to be able to for the knight to be able to reach to the uh to reach to the uh to the princess and remember so the to the princess and remember so the knight has to keep knight has to keep his health at least one at each of the his health at least one at each of the step here step here okay so for example this one okay so for example this one for example this one the knight i mean for example this one the knight i mean it gives you an example here so the the it gives you an example here so the the minimum minimum the minimum house the knight needs to the minimum house the knight needs to have is seven have is seven which means that you know at with seven which means that you know at with seven here so the knight here so the knight uh at at the first step the house uh at at the first step the house becomes a five becomes a five okay and then he he cannot go down right okay and then he he cannot go down right because when because when if he goes down he dies okay so he has if he goes down he dies okay so he has to go right to go right so now now his house becomes to two so now now his house becomes to two and then he keep going right because if and then he keep going right because if he goes down he dies too he goes down he dies too okay so here he his his house okay so here he his his house uh became to okay becomes to five uh became to okay becomes to five and then he goes down here the house and then he goes down here the house becomes to becomes to six and then finally the house six and then finally the house is one okay it has to be one remember it is one okay it has to be one remember it cannot be five here cannot be five here otherwise you know even though he otherwise you know even though he managed managed to he managed to to meet the princess to he managed to to meet the princess but he already died but he already died the the minute he entered this this the the minute he entered this this final cell here okay final cell here okay that's why the final answer is seven that's why the final answer is seven okay okay okay so i mean at the beginning okay so i mean at the beginning at the first glance right i mean it's at the first glance right i mean it's not it's i think it's pretty obvious not it's i think it's pretty obvious right this one is like a dv problem right this one is like a dv problem basically you you just need to find the basically you you just need to find the uh uh at each of the this the step here right at each of the this the step here right you have to gather from the two you have to gather from the two directions and then directions and then you're trying to get the minimum at the you're trying to get the minimum at the minimum house or the maximum minimum house or the maximum value out from it but the tricky part value out from it but the tricky part for this problem is that for this problem is that if you do it from top down okay if you do it from top down okay basically if you start from bottom from basically if you start from bottom from the the top the the top left corners and then you're trying to left corners and then you're trying to follow follow his like step like this you will his like step like this you will not get the correct answer with a one not get the correct answer with a one pass of dp pass of dp so why is that it is because you know it so why is that it is because you know it asks you to find the minimum asks you to find the minimum health right starting at this point health right starting at this point starting at zero zero point starting at zero zero point which we have no ideas okay so which which we have no ideas okay so which means means if we start from this moment here okay if we start from this moment here okay and we have minus two here and we have minus two here so what are we what's our initial so what are we what's our initial what's our initial health we don't know what's our initial health we don't know right let's say if we don't care right let's say if we don't care if let's say we just have minus two here if let's say we just have minus two here it means that it means that we're assuming the night uh the knight we're assuming the night uh the knight will have have like zero zero health will have have like zero zero health okay okay and then we're trying to see okay by the and then we're trying to see okay by the end if when he reached to the end end if when he reached to the end what's that basically what's the what's that basically what's the the maximum health he needs to get okay the maximum health he needs to get okay but that's basically but that's basically with one set of the with one part of the with one set of the with one part of the dp there's no way we can solve that dp there's no way we can solve that because we don't know because we don't know what's what's going to be after that so i mean the best answer for this problem is that we do it from from this cell from the bottom right corner and we're going back we're going backwards so why this why this one works because you know if we do it backwards right i mean we know we have seen so we have seen that the last all the cells we we need right we just all the cells we we need right we just we just solve it backwards we just solve it backwards for example here right at this moment at for example here right at this moment at this this either target what's the minimum either target what's the minimum what's the minimum we need at this cell what's the minimum we need at this cell it's the uh it's one minus the it's the uh it's one minus the the dungeon the the the values in in the dungeon the the the values in in this dungeon right this dungeon right basically one minus minus five which is basically one minus minus five which is six six basically we need six to get here uh to be survived to be able to survive here okay and then we're just going backwards so now we have to to get to this last place here we have two ways of getting here right the first one is from up there and uh the other one is from from left so how many we need how many health we need if we choose from this from this path here we need five we will need five i think okay yes we need five to be able to to get to six right because we have one here right and that that that's why we need five here how about here how many uh house we need to be to how many uh house we need to be to from from this side only one right from from this side only one right to get here of course i mean we have to to get here of course i mean we have to be the the minimum house we need for be the the minimum house we need for each cell is one each cell is one but things we we're gonna charge but things we we're gonna charge we're going to charge 30 more health we're going to charge 30 more health here that's why i mean all we here that's why i mean all we all we just you do need to have one here all we just you do need to have one here okay to be able to to get to here okay to be able to to get to here okay and then how about here how about okay and then how about here how about the minus 10 here um you know let me go back here let let me you know let me go back here let let me follow the original step here so we have follow the original step here so we have five here five here and then how about here how many we need and then how about here how many we need we need we need two here we need we need two here we need two here and then we we need five here right we need five we we need five here right we need five to get two through here that's why we to get two through here that's why we have five here have five here and then from here we have seven okay and then from here we have seven okay right so how how about how about this one here right i mean as you guys can see we need we need one or five from this one so we choose this one but here uh we need like uh 11 right to be able to get to here because we need to be we need to survive here first that's why we need 11 here how about this one here we we this is also one here okay and how about here we need like uh we need six here right we need six here because you know from one because here we have one here so we have eleven but we need at least six to survive here so among this five and six here we will choose five because we we know okay five is it's smaller than six that's why we have seven here okay as you guys can see you if we do it reversely from the the from the bottom right corner backwards to the beginning and then we we can certainly find our our correct answer because we have already seen okay so with that being said let me try okay so with that being said let me try to code this one here so we need the to code this one here so we need the amount in here amount in here the dungeon dungeon and n is the length of the uh sorry zero okay uh sorry zero okay and then for we need a dp here right the and then for we need a dp here right the dp is dp is like uh since we're getting the minimum like uh since we're getting the minimum we're getting the minimum from the two we're getting the minimum from the two of them so to be able to of them so to be able to handle the corner case we need to handle the corner case we need to initialize initialize them to the maximum size okay this is like n plus one because we'll handle this like the corner case right in range m plus one okay here okay so and so for i in range like uh m minus one minus one minus one like since we're starting from the bottom right corner and the same thing for the j for j okay n minus one minus one minus one okay so and i think we have to uh we since you know our our normal case is like this it's a like dp uh i j uh equals to the what the minimum right the minimum of the uh the minimum of dp are i minus one j and dp i j minus one and then we minus the uh the the current dungeon value okay and then in the end here right i okay and then in the end here right i mean basically mean basically we need to have at least a one here we need to have at least a one here basically what we are saying here let's basically what we are saying here let's say we have six here we have a six say we have six here we have a six uh we have six right and then uh we have six right and then we have like five here right we have we have like five here right we have five here five here and then we have uh one here and then we have uh one here okay remember so the the way we're okay remember so the the way we're getting this 11 here is that you know getting this 11 here is that you know we are we're using the minimum right we are we're using the minimum right from the previously one and we we minus the uh okay we minus the uh okay let's see minimum of this oh sorry plus okay this would be a plus one and j plus one okay since we're going and yeah sorry okay i what i mean here so how do we get one here right so i mean we as you guys can see if we use this one here right i mean the minimum of this one is six right six minus six minus uh 30 right six minus 30 is what is like minus 24 right which means the the magic orbs here is is too much for us right so which means that we don't need that much basically if dp i and j is small equal smaller than zero then we know that okay we just need like one here because we know that at this at this cells they're like way too many way too many like uh magic orbs we uh then we need so all we need is we just need one house to be able to get here okay but as you guys can see we we do a minimum of this one here right and the the base case is the is the the princess right so here we have to do a special check here basically if the i is equal to uh m minus one and j equals to the n minus one otherwise since we initialize everything with the the max size value here we're gonna have like maximum size here okay which will be a the wrong answer for the first first element here that's why i mean for for the last one uh equals to what equals one minus okay uh equals to what equals one minus okay because we we know we need at uh at because we we know we need at uh at least least basically this is our this is our base basically this is our this is our base case we need one case we need one house to be survived here that's why we house to be survived here that's why we need need like this one minus that like this one minus that else how's this else how's this okay of course we have to do the same okay of course we have to do the same thing for this for both cases thing for this for both cases okay so that we can just reduce this uh okay so that we can just reduce this uh unnecessary orbs to to just one here unnecessary orbs to to just one here and in the end we simply return like dp and in the end we simply return like dp 0 sorry 0 and 0. 0 sorry 0 and 0. yeah i think that's it submit yeah cool so it passed right i mean so i mean the time complexity of course is like uh of m m and n right m times n and the space complexity is also o of m time times n uh yeah i mean this one is not i mean for to think it back backwards it's a little bit like tricky but okay so next someone might have asked but it's some for some people it's not that easy to think it backwards right how what if we really try to solve it from from top left to bottom right can we solve it i mean the answer is yes but to do that right like like i said we don't we didn't know the we didn't know the if we do it from the top left to the bottom right we didn't know the uh the what was the answer so we couldn't solve it in one pass so what what can we do we have to do a binary search so what does it mean it means that we try all the possible we try to all the possible initial we try to all the possible initial health and then we do a binary search health and then we do a binary search and then we we find the minimum value and then we we find the minimum value that satisfies that's the that satisfies that's the the knight can still survive to get to the knight can still survive to get to the to the princess okay um okay let's try to do that okay since it's it's gonna be fun all right even though it's not the optimal solutions but i think it's worth mentioning here okay so sorry to do that right for the binary search like always we need to find the the left and and the right boundaries so what's the left boundary the left boundary is one that's that's going to be our minimum health but how about the the right how about the right boundary so the right boundary is the uh so the right boundary is the uh you know it's the the total sum of all you know it's the the total sum of all the negative numbers the negative numbers that's going to be our our right that's going to be our our right boundaries because you know boundaries because you know if we have the the length uh have all if we have the the length uh have all the uh of all the the negative numbers that's going to be our can cover all the negative numbers here it's guaranteeing that i mean the knight can reach the the final the the princess right basically that's the uh that's gonna be our uh that's gonna be our uh right boundaries here so basically i'm just going to do a a simple for loop here okay and that's the for loop to find all the negative numbers okay and if the uh the dungeon right d u n g eo and i j is smaller than zero okay and then right uh plus minus dungeon okay yep i think that's that but is that the answer probably not right i think we have to start it we have to initialize it with one so why is that because we remember even with the right boundaries we after all the summarizing all the negative numbers that that's gonna like like counterparts all the negative numbers but the knight still needs one one house to be survived to be able to survive that's why we need uh starting from one okay okay and then now the next one is the the binary search template okay so like always so we have a middle here right the left plus right minus left divided uh divided by two we do a right minus the left just to be to avoid the overflow okay and then so our next one is going to be our halper functions so basically where in this case is can survive right can survive can survive with this middle health if it can okay so now it's the part for the binary search since we're we're trying to find the minimum value okay so the minimum so for remember this so every time when you guys need to find the minimum values you always do uh if it satisfy the current conditions you set the right to the mid middle and is the middle plus one so the reason is the middle plus one so the reason being is that you know being is that you know uh with the left and right okay with the uh with the left and right okay with the left left and the right since we're getting trying and the right since we're getting trying to find the minimum values to find the minimum values basically we're trying to shrink the the basically we're trying to shrink the the right right the right pointer as as the right pointer as as as to the left as possible and the as to the left as possible and the reason we're reason we're doing the equal here is because it's doing the equal here is because it's because since the middle satisfy our because since the middle satisfy our conditions right conditions right i mean the middle could be our answer so i mean the middle could be our answer so that's why we cannot do a middle that's why we cannot do a middle minus one and we have to do a we have to minus one and we have to do a we have to include the middle include the middle and then but we are trying to shrink and then but we are trying to shrink this right to the left this right to the left until we we until we cannot shrink it until we we until we cannot shrink it anymore then either the left and right anymore then either the left and right is our answer is our answer okay and and as for the okay and and as for the for the for the false for the the other for the for the false for the the other branches here since we we know okay branches here since we we know okay we cannot it cannot survive then we know we cannot it cannot survive then we know the middle is definitely not our answer the middle is definitely not our answer that's why we have we can that's why we have we can safely change the left to middle plus safely change the left to middle plus one because we know the middle is not one because we know the middle is not the answer the answer and since we're doing the left equals to and since we're doing the left equals to middle plus one here middle plus one here we don't we don't need to do a plus one we don't we don't need to do a plus one here here okay uh okay uh i think we have explained this a few i think we have explained this a few times in my in my videos the reason times in my in my videos the reason being is that being is that if you if you're okay so for example if if you if you're okay so for example if you are trying to find the maximum value you are trying to find the maximum value in that case so this hyper functions in that case so this hyper functions even it is true we're going to do a left even it is true we're going to do a left equals to middle and the right equals to equals to middle and the right equals to middle minus 1. middle minus 1. okay we're going to come into reverse okay we're going to come into reverse but if we're doing the left equals to but if we're doing the left equals to middle middle and if we don't do a plus one here right and if we don't do a plus one here right i mean for the case of 3 and 4 i mean for the case of 3 and 4 the final answer is also 3. so basically the final answer is also 3. so basically we'll end up we'll end up stacking at this as this if statement stacking at this as this if statement forever so that's why forever so that's why if if we're assigning the middle to the if if we're assigning the middle to the left we have to do a plus one left we have to do a plus one okay but in this case we we don't have okay but in this case we we don't have to do it because we're to do it because we're where uh we're using left equals to where uh we're using left equals to middle plus one okay so then middle plus one okay so then we simply return the left we simply return the left now it's how can we implement now it's how can we implement this uh can survive can survive right uh i mean this part is a little bit tricky to implement because the the way we're implementing this we're inside like i said it's a it's another dp because now we have the the initials a house for the night all we need to do is just i we just need to check with this initial uh business initial uh house can the knight find a path to reach the uh basically to rescue the princess okay and okay so to do that i mean we have to initialize the uh our dp here so what's going to be our our answer and since uh to be able to walk through and since uh to be able to walk through to work through at each of the cells to work through at each of the cells here we're gonna collect here we're gonna collect basically we're gonna collect the basically we're gonna collect the maximum maximum health from two directions so that we health from two directions so that we can use can use the max one to be able to get to the the max one to be able to get to the current one since we're current one since we're collecting the the maximum values right collecting the the maximum values right i mean to i mean to to handle the other corner case we have to handle the other corner case we have we we need to initialize all the house to have need to initialize all the house to have the negative the negative maximum value here same thing with the m maximum value here same thing with the m plus one for this one in plus one for this one in range and cool so and cool so same thing for i in range so in this same thing for i in range so in this case we're doing like from top top left from top left so we have to do m plus one for j in range one and plus one okay i mean here it's a little bit tricky because you know why is that because we uh some of the the path is not valid okay so let's say when we add set we have so let's say when we add set we have seven here right let's say we seven here right let's say we we have five we have five here we have five we have five here i mean we can go either go down or i mean we can go either go down or or go right okay but if we go down or go right okay but if we go down if we go down here i mean basically the if we go down here i mean basically the knight knight will i mean will be that so which means will i mean will be that so which means this cell this cell is not a valid path which means when we are at this minus minus 10 here this cell should be treated as an invalid path okay but how can we do that right i mean basically we just to be able to keep to mark this cell to be invalid we just need to make it keep it like an active we just need to keep that this okay so i mean i'm gonna try to uh okay so i mean i'm gonna try to uh write the uh the most common case here write the uh the most common case here right so the most right so the most the most common case is that is this the most common case is that is this right basically max from dp right basically max from dp like i minus 1 like i minus 1 j dpi j minus one okay and then we do a dpi j minus one okay and then we do a plus plus we then we we then we can include the current dungeons value can include the current dungeons value okay okay i minus one and j minus one i minus one and j minus one that's our like state transit state that's our like state transit state transition function here transition function here okay but the problem is this right the okay but the problem is this right the problem is problem is it's like and it's like and let's say for this case right for this let's say for this case right for this one let's say one let's say if this one uh for some of the the cases uh it is smaller or equal than m than empty so it means that okay the the knight will be that right at this cell so for for that one i mean we cannot keep this one at zero or like a negative value right let's say at this moment let's say that the this dp value is minus one okay so minus one means that okay so the knight is that at this cell but if we leave this this minus one to this to this cell here okay and basically it means that the knight can still use this path to to keep going forward right but which is which is not correct if that's the case it's going to lead us because later on because later on let's because later on because later on let's say if the if the the knight is it's say if the if the the knight is it's fine here let's see the knight can fine here let's see the knight can can survive even though it's like can survive even though it's like negative one but it can still use this negative one but it can still use this one one but then the next one is 10 then then but then the next one is 10 then then right if the next one is 10 here okay so right if the next one is 10 here okay so the knight will the knight will will become will become alive again will become will become alive again here because here it will be night here here because here it will be night here and then he can just keep going and go and then he can just keep going and go and then and then in the end he will he will rescue the uh in the end he will he will rescue the uh the princess but which is the princess but which is not right if that's the case right i not right if that's the case right i mean instead of mean instead of instead of seven instead of seven i mean instead of seven instead of seven i mean the knight can be anything the knight the knight can be anything the knight can be like uh can be like uh can even can be two here right because can even can be two here right because as long as he he can reach the uh like a as long as he he can reach the uh like a magic orb to to revive him from from magic orb to to revive him from from death death right he can reach the end which is not right he can reach the end which is not which is not correct which is not correct so to be able to do to fix that right i so to be able to do to fix that right i mean mean we only assign this uh set this dp we only assign this uh set this dp value to a va to a number when it is a value to a va to a number when it is a positive number positive number okay otherwise we keep it uh okay otherwise we keep it uh we keep it like a negative we keep it like a negative max negative number to to mark it as an max negative number to to mark it as an invalid path we need the the base case for this one we need the the base case for this one okay so the base case is this right okay so the base case is this right same thing if the if i equals to 1 same thing if the if i equals to 1 and the j is equal to 1 and the j is equal to 1 and then the the dp of i and then the the dp of i and j will be what is equal to the y to and j will be what is equal to the y to the middle the middle plus the dungeon right i minus one and j plus the dungeon right i minus one and j j minus one okay cool so and in the end in the end we simply we simply return right if the dp we simply return the dp uh m and n if okay so but like like i said right since okay so but like like i said right since we're like checking if the last one is we're like checking if the last one is greater than zero we have to uh greater than zero we have to uh mark those invalid paths so to mark that mark those invalid paths so to mark that uh we need to do we need to use the time uh we need to do we need to use the time values here values here basically every time when we do a time basically every time when we do a time values here we do this right values here we do this right else we do this temp okay and if the temp is greater than zero okay then we do this dp dpi okay equals to 10. otherwise we keep this one as an active value so that in the end this one will be an active value so actually here you know we can do an early termination basically if the if the starting point is an active value here we can simply like break we can simply break the whole loop because we know okay there's no way basically the night that the moment he entered the dungeons he enters the dangers but for before the all the other cases we cannot simply break a stop there because there might be other paths that can lead the knight to the uh to the princess so in the end we check if the if is the middle with the current middle starting house can the knight find a pass okay so yeah i think that's it let's try okay so yeah i think that's it let's try to run the code here okay sir survive oh survive sir survive oh survive survive sorry um too many typos come on all right so this one submit cool so it passed as you guys can see only b is like only five five percent of people why is that so now what's the time complexity
2024-03-21 14:10:20
174
https://i.ytimg.com/vi/L…axresdefault.jpg
LeetCode 174. Dungeon Game
b2IR7Rfwsoc
hello everyone it's me abhinaya so today in this video we're going to solve in this video we're going to solve another another interesting problem from lead code interesting problem from lead code called n queens it's a called n queens it's a half it's a heart problem the problem half it's a heart problem the problem number is 51. number is 51. let's see the question the end queen's let's see the question the end queen's puzzle is the problem of placing n puzzle is the problem of placing n queens on an n into n chessboard such queens on an n into n chessboard such that no two pins attack each other that no two pins attack each other given an integer but an all distinct given an integer but an all distinct solution to the increased process solution to the increased process so in here they have given n is equal so in here they have given n is equal like you know right the queens can move like you know right the queens can move in all four directions we have to place in all four directions we have to place the end queens uh in a way that it the end queens uh in a way that it doesn't attack doesn't attack each other so if you keep here each other so if you keep here like this will not attack this and this like this will not attack this and this cannot cannot attack this and this cannot attack this attack this and this cannot attack this so what we have to do is so what we have to do is if a queen is placed in a position in if a queen is placed in a position in all those four all those four directions another queen should not be directions another queen should not be placed so we have to place a and go into placed so we have to place a and go into the ending the ending so let's see this this problem is so let's see this this problem is actually actually a pretty popular problem it's good to a pretty popular problem it's good to know this problem so know this problem so for that uh first we'll have a result the result array and then we have a board okay it's a 2d array so we'll have both so first i'm initializing everything with one for um and then we are going to go into another function called and that's going to have a board and that's going to have a board and the starting uh row position so and the starting uh row position so first i'm going to start with zero first i'm going to start with zero and then we're going to have three sets and then we're going to have three sets to check for this diagonal one to check for this diagonal one and this diagonal two and for this and this diagonal two and for this position vertical position position vertical position so we're going to have three sets so we're going to have three sets and then at last field with and then at last field with the result so let's see this function board i'm gonna call the board i'm gonna call the the row numbers i and then the row numbers i and then diagonal one two and for that vertical diagonal one two and for that vertical position position so in all these kinds of problem you so in all these kinds of problem you have a base condition right have a base condition right so if i is equal to equal to length of so if i is equal to equal to length of the board that means it the board that means it has gone through all the rows that means has gone through all the rows that means you have done with you have done with one possible solution so one possible solution so for that if i is equal to equal to for that if i is equal to equal to length length [Music] [Music] you're going to pass this ball into you're going to pass this ball into another function i'm going to call that function as uh so now what we're going to do is we're so now what we're going to do is we're going to loop to going to loop to loop through the board right you already loop through the board right you already have idea but we need another have idea but we need another it's a 2d array so we need j to change so to check this uh diagonal uh to get this diagonal we should just add i plus g to get this diagonal we should just subtract j minus i okay so if i plus stable it should not be in the set okay it's not if i plus j is not in set and j minus i is also not in fact not in d2 and the j is not in the vertical set set v then then the place is free we can place the queen there right it's not in d1 and j minus i not in d2 and j not in b if it's not in any of the set there we can place the green so for now i'm going to change it into one and in another function i'm going to change the one into three okay and now we begin now like that now that we passed we now we oh now that we place the queen in that position we can add add i plus j and j minus i and j in those sets right so d1 dot [Music] [Music] now we are going to call this function now we are going to call this function again for i plus 1 for the next again for i plus 1 for the next rows to go into the next row bold i plus 1 b bold i plus 1 b 1 and 2. 1 and 2. now now like now we don't want now now like now we don't want those all those values to go again and those all those values to go again and again so we are clearing those data again so we are clearing those data here [Music] game on the side remove g so now like remove g so now like this will uh this will get all the this will uh this will get all the possible possible possible solutions where we can see that possible solutions where we can see that we can place the queen we can place the queen now like here we have place queen as one now like here we have place queen as one but we need a uh but we need a uh skew and uh dot right so that we're skew and uh dot right so that we're going to change here so it's just looking through the board so it's just looking through the board and changing it and changing it so we have help now we're going to loop so we have help now we're going to loop through and it's a string right so we have and it's a string right so we have [Music] is one that means uh the queen is placed in that position if not uh the queen is not placed in the if not uh the queen is not placed in the position so if position so if you queen has not placed its dot so you queen has not placed its dot so we'll have we'll add we'll have we'll add the dot and we'll into this and we'll add this into this and we'll add this into the result append the heavy and that's it let's run this i hope so this is how we solve this problem so so this is how we solve this problem so if you guys know every other if you guys know every other way to solve this in the comments below way to solve this in the comments below i'll see you guys in my next video until i'll see you guys in my next video until then bye
2024-03-20 10:02:21
51
https://i.ytimg.com/vi_w…c/sddefault.webp
N-Queens | Leetcode-51 | Interview preparation | Day 11